Compare commits

..
96 Commits
Author SHA1 Message Date
qaiu e794b34982 release: v0.4.12 (#309)
Bump the app version for folder pagination (#308) and the Lanzou
folder risk-page fix (#307). The release notes link the early paging
request in #112 and state that 小飞机 was only mock-tested and 蓝奏优享
was not tried on a folder over 60 items.
2026-11-25 09:42:10 +08:00
qaiu 0a631e75ea Merge pull request #308 from qaiu/cursor/dir-pagination-f75b
目录分页:蓝奏 / 小飞机 / 蓝奏优享(含 #307 目录修复)
2026-11-25 09:02:50 +08:00
Cursor Agentandqaiu 72194dddc9 web: scroll-triggered loading, paused after failures; page list.html
list.html loads further pages via /v2/getFileListPage with dedupe,
keeps loaded items on failure and offers retry.

Co-authored-by: qaiu <[email protected]>
2026-11-25 00:56:30 +00:00
Cursor Agentandqaiu 0d5014ad40 api: accept pg as an alias of page for folder listing
Co-authored-by: qaiu <[email protected]>
2026-11-25 00:56:30 +00:00
Cursor Agentandqaiu 1d7836c1bd parser: wait 2s then 5s before retrying a rate-limited 蓝奏 page
zt=4 usually clears within 2s, occasionally needs ~5s. Still two bounded
retries; a page that stays rate-limited fails with a retryable error.

Co-authored-by: qaiu <[email protected]>
2026-11-25 00:56:30 +00:00
Cursor Agentandqaiu 6ed8ae2e28 ci: don't build/publish images on feature branch pushes
branches-ignore '*' does not match branch names containing '/', so
pushing cursor/... branches ran the Docker job and overwrote :latest.
Tag pushes and pull_request runs are unchanged.

Co-authored-by: qaiu <[email protected]>
2026-11-25 00:56:30 +00:00
Cursor Agentandqaiu b5a0155dd0 web: load more for paged folders in pane and tree views
Failed loads keep loaded items and offer retry; stale responses after
navigation are dropped; select-all and folder batch selection warn when
pages remain unloaded.

Co-authored-by: qaiu <[email protected]>
2026-11-25 00:56:30 +00:00
Cursor Agentandqaiu 8f372e5dd0 api: add page/pageCursor to getFileList and /v2/getFileListPage
getFileList without page is unchanged. getFileListPage returns
{list, paged, page, hasMore, nextPage, nextCursor, total, totalPage};
non-paging providers return the full list on page 1 and an empty
page afterwards. page/pageCursor are not appended to share URLs.

Co-authored-by: qaiu <[email protected]>
2026-11-25 00:56:30 +00:00
Cursor Agentandqaiu e9bfe14488 parser: 蓝奏 folder pagination with cursor and rate-limit handling
filemoreajax keeps paging state per t/k token, so the next page is
fetched with the previous page's form (nextCursor). zt=4 "请刷新,重试"
is upstream pacing, not the end: retry the same page twice 2s apart,
then fail with a retryable error. Only zt=2 or a short page ends the
list. Without a cursor, walk at most 6 pages 1.5s apart. Keeps PR307's
mobile-UA folder page and risk-page detection.

Co-authored-by: qaiu <[email protected]>
2026-11-25 00:56:30 +00:00
Cursor Agentandqaiu cbd10962c0 parser: page share/list folders for 小飞机 and 蓝奏优享
offset is a 1-based page number; record total/totalPage as pageInfo.
Default requests still fetch page 1 with limit 60. FjTool now fails
instead of hanging on non-JSON or malformed list items.

Co-authored-by: qaiu <[email protected]>
2026-11-25 00:12:39 +00:00
Cursor Agentandqaiu 2bb66cfc82 Recognize Lanzou folder risk pages instead of calling them expired
Old folder links return a blank off page to desktop Chrome and a real
filemoreajax page to the mobile user agent. Fetch directory pages with
the mobile agent, and report access control when the blank page remains.

Co-authored-by: qaiu <[email protected]>
2026-11-24 23:46:22 +00:00
qaiuandCursor Agent fbfb760b3a Add GitHub issue forms for parse, runtime, and feature reports (#305)
The forms collect the version, disk, and reproduction details that are
actually needed, and tell reporters not to paste tokens or account passwords.

Co-authored-by: Cursor Agent <[email protected]>
2026-11-24 16:29:13 +08:00
qaiuandCursor Agent ef03956944 release: v0.4.11 (#304)
Bump the app version after the Ctfile ALTCHA and Yongshuo password fixes.
The release notes state that anonymous ALTCHA was verified, while the
optional Ctfile v4 login fallback was not.

Co-authored-by: Cursor Agent <[email protected]>
2026-11-24 16:19:56 +08:00
qaiuandCursor Agent 542d246aab Parse Ctfile shares with the new url API and ALTCHA v2 (#303)
* Parse Ctfile shares with the new url API and ALTCHA v2

The legacy getfile.php and getdir.php endpoints now answer every share
with Cloudflare Turnstile. Password-free files and folders use ALTCHA
PBKDF2 instead: solve it off the event loop, reuse access_pass for the
same owner, and fetch the direct link from POST /url/download. Password
shares stay on Turnstile and are reported separately from missing links
and wrong or missing passwords.

Co-authored-by: qaiu <[email protected]>

* Add Ctfile v4 login parsing for password-protected shares

Password shares are blocked by Turnstile on the anonymous web API. When a
refresh token or access token is configured, convert the share to an xtc
link and use the official client list and fetch-url calls. Password-free
shares still use ALTCHA. Tests use short synthetic fixtures only.

Co-authored-by: qaiu <[email protected]>

* Parse password-protected Ctfile shares with anonymous ALTCHA

A password share's first response is often labeled Turnstile, but a fresh
ALTCHA token plus the passcode returns the file. Try that before any login.
Keep the v4 client only as a fallback when Turnstile remains and a token is
configured. Live checks download the sample PDF and a directory zip.

Co-authored-by: qaiu <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
2026-11-24 16:14:43 +08:00
qaiuandCursor Agent feff1b88c1 fix(ys): 修复永硕密码入口页改版与 ys168 重定向验证 (#302)
* fix(ys): parse the new password gate and follow ys168 redirects

Yongshuo password spaces now use an entry page with data-verification-token.
Password verification still posts to /?handler=VerifyPassword, but after a
ys168.com 302 the request must go to the final ysepan.com host. The legacy
RequestVerificationToken script form remains accepted.

Co-authored-by: qaiu <[email protected]>

* fix(ys): report invalid password instead of a bare HTTP 400

VerifyPassword answers a wrong password with HTTP 400 and
code invalid_password. Surface that short message and drop any
token-like text from the failure body.

Co-authored-by: qaiu <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
2026-11-24 16:14:24 +08:00
qaiuandCursor Agent a7d41b0107 Show parsed file details and list Quark and UC as supported (#299)
The home page now shows the filename, size, and disk name after a successful parse, and the supported-disk copy includes Quark and UC. Bump the app version to 0.4.10.

Co-authored-by: Cursor Agent <[email protected]>
2026-11-23 03:02:41 +08:00
qaiuandCursor Agent 24c22fad7f Use a checked SVIP/VIP link or probed H5 file URL for large Quark and UC files (#298)
* Route large Quark and UC files through a checked SVIP/VIP link or a probed H5 file URL.

Files at or below 10MiB keep the existing share download. Larger files use the account direct link only after the member API reports an unexpired SVIP/VIP, and otherwise return a dl-c file URL with the real filename. HTML, playlists, and account cookies are not treated as a public download.

Co-authored-by: qaiu <[email protected]>

* Open Quark and UC browser downloads without a Referer.

The parse result, file list, dialog, and show-file download actions now use a link with referrerpolicy=no-referrer so a click does not send the site Referer that makes the public CDN return 403 HTML.

Co-authored-by: qaiu <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
2026-11-23 02:53:53 +08:00
qaiu a86b26d668 Merge pull request #297 from qaiu/fix/playground-security
修复演练场密码与脚本权限,准备发布 v0.4.9
2026-11-21 12:28:19 +08:00
qq qi 5781100905 Prepare v0.4.9 and align playground editor hints with the sandbox 2026-11-21 04:25:09 +00:00
qq qi 04ba9a0e2c Require an explicit private playground password and restrict parser script engines 2026-11-20 15:08:26 +00:00
qaiu 3825527519 Merge pull request #296 from qaiu/fix/java4shell-base64
fix: 缓解 Java4Shell(CVE-2026-114938)
2026-11-20 20:33:59 +08:00
qaiu 531f431faa Merge pull request #273 from yokinanya/fix/feijipan-share-download
fix(parser): 修复小飞机分享下载失败
2026-11-20 20:32:00 +08:00
qaiu 44b023d919 perf: vectorize bounded Base64 encoding and decoding with scalar fallback 2026-11-20 19:58:07 +08:00
qaiu 5681d3b805 perf: decode Base64 with bounded lookup-table groups 2026-11-20 19:37:04 +08:00
qaiu 8c07c6e657 fix: mitigate Java4Shell in Base64 decoders and containers 2026-11-20 18:29:17 +08:00
yokinanya 25888661ad fix(parser): 处理小飞机下载错误响应解码异常
捕获不支持的编码及响应体超限异常,明确结束解析请求,补充回归测试。
2026-11-16 17:15:49 +08:00
qaiu b6922b152f Merge pull request #287 from qaiu/cursor/update-readme-sponsorship-fa6c
docs: update README sponsorship section
2026-11-04 12:08:33 +08:00
Cursor Agentandqaiu 572c5a61fc docs: show sponsorship links as a row of icons
Replace the Alipay, WeChat, and PayPal bullets with centered brand icons, and keep the intro and Lin Feng Yun sponsor image.

Co-authored-by: qaiu <[email protected]>
2026-11-04 04:02:40 +00:00
Cursor Agentandqaiu dec6cf496f docs: update README sponsorship section
Add Alipay, WeChat, and PayPal sponsorship links, and remove the stray closing tags around the Lin Feng Yun sponsor image.

Co-authored-by: qaiu <[email protected]>
2026-11-04 03:52:01 +00:00
qaiuandCursor Agent 98a043daf9 fix(qk): enter folder shares and clarify 123 local Authorization (#283)
Quark parse stopped when the share root was only a folder and reported
that nothing could be downloaded. Enter subfolders, skip 0-byte
placeholders, and for visitors try a smaller file when Quark returns
23018 instead of transferring without a Cookie.

123 download failures now tell users to configure a local
auths.ye.authorization. Share listings can be read without login, and
hash fragments on 123 URLs are ignored. New URL fixtures use a ref=example
query, not a password-shaped parameter.

Co-authored-by: Cursor Agent <[email protected]>
2026-10-31 07:45:46 +08:00
qaiu 12d0f6bfbb Merge pull request #233 from qaiu/cursor/ye-password-risk-auth-hint-140f
fix: 123 云盘账号密码登录触发验证码/风控时引导配置 Authorization
2026-10-31 07:06:12 +08:00
qaiu 9d2fd09331 Merge branch 'main' into cursor/ye-password-risk-auth-hint-140f 2026-10-31 07:03:25 +08:00
yokinanya d692416a2e fix(parser): 修复小飞机分享下载身份及过期签名
使用分享者 userId 生成下载签名,兼容有效旧目录链接并在下载时刷新时间戳,补充上游错误诊断及回归测试。
2026-10-23 15:50:54 +08:00
qaiu e9be9b3345 Merge pull request #259 from qaiu/fix/iz-auth-fallback
fix(iz): 蓝奏优享登录失败回退免登录 + release 0.4.8
2026-10-14 04:53:24 +08:00
qaiu 6acb774c87 release: 0.4.8 Youxiang auth fallback and configurable XFF 2026-10-14 04:38:00 +08:00
qaiu 511515cae4 fix(iz): 蓝奏优享登录失败回退免登录、TokenCache 多账号、可配置 XFF
- IzTool.parse 预登录失败 recover 后继续免登录解析
- IzTool / IzToolWithAuth 登录或重登失败回退匿名下载(downloadAnonymous)
- IzTool 改用 TokenCache(按 _configId/username 隔离),校验 token 前恢复 appToken 头
- 新增 IzXffHeader:-Dnfd.iz.xff / NFD_IZ_XFF = off(默认)/random/固定IP
2026-10-14 04:38:00 +08:00
Cursor Agentandqaiu 1ab9df7826 fix: guide Authorization when 123 password login hits captcha
123 pan username/password sign-in that returns captcha or risk-control
now fails with a user-facing hint to configure Authorization (Bearer/JWT),
instead of the raw upstream message. Wrong-password and network errors stay
distinct. No captcha solving, QR login, or retries.

Co-authored-by: qaiu <[email protected]>
2026-09-27 22:08:16 +00:00
qaiu ab8b687837 Merge pull request #231 from qaiu/cursor/release-047-9e8b
release: v0.4.7
2026-09-25 16:35:29 +08:00
Cursor Agentandqaiu 7616bf3144 release: 0.4.7 Lanzou host rewrite and apifile ajax
Co-authored-by: qaiu <[email protected]>
2026-09-25 08:34:52 +00:00
qaiu 01d7956de5 Merge pull request #229 from qaiu/cursor/lanzou-skip-wwww-rewrite-d50d
fix(parser): 蓝奏个性域名保留原主机,文件直链走 apifile
2026-09-25 16:33:05 +08:00
Cursor Agentandqaiu 78e53c076e fix(parser): 蓝奏文件 ajax 优先使用页面里的 apifile 绝对地址
个性域名文件页把 ajaxfile.php 写到 apifile.lanzouw.com。相对路径打到页面源站会空响应,直链拿不到。绝对地址优先,apifile 放进文件 ajax 兜底且排在四 w 之前;目录列表仍不走 apifile。

Co-authored-by: qaiu <[email protected]>
2026-09-25 08:27:58 +00:00
Cursor Agentandqaiu 4d985cc96f fix(parser): 蓝奏个性域名不再强制改写到 wwww.lanzoux.com
a.lanzouw.com 的页面请求被改到四个 w 的主机后,部分出口会连接超时。
分享页 GET 保留原主机;ajax/filemore 再按 w1、www、wwww 顺序回退。

Co-authored-by: qaiu <[email protected]>
2026-09-25 06:46:11 +00:00
qaiu 13ccdb8adf 更新 README.md 2026-09-24 06:05:20 +08:00
qaiu ac1afcd35f 更新 README.md 2026-09-24 06:04:37 +08:00
qaiu 0c678a4124 Merge pull request #221 from qaiu/cursor/release-046-b82b
release: v0.4.6
2026-09-18 19:01:51 -07:00
Cursor Agentandqaiu f77800602d release: 0.4.6 tree batch auto-expand and view-switch icons
Co-authored-by: qaiu <[email protected]>
2026-09-19 01:39:46 +00:00
qaiu 79ab829952 Merge pull request #220 from qaiu/cursor/tree-batch-expand-f84e
feat: 文件树批量勾选自动展开 + 视图切换图标 / Tree batch auto-expand and view-switch icons
2026-09-18 18:38:23 -07:00
Cursor Agentandqaiu 2181ef38df fix(web): set tree batch default max depth to 5
Align with VIP: default recursive batch depth is 5 (checked folder = depth 0). Still configurable via batchMaxDepth; warn when remaining folders hit the cap.

Co-authored-by: qaiu <[email protected]>
2026-09-19 01:14:06 +00:00
Cursor Agentandqaiu e09c9f76a7 feat(web): tree batch auto-expand with depth limit and view icons
勾选文件树文件夹时自动展开并懒加载子节点,按最大深度(默认 4,勾选文件夹为第 0 层)递归收集可下载文件;触及上限时中文提示部分文件已跳过。树侧栏顶部增加显眼的批量下载入口。Home/ShowList 窗格与文件树切换增加 Font Awesome 图标。

Co-authored-by: qaiu <[email protected]>
2026-09-19 01:12:33 +00:00
qaiu 7adb938357 更新 README.md 2026-09-18 00:36:05 -07:00
qaiu efb800d88e 更新 README.md 2026-09-18 00:30:44 -07:00
qandCursor 422d5b845b fix: recognize 123pan uid.share links and trim paste input
Clipboard auto-detect now matches {userId}.share.123pan.cn/123pan/{key}, and the share URL field is trimmed on paste and blur. Split web-service compiler args so IDE rebuilds no longer wipe classes.

Co-authored-by: Cursor <[email protected]>
2026-08-18 01:22:47 +08:00
qandCursor 054e9cc1ec fix: harden gzip decode and release 0.4.5
Avoid ZipException when Vert.x already decompressed gzip bodies, keep jackson-databind on the IDE classpath, and show a real build version instead of unknown.

Co-authored-by: Cursor <[email protected]>
2026-08-18 01:00:32 +08:00
qandCursor f3da45bb16 fix(lz): port Lanzou parser to wwww.lanzoux.com flow
Use the new share/ajax/verify pipeline (arg1 retry, regex ajax extract, delayed CDN verify) on the open-source PanBase client, keeping proxy support and complete() for downloadUrl.

Bump version to 0.4.4.

Co-authored-by: Cursor <[email protected]>
2026-08-18 00:25:49 +08:00
qandCursor 273dbae5e7 ci: only publish GitHub releases for v* tags
Agent/feature tags were matching '*' and becoming Latest, which also multiplied auto-generated notes.

Co-authored-by: Cursor <[email protected]>
2026-08-18 00:22:02 +08:00
q e103003b7a Merge branch 'main' of github.com:qaiu/netdisk-fast-download 2026-08-18 00:21:51 +08:00
qandCursor e853365fe4 fix(lz): adapt new Lanzou pages and stop duplicate release notes
Complete the fake jQuery/document sandbox for cookie, location, querySelector and chained APIs, extract ajax params by regex first with JS fallback, and generate GitHub release notes in a single job so matrix OS uploads no longer append What's Changed twice.

Bump version to 0.4.3.

Co-authored-by: Cursor <[email protected]>
2026-08-18 00:21:03 +08:00
qaiu b5f7d9694b 更新 README.md 2026-08-16 21:20:04 +08:00
qaiu f75d9f687b 更新 README.md 2026-08-16 21:18:37 +08:00
qaiu 703bfa3061 Merge pull request #213 from qaiu/claude/fangcloud-share-validity-check-9fzoi6
fix(parser): FangCloud share validity check reads the wrong JSON field
2026-08-13 16:05:23 +08:00
Claude 6c709fde65 fix(parser): fix FangCloud share validity check and h5 share link regex
Root cause confirmed against a live share link: FcTool never actually
checked share validity against the info API — it read a top-level
"is_valid" field that the endpoint doesn't return. The real validity
flags (process.is_closed / process.is_expired) live under "process",
so an invalid share fell through to HTML scraping and surfaced a
confusing "未匹配到文件id(typed_id)" error instead of a clear
"分享已失效" message. parse() now checks share_links/info first and
fails fast with a clear message when the share is closed/expired.

Also widen PanDomainTemplate's FC regex to accept the mobile H5
landing page path (/h5/share/{key}), which previously didn't match
at all.

Updated verify_fangcloud_share.py to reflect the confirmed API
response shape instead of the earlier incorrect guess.
2026-08-13 07:46:29 +00:00
Claude 449fd741ac Add diagnostic script for FangCloud share validity check
FcTool.java's share validity check hits a share_links/info endpoint on
v2.fangcloud.cn that doesn't appear in the project's own captured
traffic (pan-fc.http) or public docs, and its regex in
PanDomainTemplate doesn't match the /h5/share/ path used by mobile
links. This script reproduces both requests against a live share URL
to confirm the root cause before fixing the parser.
2026-08-13 07:29:42 +00:00
qaiu c18b8d80e1 更新 README.md 2026-08-07 09:36:35 +08:00
qaiu 06ba0aff52 Merge pull request #211 from qaiu/copilot/update-readme-to-latest-version
docs: update download URL to latest release v0.4.2
2026-08-05 21:42:39 +08:00
copilot-swe-agent[bot]andqaiu 74e401d99c docs: fix download URL and zip filename for v0.4.2 linux-amd64
Co-authored-by: qaiu <[email protected]>
2026-08-05 13:28:37 +00:00
copilot-swe-agent[bot]andqaiu 4995bca901 docs: update download URL to latest release v0.4.2
Co-authored-by: qaiu <[email protected]>
2026-08-05 13:18:11 +00:00
qaiu 7299fd8762 Merge pull request #207 from qaiu/cursor/ghsa-997r-ssrf-verify-2b8b
fix(security): GHSA-997r SSRF verification + residual hardening
2026-07-26 21:10:39 +08:00
Cursor Agentandqaiu efbadde4ed fix(security): harden GHSA-997r Cloudreve SSRF residual paths
Disable redirect following on CE/Ce4 attacker-controlled requests and stop
echoing upstream response bodies in client-facing JSON errors. Add
assertPublicHost regression coverage for the advisory PoC hosts.

Co-authored-by: qaiu <[email protected]>
2026-07-26 12:05:16 +00:00
qandCursor d1fa787bef fix(uc/qk): improve directory download with cookie, transfer fallback and URL-safe param encoding
- Preserve download cookie for UC/Quark needDownloader flows and disable browser/copy when required
- Quark: share-link first, transfer only on size limit (23018), reuse savedFileCache/search_exit
- Propagate auth to subdirectory parser URLs; switch path params to URL-safe Base64 (no double encode)
- Bump version to 0.4.2

Fixes #205

Co-authored-by: Cursor <[email protected]>
2026-07-26 16:16:51 +08:00
q c282fcb109 Merge branch 'main' into feature/ysepan-parser 2026-07-26 13:20:16 +08:00
qandCursor 4995173de2 feat: add Yongshuo E-pan (ysepan) share parser
Support space shares like https://xxx.ysepan.com/ with password auth,
directory/file listing, and direct download URL construction.

Co-authored-by: Cursor <[email protected]>
2026-07-26 12:37:38 +08:00
qaiu 1c1068beba Merge pull request #206 from qaiu/dependabot/maven/maven-858658338e
chore(deps): bump the maven group across 1 directory with 2 updates
2026-07-26 09:04:56 +08:00
qaiu 4a5240fcbc Merge pull request #203 from qaiu/dependabot/npm_and_yarn/web-front/npm_and_yarn-c42958dede
build(deps): bump axios from 1.16.1 to 1.18.0 in /web-front in the npm_and_yarn group across 1 directory
2026-07-26 08:47:25 +08:00
dependabot[bot] 0f34672e33 chore(deps): bump the maven group across 1 directory with 2 updates
Bumps the maven group with 2 updates in the / directory: [ch.qos.logback:logback-core](https://github.com/qos-ch/logback) and [com.fasterxml.jackson.core:jackson-databind](https://github.com/FasterXML/jackson).


Updates `ch.qos.logback:logback-core` from 1.5.33 to 1.5.34
- [Release notes](https://github.com/qos-ch/logback/releases)
- [Commits](https://github.com/qos-ch/logback/compare/v_1.5.33...v_1.5.34)

Updates `com.fasterxml.jackson.core:jackson-databind` from 2.18.6 to 2.18.9
- [Commits](https://github.com/FasterXML/jackson/commits)

---
updated-dependencies:
- dependency-name: ch.qos.logback:logback-core
  dependency-version: 1.5.34
  dependency-type: direct:production
  dependency-group: maven
- dependency-name: com.fasterxml.jackson.core:jackson-databind
  dependency-version: 2.18.9
  dependency-type: direct:production
  dependency-group: maven
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-07-26 00:46:44 +00:00
qaiu ecd365767a Merge pull request #199 from qaiu/dependabot/maven/maven-6421fd6730
chore(deps): bump ch.qos.logback:logback-core from 1.5.32 to 1.5.33 in the maven group across 1 directory
2026-07-26 08:46:01 +08:00
qaiu f358140974 Update README.md 2026-07-25 11:14:19 +08:00
qaiu 541c21f963 Merge pull request #204 from newbie000652/fix/uc-subdirectory-stoken
fix: UC subdirectory listing fails due to missing stoken parameter
2026-07-25 07:58:14 +08:00
Tra bdd253383d docs: add stoken parameter to /v2/getFileList OpenAPI spec 2026-07-24 20:43:04 +08:00
RuneandCopilot Autofix powered by AI 0fb53d5159 Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-07-24 19:54:22 +08:00
Tra b9ff408bdd fix: UC subdirectory listing fails due to missing stoken parameter
When the frontend requests subdirectory contents for UC drive shares, the
stoken query parameter is mishandled in two places, breaking directory browsing:

1. URLParamUtil.handleTruncatedUrl() does not exclude stoken from the URL
   construction loop. As a result, the stoken value gets appended to the share
   URL (e.g. https://drive.uc.cn/s/xxx?stoken=yyy). The extra query string
   breaks the UC URL regex match in PanDomainTemplate, causing the parser to
   fall back to the default IPanTool.parseFileList() which returns
   "Not implemented yet".

2. ParserApi.getFileList() does not accept stoken as a method parameter and
   does not forward it to ShareLinkInfo.otherParam. Even when the stoken is
   present in the request URL, UcTool.parseFileList() cannot find it and must
   re-authenticate against the UC API — which fails without proper auth cookies.

The fix:
- URLParamUtil: add stoken to the param exclusion list
- ParserApi: add String stoken parameter and put it into otherParam

Both first-level and nested directory listing work correctly after this fix.
2026-07-24 18:04:52 +08:00
qaiu aeb4394cf8 fix GHSA-997r-7xx2-p9x6 2026-07-22 10:25:10 +08:00
dependabot[bot] 8d419d3265 build(deps): bump axios
Bumps the npm_and_yarn group with 1 update in the /web-front directory: [axios](https://github.com/axios/axios).


Updates `axios` from 1.16.1 to 1.18.0
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.16.1...v1.18.0)

---
updated-dependencies:
- dependency-name: axios
  dependency-version: 1.18.0
  dependency-type: direct:production
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-07-21 07:29:38 +00:00
q b70e30796f ci: package fuller jre for native builds 2026-07-19 09:57:31 +08:00
q d3ef521773 fix: support donated auth for 123 directory downloads 2026-07-19 09:39:55 +08:00
q 2969c92d3d build jre 2026-07-19 02:06:33 +08:00
q 2fde421169 chore: bump version to 0.3.9 2026-07-19 01:11:57 +08:00
q 3494271150 chore: bump version to 0.3.8 2026-07-19 00:55:54 +08:00
q 675d930f86 fix: 123网盘捐赠账号无需临时auth参数即可自动生效,修复token前缀与脏数据问题
- 前端: getCurrentPanType() 补全123网盘域名匹配正则(share.123pan.cn等子域名)
- 前端: 临时认证弹窗补充123云盘(YE)选项及提示文案
- 前端: submitDonateAccount() 按当前authType只提交相关字段,避免切换认证方式后
  残留的用户名/密码脏数据被一并提交
- 后端: URLParamUtil.addParam() 不再无条件用静态yml配置覆盖已生效的临时认证/
  自动捐赠账号回退(增加 __TEMP_AUTH_ADDED 判断)
- 后端: CacheServiceImpl 新增 applyDonatedAccountFallback(),请求未带auth参数
  且无静态配置时自动从捐赠账号池随机取一个可用账号使用,并在解析失败时记录/
  自动禁用失败账号
- 后端: DbServiceImpl.getRandomDonatedAccount() 对非password类型账号强制丢弃
  历史遗留的username/password字段,避免被误当账号密码登录
- 解析器: Ye2Tool 清理token/authorization前缀中的"Bearer ",避免拼接成
  'Bearer Bearer xxx' 导致123接口返回 tokenstring should not contain bearer

已通过本地实测验证: 捐赠123账号后,不带auth参数直接请求
/json/parser?url=https://1815268665.share.123pan.cn/123pan/iaKtVv-r4aCd
可正常返回200及直链
2026-07-18 23:21:56 +08:00
q 5e20ed5050 fix: 123网盘(YE)支持authorization别名配置并修复auth临时参数登录被覆盖问题, 更新README认证说明, bump version to 0.3.7
引用 #201 #198 #116
说明: 123解析仅限于本地部署(可Windows一键运行 run.bat),公共/云端服务因风控限制不保证可用
2026-07-18 12:28:00 +08:00
qaiu 91f4fcaa76 更新 README.md
oosmetrics不可用
2026-07-11 06:28:53 +08:00
qaiu 0754fe20f1 更新 README.md 2026-07-10 16:41:58 +08:00
qaiu 034fd20d3b 更新 README.md 2026-07-10 16:41:06 +08:00
dependabot[bot] 363c603bbb chore(deps): bump ch.qos.logback:logback-core
Bumps the maven group with 1 update in the / directory: [ch.qos.logback:logback-core](https://github.com/qos-ch/logback).


Updates `ch.qos.logback:logback-core` from 1.5.32 to 1.5.33
- [Release notes](https://github.com/qos-ch/logback/releases)
- [Commits](https://github.com/qos-ch/logback/compare/v_1.5.32...v_1.5.33)

---
updated-dependencies:
- dependency-name: ch.qos.logback:logback-core
  dependency-version: 1.5.33
  dependency-type: direct:production
  dependency-group: maven
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-07-06 02:09:01 +00:00
q 24bf98bca9 fix: support 123pan redirected share links 2026-07-06 08:50:18 +08:00
qaiu 275f6b9e6d 更新 README.md 2026-06-23 17:10:09 +08:00
qaiu 5db9e422f4 更新 README.md 2026-06-11 12:03:44 +08:00
134 changed files with 16465 additions and 2809 deletions

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: 使用文档
url: https://nfd-parser.github.io/
about: 部署、接口和配置说明
- name: 已发布版本
url: https://github.com/qaiu/netdisk-fast-download/releases
about: 先看最新版本和更新说明,再反馈旧版本里已经修过的问题
+40
View File
@@ -0,0 +1,40 @@
name: 功能建议
description: 新功能或改进建议。不需要填写报错、日志或分享链接。
title: "[建议] "
labels:
- enhancement
body:
- type: markdown
attributes:
value: |
这里只讨论建议。解析失败或程序跑不起来,请分别使用对应模板。
如果要举例,只用可公开的测试分享,不要附带账号、令牌或私人文件。
- type: checkboxes
id: checks
attributes:
label: 提交前
options:
- label: 我查过现有 issue,没有找到相同建议
required: true
- type: textarea
id: problem
attributes:
label: 想解决的问题
placeholder: 现在做什么不方便
validations:
required: true
- type: textarea
id: proposal
attributes:
label: 建议怎么做
placeholder: 希望增加或改变什么
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: 还可以怎么做
description: 没有就留空。
validations:
required: false
+157
View File
@@ -0,0 +1,157 @@
name: 解析失败
description: 某个分享链接解析失败、列目录失败,或直链无法下载
title: "[解析失败] "
labels:
- bug
body:
- type: markdown
attributes:
value: |
只提交可以公开的测试分享。私人文件、含个人信息的分享不要发到这里。
不要粘贴 Cookie、Authorization、refresh_token、access token、网盘账号密码、后台密码,或未打码的配置。提取码、访问密码和账号密码不是一回事:下面只接受分享本身的提取码或访问密码。
- type: checkboxes
id: checks
attributes:
label: 提交前
options:
- label: 我查过现有 issue,没有找到相同问题
required: true
- label: 我看过当前版本和更新说明,这不是已经修好的问题
required: true
- label: 分享可以公开,且没有附带令牌、Cookie、账号密码或未脱敏配置
required: true
- type: input
id: version
attributes:
label: 版本号
description: 页面上的版本,或发布包名里的版本,例如 0.4.12。
placeholder: "0.4.12"
validations:
required: true
- type: dropdown
id: pan
attributes:
label: 网盘类型
options:
- 蓝奏云
- 蓝奏云优享
- 城通网盘
- 永硕 E 盘
- 123云盘
- 夸克网盘
- UC网盘
- 小飞机盘
- 其他(在现象里补充名称)
validations:
required: true
- type: dropdown
id: deploy
attributes:
label: 部署方式
options:
- 本机发布包
- Docker
- 自行编译
- 公共站点
- 其他
validations:
required: true
- type: dropdown
id: kind
attributes:
label: 分享内容
options:
- 单文件
- 目录
- 不确定
validations:
required: true
- type: dropdown
id: access
attributes:
label: 分享是否带密码
description: 提取码是分享链接自带的短码。不要填写网盘登录密码。
options:
- 无密码
- 只有提取码
- 有访问密码
- 不确定
validations:
required: true
- type: input
id: passcode
attributes:
label: 提取码或访问密码
description: 没有就留空。这里不是账号密码。
placeholder: "例如 abcd"
validations:
required: false
- type: input
id: share-url
attributes:
label: 可公开的完整分享链接
description: 用专门准备的测试分享。没有可公开链接时留空,并在下一项说明原因。
placeholder: "https://"
validations:
required: false
- type: textarea
id: no-share-reason
attributes:
label: 不能提供测试分享的原因
description: 已经填写链接就留空。
placeholder: 例如分享含私人文件,只能描述现象
validations:
required: false
- type: checkboxes
id: share-or-reason
attributes:
label: 链接
options:
- label: 我填写了可公开的完整分享链接,或已经说明不能提供的原因
required: true
- type: dropdown
id: official
attributes:
label: 官方网页是否可用
options:
- 可以打开,并且能下载
- 可以打开,但不能下载
- 打不开或提示失效
- 还没在官方网页试过
validations:
required: true
- type: textarea
id: expected
attributes:
label: 预期结果
placeholder: 应解析出直链,或列出目录中的文件
validations:
required: true
- type: textarea
id: actual
attributes:
label: 实际结果
description: 写页面或接口返回的原文。不要贴令牌。
placeholder: 例如提示分享不存在,或直链返回 403
validations:
required: true
- type: textarea
id: steps
attributes:
label: 复现步骤
placeholder: |
1. 使用上述版本和部署方式
2. 解析这个分享
3. 看到上述结果
validations:
required: true
- type: textarea
id: logs
attributes:
label: 脱敏后的报错日志
description: 没有日志就写「无」。删除 Cookie、Authorization、token、密码和未脱敏配置后再粘贴。
render: shell
placeholder: 无
validations:
required: true
+84
View File
@@ -0,0 +1,84 @@
name: 部署或运行问题
description: 程序无法启动、页面打不开、配置或运行报错。不是某一个分享解析失败。
title: "[运行问题] "
labels:
- bug
body:
- type: markdown
attributes:
value: |
单个分享解析失败请改用「解析失败」。
不要粘贴 Cookie、Authorization、refresh_token、access token、网盘或后台密码、个人信息,以及未打码的配置。
- type: checkboxes
id: checks
attributes:
label: 提交前
options:
- label: 我查过现有 issue,没有找到相同问题
required: true
- label: 我看过当前版本和更新说明
required: true
- label: 日志和配置已经去掉令牌、密码和个人信息
required: true
- type: input
id: version
attributes:
label: 版本号
description: 例如 0.4.12。不确定就写获取方式。
placeholder: "0.4.12"
validations:
required: true
- type: dropdown
id: deploy
attributes:
label: 部署方式
options:
- 本机发布包(Linux)
- 本机发布包(Windows)
- Docker
- 自行编译
- 其他
validations:
required: true
- type: input
id: environment
attributes:
label: 系统环境
description: 操作系统、架构,以及是否用了代理。没有就写「未记录」。
placeholder: "例如 Ubuntu 22.04 x86_64"
validations:
required: false
- type: textarea
id: expected
attributes:
label: 预期结果
placeholder: 服务应正常启动,页面可以打开
validations:
required: true
- type: textarea
id: actual
attributes:
label: 实际结果
placeholder: 启动后立即退出,或页面无法访问
validations:
required: true
- type: textarea
id: steps
attributes:
label: 复现步骤
placeholder: |
1. 下载并解压对应版本
2. 按文档启动
3. 看到上述结果
validations:
required: true
- type: textarea
id: logs
attributes:
label: 脱敏后的报错日志
description: 没有日志就写「无」。不要包含令牌、密码或完整私有配置。
render: shell
placeholder: 无
validations:
required: true
+25
View File
@@ -0,0 +1,25 @@
## 更新内容
目录列表支持分页了。之前蓝奏云目录只返回前 50 个文件,小飞机盘和蓝奏云优享只返回前 60 个。早先的分页需求见 https://github.com/qaiu/netdisk-fast-download/issues/112 。
- 目录分页(#308):
- 蓝奏云:按页读取 `filemoreajax`,每页 50 个。只有 `zt=2`(翻过最后一页)或不足 50 个的页才算结束。`zt=4`「请刷新,重试0」视为限流,同一页等 2 秒、再等 5 秒重试;仍失败就返回可重试的错误,不当作最后一页。每页返回 `nextCursor`,下一页沿用同一组翻页参数。不带游标时最多直接请求到第 6 页。
- 小飞机盘、蓝奏云优享:`offset` 作为页码,每页 60 个,由 `totalPage` / `total` 判断是否还有下一页。
- 新接口 `/v2/getFileListPage` 返回 `list`、`hasMore`、`nextPage`、`nextCursor`、`total`、`totalPage`。`/v2/getFileList` 也接受 `page`(或 `pg`)和 `pageCursor`。不带页码时返回结构和以前一样。不支持分页的网盘请求第 2 页及以后时返回空页。
- 前端:目录面板和树形视图有「加载更多」,滚动到底也会自动加载下一页。已加载的文件会保留,加载失败时显示错误并停止自动加载,点击可重试。`list.html` 同样支持。
- 蓝奏云目录风控页(#307):目录分享页改用移动端 UA 请求,文件页仍用桌面 UA。如果仍返回空白风控页,提示「访问风控,不能据此判断分享已失效」,不再报成分享已失效。
- 新增 Issue 表单:解析失败、运行问题、功能建议(#305)。
## 实测范围
- 蓝奏云 `pan.lanzoui.com/b66477`:连续翻完 93 页,共 4598 个文件,没有重复,最后一页 9 个且 `hasMore=false`。实测遇到 `zt=4` 时,2 秒后重试成功。第 2 页的文件可以下载。
- 蓝奏云带密码目录 `moteam.lanzoum.com/b00yaejvte`(密码 `1234`):第 1 页 7 个且没有下一页,第 2 页为空。不带页码的旧接口仍返回 7 个。
- 蓝奏云优享:用真实小目录、把每页条数临时设为 1 来验证。`offset` 是从 1 开始的页码,`total` / `totalPage` 正确,翻过最后一页为空。
- 夸克、城通:目录列表和以前一样,请求第 2 页返回空页。
## 限制
- 小飞机盘没有可用的真实目录样本,只做了本地模拟测试(与蓝奏云优享是同一套接口)。
- 蓝奏云优享没有实测超过 60 个文件的大目录。
- 蓝奏云不带游标直接请求第 7 页及以后会提示需要游标,请按 `nextCursor` 顺序翻页。
- 风控页提示只能说明这次请求被拦截,不代表分享一定有效。
+55 -30
View File
@@ -8,9 +8,10 @@ on:
workflow_dispatch:
push:
tags:
- '*'
- 'v*'
# '*' 不匹配含 / 的分支名(如 cursor/xxx),会让功能分支推送也发布 :latest 镜像
branches-ignore:
- '*'
- '**'
paths-ignore:
- 'bin/**'
- '.github/**'
@@ -52,6 +53,24 @@ jobs:
- name: Maven 编译打包
run: mvn -B package -DskipTests --file pom.xml
- name: Base64 兼容性回归测试
if: github.event_name == 'pull_request'
run: >-
mvn -B test -DskipTests=false
-Dtest=Base64DecoderTest,HttpProxyBase64Test,Base64CompatibilityTest
-Dsurefire.failIfNoSpecifiedTests=false
-DargLine=-XX:-UseBASE64Intrinsics
--file pom.xml
- name: Base64 SIMD 兼容性回归测试
if: github.event_name == 'pull_request'
run: >-
mvn -B test -DskipTests=false
-Dtest=Base64DecoderTest,HttpProxyBase64Test,Base64CompatibilityTest
-Dsurefire.failIfNoSpecifiedTests=false
"-DargLine=--add-modules=jdk.incubator.vector -XX:-UseBASE64Intrinsics -Dnfd.test.requireVector=true"
--file pom.xml
- name: 更新依赖图谱
uses: advanced-security/maven-dependency-submission-action@v3
if: github.event_name != 'pull_request'
@@ -158,37 +177,19 @@ jobs:
path: web-service/target/package
# ============================================================
# jdeps 分析 → 确定所需 JDK 模块
# 选择 JDK 模块
# ============================================================
- name: 分析所需 JDK 模块(jdeps)
- name: 选择完整 JDK 模块集合
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
# 123 网盘/自定义 JS 解析器会通过 javax.script、Nashorn 和 SPI/反射加载模块,
# jdeps 无法稳定识别这些运行时依赖。这里优先保证原生包可运行,使用完整
# JDK 模块集合生成运行时,避免 Windows 精简 JRE 缺 java.scripting/jdk.dynalink 等模块。
printf 'JDK_MODULES=ALL-MODULE-PATH\n' >> $GITHUB_ENV
# ============================================================
# jlink 生成精简 JRE
# jlink 生成完整模块 JRE
# ============================================================
- name: 生成精简 JRE(jlink)
- name: 生成完整模块 JRE(jlink)
run: |
jlink \
--module-path "$JAVA_HOME/jmods" \
@@ -215,6 +216,11 @@ jobs:
ls -la "$JRE_BIN"/*.dll 2>/dev/null || echo "(无 .dll 文件)"
fi
echo "=== 关键 JDK 模块校验 ==="
"native-package/netdisk-fast-download/jre/bin/java" --list-modules | grep -q '^java.scripting@'
"native-package/netdisk-fast-download/jre/bin/java" --list-modules | grep -q '^jdk.dynalink@'
"native-package/netdisk-fast-download/jre/bin/java" --list-modules | grep -q '^jdk.unsupported@'
# ============================================================
# 组装包目录
# ============================================================
@@ -275,9 +281,28 @@ jobs:
name: ${{ matrix.artifact-name }}
path: ${{ matrix.artifact-name }}.zip
- name: 上传到 Release
# ================================================================
# 阶段三:创建 GitHub Release(只跑一次,避免矩阵任务重复拼接更新日志)
# ================================================================
publish-release:
name: 发布 GitHub Release
needs: native-package
if: github.event_name != 'pull_request' && github.ref_type == 'tag'
runs-on: ubuntu-latest
steps:
- name: 下载原生安装包
uses: actions/download-artifact@v4
with:
pattern: netdisk-fast-download-*
merge-multiple: true
- name: 创建 Release
uses: softprops/action-gh-release@v2
with:
files: ${{ matrix.artifact-name }}.zip
files: |
netdisk-fast-download-linux-amd64.zip
netdisk-fast-download-windows-amd64.zip
tag_name: ${{ github.ref_name }}
body_path: .github/release-notes.md
generate_release_notes: true
fail_on_unmatched_files: true
+2 -1
View File
@@ -1,4 +1,5 @@
FROM eclipse-temurin:17-jre
ARG JAVA_RUNTIME_IMAGE=eclipse-temurin:17-jre
FROM ${JAVA_RUNTIME_IMAGE}
WORKDIR /app
+137 -56
View File
@@ -6,8 +6,10 @@ QQ交流群:1017480890
<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://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://github.com/QAIU/netdisk-fast-download">
<img src="https://img.shields.io/github/stars/QAIU/netdisk-fast-download?style=flat&logo=github" alt="GitHub Stars">
</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>
<a href="https://oosmetrics.com/repo/qaiu/netdisk-fast-download"><img src="https://api.oosmetrics.com/api/v1/badge/achievement/826aa27a-6e59-4de5-b7fa-cd189f484035.svg"></a>
<p align="center">
<a href="https://trendshift.io/repositories/12101" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12101" alt="qaiu%2Fnetdisk-fast-download | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
</p>
@@ -16,13 +18,11 @@ QQ交流群:1017480890
![alt text](web-front/img/image.png)
## 国内镜像
本项目同步托管于 **AtomGit**,国内访问更流畅:👉 [https://atomgit.com/QAIU/netdisk-fast-download](https://atomgit.com/QAIU/netdisk-fast-download)
> 本平台所有音乐解析工具不再维护,请移步[Sonder播放器](https://sodecode.qaiu.top)
> 需要百度、迅雷的完整支持请使用[专业版](https://189.qaiu.top)。夸克网盘、UC网盘已包含在开源版。
## 介绍
> netdisk-fast-download网盘直链解析可以把云盘分享链接转为直链,可广泛应用于各类下载站,资源站,个人博客,图床,APP下载更新,视频点播等领域。支持市面各大主流云盘的文件分享以及文件夹分享链接,已支持蓝奏云/蓝奏云优享/移动云云空间/小飞机盘/亿方云/123云盘/Cloudreve等,支持加密分享,以及部分网盘文件夹分享。
> netdisk-fast-download网盘直链解析可以把云盘分享链接转为直链,可广泛应用于各类下载站,资源站,个人博客,图床,APP下载更新,视频点播等领域。支持市面各大主流云盘的文件分享以及文件夹分享链接,已支持蓝奏云/蓝奏云优享/移动云云空间/小飞机盘/亿方云/123云盘/夸克网盘/UC网盘/永硕E盘/Cloudreve等,支持加密分享,以及部分网盘文件夹分享。
[官方文档](https://nfd-parser.github.io/)
[API接入](https://nfdparser.apifox.cn/)
@@ -30,25 +30,31 @@ QQ交流群:1017480890
[公益解析,lz0站](https://lz0.qaiu.top)
[专业版](https://189.qaiu.top)
## 快速开始
命令行下载分享文件:
```shell
curl -LOJ "https://lz.qaiu.top/parser?url=https://share.feijipan.com/s/Tk1F2kGQ&pwd=1234"
```
或者使用wget:
```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%2Fshare.feijipan.com%2Fs%2FTk1F2kGQ&name=bilibili.mp4&ext=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%2Fshare.feijipan.com%2Fs%2FTk1F2kGQ&name=bilibili.mp4&ext=mp4
以带提取码的分享链接为例(提取码 `1234`),链接中含 `#`、`&`,作为 `url` 参数传入前必须做 URL 编码:
`https://www.ecpan.cn/web/#/yunpanProxy?path=%2F%23%2Fdrive%2Foutside&data=70017ece572737b12b30709b7f029308eJD0&isShare=1`
**命令行下载**
```shell
# curl
curl -LOJ "https://lz.qaiu.top/parser?url=https%3A%2F%2Fwww.ecpan.cn%2Fweb%2F%23%2FyunpanProxy%3Fpath%3D%252F%2523%252Fdrive%252Foutside%26data%3D70017ece572737b12b30709b7f029308eJD0%26isShare%3D1&pwd=1234"
# wget
wget -O v01 "https://lz.qaiu.top/parser?url=https%3A%2F%2Fwww.ecpan.cn%2Fweb%2F%23%2FyunpanProxy%3Fpath%3D%252F%2523%252Fdrive%252Foutside%26data%3D70017ece572737b12b30709b7f029308eJD0%26isShare%3D1&pwd=1234"
```
**短链方式**(key 取分享链接的 `data` 参数,提取码用 `@` 拼接)
| 用途 | 地址 |
| --- | --- |
| 下载 | `https://lz.qaiu.top/ec/70017ece572737b12b30709b7f029308eJD0@1234` |
| 在线预览 | [点击访问](https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.top%2Fec%2F70017ece572737b12b30709b7f029308eJD0%401234&name=v01&ext=mp4) |
> 无提取码时去掉 `&pwd=1234` / `@1234` 即可;预览页 `src` 需编码(`@` → `%40`),用短链可避免二次编码。
**解析器模块文档:** [parser/README.md](parser/README.md)
**JavaScript解析器文档:** [JavaScript解析器开发指南](parser/doc/JAVASCRIPT_PARSER_GUIDE.md) | [自定义解析器扩展指南](parser/doc/CUSTOM_PARSER_GUIDE.md) | [快速开始](parser/doc/CUSTOM_PARSER_QUICKSTART.md)
@@ -58,7 +64,7 @@ https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.
**注意⚠️小飞机解析有IP限制,多数云服务商的大陆IP会被拦截(可以自行配置代理),和本程序无关**
**注意⚠️收到很多用户反馈,小飞机近期封号频繁,请尽可能选择其他网盘分享**
**注意⚠️请不要过度依赖 lz.qaiu.top,建议本地搭建或者云服务器自行搭建。请求量过多的话服务器可能会被云盘厂商限制,遇到解析失败的分享链接不要着急提issues,请先检查分享是否有效。**
**注意⚠️请不要过度依赖 lz.qaiu.top,建议本地搭建或者云服务器自行搭建。请求量过多的话服务器可能会被云盘厂商限制,遇到解析失败的分享链接不要着急提 issues,请先检查分享是否有效。**反馈时使用 [问题模板](https://github.com/qaiu/netdisk-fast-download/issues/new/choose),只提供可公开的测试分享,不要粘贴 Cookie、令牌或账号密码。
## 网盘支持情况:
> 20230824 123云盘解析大文件(>100MB)失效,需要登录
@@ -71,13 +77,16 @@ https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.
- [移动云云空间-ec](https://www.ecpan.cn/web)
- [小飞机网盘-fj](https://www.feijipan.com/)
- [亿方云-fc](https://www.fangcloud.com/)
- [123云盘-ye](https://www.123pan.com/)
- [123云盘-ye](https://www.123pan.com/) ⚠️仅建议本地部署使用。公共云解析没有共享 123 账号;下载返回 5112 / 请登录后下载时,在本机配置 `auths.ye.authorization`(Windows 可直接用 run.bat)
- ~[115网盘(失效)-p115](https://115.com/)~
- [文叔叔-ws](https://www.wenshushu.cn/)
- [夸克网盘-qk](https://pan.quark.cn/)
- [UC网盘-uc](https://fast.uc.cn/)
- [联想乐云-le](https://lecloud.lenovo.com/)
- [QQ邮箱云盘-qqw](https://mail.qq.com/)
- [QQ闪传-qqsc](https://nutty.qq.com/nutty/ssr/26797.html)
- [城通网盘-ct](https://www.ctfile.com)
- [永硕E盘-ys](https://www.ysepan.com/)(空间分享,如 `https://xxx.ysepan.com/`,密码为空间访问密码;多文件请用文件列表接口)
- [网易云音乐分享链接-mnes](https://music.163.com)
- [酷狗音乐分享链接-mkgs](https://www.kugou.com)
- [酷我音乐分享链接-mkws](https://kuwo.cn)
@@ -94,9 +103,9 @@ https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.
- Dropbox-pdp
- iCloud-pic
### 专业版提供
- 迅雷网盘-xl
- [夸克云盘-qk](https://pan.quark.cn/)
- [UC云盘-uc](https://fast.uc.cn/)
- 百度网盘开放平台-bd
- 迅雷云盘开放平台-xl
- [光鸭云盘开放平台-gy](https://www.guangyapan.com)
- [移动云盘-p139](https://yun.139.com/)
- [联通云盘-pwo](https://pan.wo.cn/)
- [天翼云盘-p189](https://cloud.189.cn/)
@@ -134,6 +143,7 @@ GET /json/parser?url={分享链接}&pwd={密码}
```
GET /json/{网盘标识}/{分享key}@{密码}
```
注意: 移动云云空间的 `分享key` 取分享链接中的 `data` 参数值
#### 3. 文件夹解析(v0.1.8fixed3+)
@@ -150,7 +160,7 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
### 认证参数(v0.2.1+)
[可以使用在线认证参数加密](https://qaiu.top/nfd-auth.html)
部分网盘(如夸克、UC)需要登录后的 Cookie 才能解析和下载。可通过 `auth` 参数传递认证信息:
部分网盘需要登录后的 Cookie 或 Authorization 才能下载。可通过 `auth` 参数传递认证信息:
**参数格式**:`auth` 参数值为 AES 加密后的 JSON 字符串,经过 Base64 编码和 URL 编码
@@ -174,10 +184,11 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
**网盘认证要求**:
| 网盘 | 认证要求 | 说明 |
|------|---------|------|
| 夸克网盘(QK) | **必须** | 必须配置 Cookie 才能解析 |
| UC网盘(UC) | **必须** | 必须配置 Cookie 才能解析 |
| 夸克网盘(QK) | 不超过 10MiB 可走原解析 | 不大于 `10 * 1024 * 1024` 字节(含等于该值)保持原来的分享解析。更大的文件仅在会员接口确认未过期 SVIP/VIP 时使用该账号直链;否则使用探测通过的 H5 文件地址并附上真实文件名。普通或过期 Cookie 不算会员 |
| UC网盘(UC) | **不能免登录** | 小文件仍要 Cookie。超过 10MiB 时同样只认未过期 SVIP/VIP 的账号直链;没有时才尝试 H5 文件地址。H5 没有可下载文件就返回明确错误,不会把 UC 当成免登录 |
| 小飞机网盘(FJ) | 可选 | 大文件(>100MB)需要认证 |
| 蓝奏优享(IZ) | 可选 | 大文件需要认证 |
| 123网盘(YE) | 下载通常需要 | 分享列表经常可以不登录读取。下载接口常见 5112 / 请登录后下载 / 您需要注册登录或付费后下载,请在**本机**配置 `auths.ye.authorization`(与 `token` 等价)或账号密码。公共云解析没有共享 123 账号。约 10MB 小文件有时可以直链,大文件和风控必须用你自己的账号。短链:`ye:分享key@提取码`;`#` 片段会去掉;`yun.123pan.com`、`www.123pan.com`、`*.share.123pan.cn` 同一类 |
**使用示例**:
```
@@ -198,10 +209,41 @@ GET /parser?url={分享链接}&pwd={密码}&auth={加密后的认证参数}
- 目的:防止客户端伪造失败计数请求
- 建议:使用高强度随机字符串,且不要与 `authEncryptKey` 相同
### 特殊说明
#### `auth` 临时认证参数 与 `auths` 静态配置认证 的区别
- 移动云云空间的 `分享key` 取分享链接中的 `data` 参数值
- 移动云云空间、小飞机网盘的加密分享可忽略密码参数
本项目存在两种互相独立的认证配置方式,作用范围不同,不要混淆:
| 方式 | 配置位置 | 生效范围 | 适用场景 |
|------|---------|---------|---------|
| `auth` 临时认证参数 | 请求 URL 上的 `auth` 查询参数 | **仅当次请求**,优先级高于 app-dev.yml 中的静态配置 | 调用方按用户临时提供的账号/Cookie/token 解析,不同请求可携带不同认证信息 |
| `auths` 静态配置认证 | `app-dev.yml` 的 `auths.<网盘标识>` 节点 | **服务端长期生效**,所有未携带 `auth` 参数的请求都会复用 | 部署方自己长期配置一份账号,供所有请求默认使用 |
以 123网盘(`ye`)为例,`app-dev.yml` 中支持以下几种写法(三选一即可):
```yaml
auths:
ye:
username: 你的123网盘账号
password: 你的123网盘密码
```
```yaml
auths:
ye:
token: 已登录后获取的 Authorization/AccessToken
```
```yaml
auths:
ye:
authorization: 已登录后获取的 Authorization/AccessToken # 与 token 等价,二选一
```
> ⚠️ 注意:YAML 中 key 后面不写值(如 `authorization:` 空着)等同于没配置,不会生效,必须填入真实的账号密码或 token 内容。
>
> 若 123 云盘账号密码登录触发验证码或风控,解析会直接失败并提示改用 Authorization,不会尝试验证码。请改填上面的 `authorization` / `token`(浏览器 localStorage 的 `authorToken`,或请求头 `authorization` / Cookie `sso-token` 里的 JWT)。
>
> 公共解析站(例如别人搭的在线解析)不能替你登录 123。看到「请登录后下载」「5112」「您需要注册登录或付费后下载」时,把服务跑在自己的机器上并填入自己的 Authorization。这是 123 的登录和风控要求。链接写法:`/d/ye/分享key@提取码`;浏览器地址栏里 `#` 后面的片段不参与解析;`yun.123pan.com` 与 `www.123pan.com`、`数字.share.123pan.cn` 是同一种分享。
如果只是临时调用一次,不想改动服务端配置,也可以用上面提到的 `auth` 参数临时传递(`authType` 可选 `password`/`accesstoken`/`authorization`),无需重启服务,仅本次请求生效。
### 示例
@@ -278,9 +320,12 @@ json返回数据格式示例:
"timestamp": 1736489219402
}
```
#### 3. 文件夹解析(仅支持蓝奏云/蓝奏优享/小飞机网盘)
#### 3. 文件夹解析(支持蓝奏云/蓝奏优享/小飞机/永硕E盘等)
/v2/getFileList?url=分享链接&pwd=分享密码
永硕E盘(`ys`)空间链接先返回目录列表,再带 `dirId` 获取目录内文件:
`/v2/getFileList?url=https://xxx.ysepan.com/&pwd=空间密码&dirId=目录编号`
```json
{
"code": 200,
@@ -334,13 +379,19 @@ json返回数据格式示例:
| 移动云云空间(个人版) | √ | √(密码可忽略) | 5G(个人) | 不限大小 |
| 小飞机网盘 | √ | √ | 10G | 不限大小 |
| 360亿方云 | √ | √ | 100G(须实名) | 不限大小 |
| 123云盘 | √ | √ | 2T | 100G(>100M需要登录) |
| 123云盘 | 小文件有时可以 | √ | 2T | 大文件/风控需要本机登录 |
| 文叔叔 | √ | √ | 10G | 5GB |
| 永硕E盘 | √ | √(空间密码) | 视套餐 | 视套餐 |
| WPS云文档 | √ | X | 5G(免费) | 10M(免费)/2G(会员) |
| 夸克网盘 | x | √ | 10G | 不限大小 |
| UC网盘 | x | √ | 10G | 不限大小 |
| 夸克网盘 | ≤10MiB 原解析 | √ | 10G | 更大文件要有效 SVIP/VIP,或可用的 H5 文件地址 |
| UC网盘 | x | √ | 10G | 不能免登录;大文件规则同夸克 |
| 飞书云盘 | √ | X | 15G | 不限大小 |
免登录边界(阈值由网盘决定,不是本项目写死的):
- **夸克 / UC**:单文件体积阈值是 `10 * 1024 * 1024` 字节(10MiB)。小于或等于该值保持原来的解析。严格大于该值时,先请求会员接口,只把 `member_type` 为 `SUPER_VIP`、`EXP_SVIP`、`Z_VIP`、`VIP`、`EXP_VIP` 且 `exp_at` 仍在未来的账号当作有效 SVIP/VIP,并走原来的账号直链。缺少档位、普通账号、已过期或只有 Cookie 都不会当成会员。没有有效会员时,才使用 H5 预览返回的 `https://dl-c-*.drive.quark.cn` 或 `https://dl-c-*.drive.uc.cn` 文件地址,并加上真实 `filename`(含中文)。预览网页、HTML、JSON、m3u8 不会当作下载成功。UC 不能免登录。目录列表不变。百度大约 100MB 以内有直链,属于专业版,这次没有改解析器。
- **123**:分享目录经常可以不登录看。下载则经常要登录。请本机配置 Authorization,不要依赖公共云解析的共享账号。约 10MB 的小文件有时能直链。
# 打包部署
## JDK下载(lz.qaiu.top提供直链云解析服务)
@@ -419,8 +470,8 @@ 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
unzip netdisk-fast-download-bin.zip
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.12/netdisk-fast-download-linux-amd64.zip
unzip netdisk-fast-download.zip
cd netdisk-fast-download
bash service-install.sh
```
@@ -476,7 +527,7 @@ nfd-proxy搭建http代理服务器
参考https://github.com/nfd-parser/nfd-proxy
### 认证信息配置说明
部分网盘(如123)解析大文件时需要登录认证,可以在配置文件中添加认证信息。
夸克不超过 10MiB 可以不登录;更大的文件要本机未过期的 SVIP/VIP Cookie,或上游确实返回了可下载的 H5 文件地址。UC 不能免登录。123 的下载在公共解析站上基本都要你自己的 Authorization,云端没有共用账号。
修改配置文件:
app-dev.yml
@@ -484,14 +535,24 @@ app-dev.yml
```yaml
### 解析认证相关
auths:
# 123:配置用户名密码
# 夸克 / UC 大于 10MiB(10 * 1024 * 1024 字节)时才会查询会员接口。
# 只有未过期的 SVIP/VIP 才使用该账号直链;不要把普通 Cookie 写成会员。
# qk:
# cookie: 浏览器里夸克网盘的 Cookie
# uc:
# cookie: 浏览器里 UC 网盘的 Cookie
# 123:优先填 authorization。账号密码若触发验证码会失败,本项目不处理验证码。
ye:
username: 你的用户名
password: 你的密码
# authorization: 浏览器登录后的 authorToken / sso-token
# 城通免密和带密码分享都先匿名解析。仅当仍被 Turnstile 拦住时才需要登录令牌。
# 登录 https://pan.ctfile.com 后,从 Session Storage 复制 refresh_token。
# ct:
# refresh_token: 登录后的 refresh_token
# token: 可选,当前 access token
```
**注意:** 目前仅支持 123(ye)的认证配置。
**技术栈:**
Jdk17+Vert.x4
@@ -500,21 +561,41 @@ Core模块集成Vert.x实现类似spring的注解式路由API
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=qaiu/netdisk-fast-download&type=Date)](https://star-history.com/#qaiu/netdisk-fast-download&Date)
## **免责声明**
- 用户在使用本项目时,应自行承担风险,并确保其行为符合当地法律法规。开发者不对用户因使用本项目而导致的任何后果负责。
## 支持该项目
开源不易,用爱发电,本项目长期维护如果觉得有帮助, 可以请作者喝杯咖啡, 感谢支持
本项目的服务器由林枫云提供赞助<br>
<a href="https://www.star-history.com/?repos=qaiu%2Fnetdisk-fast-download&type=date&legend=bottom-right">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=qaiu/netdisk-fast-download&type=date&theme=dark&legend=bottom-right&sealed_token=dfQO_dJcTqcPkEnM7SfxRyHoFbV5Ah4LxoEhdlheMn4T2YLEV_WETxFZexeAbWN5OmNyYuycWan2d42PAFbw0CuU4oCTKgehfErFJ9eVl2CyVpP_4xrdQw" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=qaiu/netdisk-fast-download&type=date&legend=bottom-right&sealed_token=dfQO_dJcTqcPkEnM7SfxRyHoFbV5Ah4LxoEhdlheMn4T2YLEV_WETxFZexeAbWN5OmNyYuycWan2d42PAFbw0CuU4oCTKgehfErFJ9eVl2CyVpP_4xrdQw" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=qaiu/netdisk-fast-download&type=date&legend=bottom-right&sealed_token=dfQO_dJcTqcPkEnM7SfxRyHoFbV5Ah4LxoEhdlheMn4T2YLEV_WETxFZexeAbWN5OmNyYuycWan2d42PAFbw0CuU4oCTKgehfErFJ9eVl2CyVpP_4xrdQw" />
</picture>
</a>
## **声明**
- 本项目**仅供个人学习与技术交流使用**,请勿用于商业用途或大规模滥用。
- 所用接口均来自各网盘**官方开放平台**、官方公开接口及**已知开源项目**,仅解析用户主动提供的分享链接,**不涉及破解或绕过版权保护**。
- 本项目**相当于自动化程序代替用户发起请求**,**不会提升或绕过任何会员权限**,也**不会突破网盘的限速策略**;我们**鼓励用户开通官方 VIP/SVIP**以获得更好的下载与加速体验。
- 使用者应遵守各网盘服务商的**用户协议与使用条款**,以及所在地区的**法律法规**,违反所产生的后果自行承担。
- **高频调用可能触发网盘风控**,导致**账号限流、封禁**或**来源 IP 被屏蔽**,请合理控制请求频率,避免高并发与批量请求。
- 网盘接口调整、风控策略变更等因素可能导致功能失效,本项目**不对可用性与稳定性作任何担保**。
- 开发者**不对**使用本项目产生的**任何直接或间接损失**(账号封禁、数据丢失、法律纠纷等)**承担责任**。
- 开发者保留**随时修改本免责声明**的权利,恕不另行通知。
- **下载、部署或使用本项目,即视为您已阅读并接受上述全部条款。**
## 赞助该项目
开源不易,用爱发电。本项目长期维护,如果觉得有帮助,欢迎赞助开发者,感谢支持。
<p align="center">
<a href="https://blog.qaiu.top/archives/da-shang-zhuan-yong"><img alt="微信" src="https://api.iconify.design/simple-icons/wechat.svg?color=%2307C160" width="44" height="44"></a>
&nbsp;&nbsp;&nbsp;&nbsp;
<a href="https://blog.qaiu.top/archives/da-shang-zhuan-yong"><img alt="支付宝" src="https://api.iconify.design/simple-icons/alipay.svg?color=%231677FF" width="44" height="44"></a>
&nbsp;&nbsp;&nbsp;&nbsp;
<a href="https://paypal.me/futianshun"><img alt="PayPal" src="https://api.iconify.design/simple-icons/paypal.svg?color=%2300457C" width="44" height="44"></a>
</p>
本项目的服务器由林枫云提供赞助
<a href="https://www.dkdun.cn/aff/WDBRYKGH" target="_blank">
<img src="https://www.dkdun.cn/themes/web/www/upload/local68c2dbb2ab148.png" width="200">
</a>
</p>
Regular → Executable
+5 -1
View File
@@ -1,5 +1,9 @@
#!/bin/bash
# set -x
LAUNCH_JAR="netdisk-fast-download.jar"
exec java -Xmx${JVM_XMX:-512M} ${JVM_OPTS} -jar "$LAUNCH_JAR" "$@"
VECTOR_MODULE_OPT=
if java --list-modules 2>/dev/null | grep -q '^jdk.incubator.vector@'; then
VECTOR_MODULE_OPT=--add-modules=jdk.incubator.vector
fi
exec java ${VECTOR_MODULE_OPT} -Xmx${JVM_XMX:-512M} ${JVM_OPTS} -jar "$LAUNCH_JAR" "$@"
+1 -1
View File
@@ -65,7 +65,7 @@
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.11</version>
<version>42.7.13</version>
</dependency>
</dependencies>
@@ -162,13 +162,18 @@ public class CommonUtil {
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");
String version = properties.getProperty("app.version");
String build = properties.getProperty("build");
if (version != null && !version.contains("${")) {
appVersion = version + "build" + (build == null || build.contains("${") ? "" : build);
}
}
} catch (IOException e) {
} catch (Exception e) {
LOGGER.error("读取app.properties失败", e);
}
if (appVersion == null) {
appVersion = "unknown";
}
}
return appVersion;
}
@@ -13,7 +13,10 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static cn.qaiu.vx.core.util.ConfigConstant.GLOBAL_CONFIG;
@@ -25,6 +28,20 @@ import static cn.qaiu.vx.core.util.ConfigConstant.LOCAL;
public class HttpProxyVerticle extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpProxyVerticle.class);
static byte[] decodeProxyAuthorization(String encoded) {
var source = new ByteArrayInputStream(encoded.getBytes(StandardCharsets.ISO_8859_1));
// The streaming decoder uses scalar Java code and does not call the bulk intrinsic.
try (var decoder = Base64.getDecoder().wrap(source)) {
byte[] decoded = decoder.readAllBytes();
if (source.available() != 0) {
throw new IllegalArgumentException("Unexpected data after Base64 padding");
}
return decoded;
} catch (IOException e) {
throw new IllegalArgumentException("Invalid Base64 proxy credentials", e);
}
}
private HttpClient httpClient;
private NetClient netClient;
private HttpServer httpServer;
@@ -164,7 +181,7 @@ public class HttpProxyVerticle extends AbstractVerticle {
}
String[] split;
try {
split = new String(Base64.getDecoder().decode(s.replace("Basic ", ""))).split(":");
split = new String(decodeProxyAuthorization(s.replace("Basic ", ""))).split(":");
} catch (IllegalArgumentException e) {
LOGGER.warn("Proxy-Authorization header is not valid Base64");
failClientResponse(clientRequest.response(), 403, null);
@@ -0,0 +1,30 @@
package cn.qaiu.vx.core.verticle;
import org.junit.Test;
import java.util.Base64;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.fail;
public class HttpProxyBase64Test {
@Test
public void matchesJdkBasicDecoder() {
for (String value : new String[]{"", "Zg", "Zg==", "Zm8=", "dXNlcjpwYXNz", "+/8=", "ABCD",
"AB==", "Z", "Zg=", "Zm8==", "Zg==suffix", "Zg==\n", "-_8=", "AA\u2603", "===="}) {
byte[] expected;
try {
expected = Base64.getDecoder().decode(value);
} catch (IllegalArgumentException expectedFailure) {
try {
HttpProxyVerticle.decodeProxyAuthorization(value);
} catch (IllegalArgumentException actualFailure) {
continue;
}
fail("Accepted invalid proxy credentials: " + value);
return;
}
assertArrayEquals(expected, HttpProxyVerticle.decodeProxyAuthorization(value));
}
}
}
+6 -1
View File
@@ -10,4 +10,9 @@ DEFAULT_JVM_OPTS="-Xmx${JVM_XMX:-512M} -Xss${JVM_XSS:-512k} -XX:MaxDirectMemoryS
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
# Keep this after JVM_OPTS to disable the intrinsic even with an older base image.
VECTOR_MODULE_OPT=
if java --list-modules 2>/dev/null | grep -q '^jdk.incubator.vector@'; then
VECTOR_MODULE_OPT=--add-modules=jdk.incubator.vector
fi
exec java ${VECTOR_MODULE_OPT} ${DEFAULT_JVM_OPTS} ${JVM_OPTS} -XX:-UseBASE64Intrinsics -Duser.timezone=${TZ:-Asia/Shanghai} -jar /app/netdisk-fast-download.jar
+3 -2
View File
@@ -24,7 +24,7 @@
### 认证参数说明(v0.2.1+)
部分网盘(如夸克QK、UC网盘)需要登录后的 Cookie 才能解析。`auth` 参数用于传递认证信息:
部分网盘需要登录后的 Cookie 或 Authorization 才能下载。夸克小文件可以不登录;UC 必须有 Cookie。`auth` 参数用于传递认证信息:
**加密方式**:
- 算法:AES/ECB/PKCS5Padding
@@ -42,8 +42,9 @@
**网盘认证要求**:
| 网盘 | 认证要求 |
|------|---------|
| 夸克网盘(QK) | **必须** |
| 夸克网盘(QK) | 小文件可免登录;超过访客大小限制(23018)需要 Cookie |
| UC网盘(UC) | **必须** |
| 123网盘(YE) | 下载通常需要本机 `auths.ye.authorization`;公共云解析没有共享账号 |
| 小飞机网盘(FJ) | 大文件需要 |
| 蓝奏优享(IZ) | 大文件需要 |
+3 -31
View File
@@ -261,39 +261,11 @@ var methods = systemClass.getDeclaredMethods();
Nashorn引擎默认允许JavaScript访问所有Java类,这是一个严重的安全隐患。以下是建议的安全措施:
### 1. 使用ClassFilter限制类访问 🔒 必须
### 1. 演练场与已注册解析器的类访问限制
```java
import jdk.nashorn.api.scripting.ClassFilter;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
两个入口都通过 `ParserScriptEngine.create()` 创建 Nashorn 引擎。引擎使用 `--no-java`,类过滤器拒绝按名称解析 Java 类。引擎在执行解析器代码前禁用包入口、脚本加载函数和脚本上下文全局变量。解析器仍可使用项目显式注入的分享信息、HTTP、Fetch 和日志接口。
public class SecurityClassFilter implements ClassFilter {
@Override
public boolean exposeToScripts(String className) {
// 黑名单:禁止访问危险类
if (className.startsWith("java.lang.Runtime") ||
className.startsWith("java.lang.ProcessBuilder") ||
className.startsWith("java.io.File") ||
className.startsWith("java.nio.file") ||
className.startsWith("java.lang.System") ||
className.startsWith("java.lang.Class") ||
className.startsWith("java.lang.reflect") ||
className.startsWith("java.net.Socket") ||
className.startsWith("java.net.URL")) {
return false;
}
// 白名单:只允许特定的类
// return className.startsWith("允许的包名");
return false; // 默认拒绝所有
}
}
// 使用ClassFilter创建引擎
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(new SecurityClassFilter());
```
`ParserScriptEngineTest` 检查受限全局变量的属性,并通过两个执行入口验证普通解析器的行为。
### 2. 设置执行超时 ⏱️ 强烈推荐
@@ -109,6 +109,8 @@ URL解码 → Base64解码 → AES解密 → JSON对象
}
```
> 123云盘(`ye`)账号密码登录如果返回验证码或风控,解析会直接失败,并提示改用 Authorization,不会尝试验证码。请在浏览器登录后复制 `authorToken` / 请求头 `authorization` / Cookie `sso-token`,用 `authType=authorization` 或 `accesstoken` 传入,或写入 `app-dev.yml` 的 `auths.ye.authorization`。
#### 4. 自定义认证
```json
{
@@ -339,3 +341,4 @@ server:
## 更新日志
- **2026-02-05**: 初始版本,支持 accesstoken、cookie、password、custom 认证类型
- **2026-09-27**: 补充 123云盘账号密码登录触发验证码/风控时改用 Authorization 的说明
@@ -57,6 +57,8 @@
}
```
> 123云盘(`ye`)账号密码登录触发验证码/风控时,请改用 `authType=authorization` 或 `accesstoken`(`token` 填浏览器中的 Bearer token / JWT),或在 `app-dev.yml` 配置 `auths.ye.authorization`。解析不会尝试验证码。
### 自定义认证
```json
{
+10 -2
View File
@@ -63,7 +63,7 @@
<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>
<jackson.version>2.18.9</jackson.version>
<logback.version>1.5.32</logback.version>
<junit.version>4.13.2</junit.version>
</properties>
@@ -165,6 +165,10 @@
<version>3.13.0</version>
<configuration>
<release>${maven.compiler.source}</release>
<compilerArgs>
<arg>--add-modules</arg>
<arg>jdk.incubator.vector</arg>
</compilerArgs>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
@@ -200,7 +204,11 @@
<!-- 忽略 Javadoc 错误 -->
<failOnError>false</failOnError>
<!-- 禁用 doclint(新版参数名改为 additionalOptions) -->
<additionalOptions>-Xdoclint:none</additionalOptions>
<additionalOptions>
<additionalOption>-Xdoclint:none</additionalOption>
<additionalOption>--add-modules</additionalOption>
<additionalOption>jdk.incubator.vector</additionalOption>
</additionalOptions>
<!-- 如果项目源码中几乎没有 Javadoc,可设 true -->
<quiet>true</quiet>
</configuration>
@@ -1,5 +1,7 @@
package cn.qaiu.entity;
import cn.qaiu.util.QuarkAccountScope;
import java.util.HashMap;
import java.util.Map;
@@ -85,12 +87,19 @@ public class ShareLinkInfo {
public String getCacheKey() {
// 将type和shareKey组合成一个字符串作为缓存key
String key = type + ":" + shareKey;
if (type.equals("p115")) {
if (type != null && type.equals("p115")) {
Object ua = otherParam != null ? otherParam.get("UA") : null;
if (ua != null) {
key += ("_" + ua.toString().hashCode());
}
}
// 带账号的夸克 / UC 直链按账号隔离,避免会员链和 Cookie 进入分享级缓存。
if (type != null && ("qk".equalsIgnoreCase(type) || "uc".equalsIgnoreCase(type))) {
String scope = QuarkAccountScope.suffix(otherParam);
if (scope != null) {
key += "#" + scope;
}
}
return key;
}
@@ -0,0 +1,145 @@
package cn.qaiu.parser;
import cn.qaiu.entity.ShareLinkInfo;
import io.vertx.core.json.JsonObject;
import java.util.Locale;
import java.util.Set;
/**
* 目录列表分页约定(解析器与 API 共用)。
* <p>
* 入参写在 {@link ShareLinkInfo#getOtherParam()}:
* <ul>
* <li>{@link #PAGE}:从 1 开始的页码;不传时解析器按原逻辑只取第一页</li>
* <li>{@link #CURSOR}:上一页返回的 {@code nextCursor},可选,只是加速,不可信</li>
* </ul>
* 解析器取完一页后写回 {@link #PAGE_INFO},见 {@link #pageInfo}。
* 没写 {@link #PAGE_INFO} 的解析器视为不分页,整份列表就是第 1 页。
*/
public final class FolderPaging {
public static final String PAGE = "page";
public static final String CURSOR = "pageCursor";
public static final String PAGE_INFO = "pageInfo";
/** 页码上限。蓝奏无游标时要从第 1 页顺序翻到目标页,必须有界。 */
public static final int MAX_PAGE = 500;
private static final Set<String> PAGED_TYPES = Set.of("lz", "fj", "iz");
private FolderPaging() {
}
/** 该网盘的目录解析是否支持按页取。 */
public static boolean supports(String type) {
return type != null && PAGED_TYPES.contains(type.toLowerCase(Locale.ROOT));
}
/**
* 解析页码参数。空值返回 null(保持旧行为);非法值抛 IllegalArgumentException。
*/
public static Integer parsePage(String raw) {
if (raw == null || raw.isBlank()) {
return null;
}
int page;
try {
page = Integer.parseInt(raw.trim());
} catch (NumberFormatException e) {
throw new IllegalArgumentException("page 必须是正整数: " + raw);
}
if (page < 1 || page > MAX_PAGE) {
throw new IllegalArgumentException("page 超出范围 1-" + MAX_PAGE + ": " + raw);
}
return page;
}
/** 本次请求的页码;没传返回 null。 */
public static Integer requestedPage(ShareLinkInfo info) {
Object v = info.getOtherParam().get(PAGE);
if (v instanceof Number n) {
return n.intValue();
}
return v == null ? null : parsePage(v.toString());
}
/** 本次请求的页码;没传按第 1 页。 */
public static int pageOrFirst(ShareLinkInfo info) {
Integer page = requestedPage(info);
return page == null ? 1 : page;
}
public static String cursor(ShareLinkInfo info) {
Object v = info.getOtherParam().get(CURSOR);
return v == null || v.toString().isBlank() ? null : v.toString();
}
/**
* 写回分页结果。
*
* @param pageSize 上游每页条数(原始条数口径,含被过滤的占位项)
* @param hasMore 上游明确还有下一页
* @param total 上游给出的总条数,未知传 null
* @param totalPage 上游给出的总页数,未知传 null
* @param nextCursor 取下一页可直接复用的游标,没有传 null
*/
public static JsonObject pageInfo(ShareLinkInfo info, int page, int pageSize, boolean hasMore,
Integer total, Integer totalPage, String nextCursor) {
JsonObject json = new JsonObject()
.put("paged", true)
.put("page", page)
.put("pageSize", pageSize)
.put("hasMore", hasMore)
.put("nextPage", hasMore ? page + 1 : null)
.put("total", total)
.put("totalPage", totalPage)
.put("nextCursor", hasMore ? nextCursor : null);
info.getOtherParam().put(PAGE_INFO, json);
return json;
}
/**
* 上游给了总页数就以它为准;没给时整页满才认为可能还有。空页一律结束,避免无限翻页。
*/
public static boolean hasMore(int page, int rawCount, int pageSize, Integer totalPage) {
if (rawCount <= 0) {
return false;
}
if (totalPage != null && totalPage > 0) {
return page < totalPage;
}
return rawCount >= pageSize;
}
/** 小飞机 / 蓝奏优享 share/list 响应:offset 为页码,带 total / totalPage。 */
public static JsonObject offsetListPage(ShareLinkInfo info, JsonObject resp, int rawCount, int pageSize) {
int page = pageOrFirst(info);
Integer total = intOrNull(resp, "total");
Integer totalPage = intOrNull(resp, "totalPage");
return pageInfo(info, page, pageSize, hasMore(page, rawCount, pageSize, totalPage), total, totalPage, null);
}
private static Integer intOrNull(JsonObject json, String key) {
if (json == null) {
return null;
}
Object v = json.getValue(key);
if (v instanceof Number n) {
return n.intValue();
}
if (v instanceof CharSequence s) {
try {
return Integer.parseInt(s.toString().trim());
} catch (NumberFormatException ignored) {
return null;
}
}
return null;
}
public static JsonObject pageInfo(ShareLinkInfo info) {
Object v = info.getOtherParam().get(PAGE_INFO);
return v instanceof JsonObject json ? json : null;
}
}
@@ -20,6 +20,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
@@ -201,6 +204,76 @@ public abstract class PanBase implements IPanTool, Closeable {
}
}
/**
* SSRF 防护: 校验通用自定义域名解析器 (CE/Ce4/Kd/Other 等) 即将请求的目标主机,
* 拒绝解析到回环/内网/链路本地/组播等非公网地址的域名, 阻止攻击者通过可控 DNS
* 记录 (或直接填写内网域名) 让服务端向内网/云元数据接口发起请求。
* <p>
* 必须在子类 parse() 中构造出 baseUrl/发起任何 clientSession 请求之前调用。
*
* @param url 从 shareLinkInfo.getShareUrl() 解析出的 URL
* @throws IOException 当主机无法解析或解析结果落入禁止的地址段时抛出
*/
protected static void assertPublicHost(URL url) throws IOException {
String host = url.getHost();
InetAddress[] addresses;
try {
addresses = InetAddress.getAllByName(host);
} catch (UnknownHostException e) {
throw new IOException("无法解析目标主机: " + host, e);
}
if (addresses.length == 0) {
throw new IOException("无法解析目标主机: " + host);
}
for (InetAddress addr : addresses) {
if (isDisallowedAddress(addr)) {
throw new IOException("目标地址不允许访问(内网/回环/链路本地/组播): "
+ host + " -> " + addr.getHostAddress());
}
}
}
/**
* 判断地址是否落入禁止访问的范围: 0.0.0.0/8, 10/8, 127/8, 169.254/16(含云元数据
* 169.254.169.254), 172.16/12, 192.168/16, 100.64/10(CGNAT), 224/4~255/4(组播/保留),
* 以及对应的 IPv6 回环/链路本地/唯一本地地址(fc00::/7)/组播地址; IPv4-映射的 IPv6
* 地址(::ffff:a.b.c.d) 会先还原为 IPv4 再判断,避免绕过。
*/
private static boolean isDisallowedAddress(InetAddress addr) {
byte[] bytes = addr.getAddress();
if (bytes.length == 16 && isIPv4Mapped(bytes)) {
byte[] v4 = new byte[4];
System.arraycopy(bytes, 12, v4, 0, 4);
bytes = v4;
}
if (bytes.length == 4) {
int b0 = bytes[0] & 0xFF;
int b1 = bytes[1] & 0xFF;
if (b0 == 0) return true; // 0.0.0.0/8
if (b0 == 10) return true; // 10.0.0.0/8
if (b0 == 127) return true; // 127.0.0.0/8 loopback
if (b0 == 169 && b1 == 254) return true; // 169.254.0.0/16 (含云元数据 169.254.169.254)
if (b0 == 172 && b1 >= 16 && b1 <= 31) return true; // 172.16.0.0/12
if (b0 == 192 && b1 == 168) return true; // 192.168.0.0/16
if (b0 == 100 && b1 >= 64 && b1 <= 127) return true;// 100.64.0.0/10 CGNAT
return b0 >= 224; // 224.0.0.0/4 组播 + 240.0.0.0/4 保留
}
// IPv6
if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()
|| addr.isLinkLocalAddress() || addr.isSiteLocalAddress()
|| addr.isMulticastAddress()) {
return true;
}
return bytes.length == 16 && (bytes[0] & 0xFE) == 0xFC; // fc00::/7 unique local
}
private static boolean isIPv4Mapped(byte[] b) {
for (int i = 0; i < 10; i++) {
if (b[i] != 0) return false;
}
return (b[10] & 0xFF) == 0xFF && (b[11] & 0xFF) == 0xFF;
}
protected String baseMsg() {
if (shareLinkInfo.getShareUrl() != null) {
return shareLinkInfo.getPanName() + "-" + shareLinkInfo.getType() + ": url=" + shareLinkInfo.getShareUrl();
@@ -295,9 +368,12 @@ public abstract class PanBase implements IPanTool, Closeable {
// 检查响应头中的Content-Encoding是否为gzip
String contentEncoding = res.getHeader("Content-Encoding");
try {
if ("gzip".equalsIgnoreCase(contentEncoding)) {
if ("gzip".equalsIgnoreCase(contentEncoding) && res.body() instanceof Buffer gzipBody
&& gzipBody.length() >= 2
&& (gzipBody.getByte(0) & 0xff) == 0x1f
&& (gzipBody.getByte(1) & 0xff) == 0x8b) {
// 如果是gzip压缩的响应体,解压(只解压一次,缓存结果)
String decompressed = decompressGzip((Buffer) res.body());
String decompressed = decompressGzip(gzipBody);
return new JsonObject(decompressed);
} else {
return res.bodyAsJsonObject();
@@ -309,9 +385,10 @@ public abstract class PanBase implements IPanTool, Closeable {
log.error("响应gzip解压或JSON解析失败: {}", e.getMessage());
fail("响应gzip解压或JSON解析失败: {}", e.getMessage());
} else {
// 上游响应体可能来自内网探测目标,仅写日志,避免经 HTTP 500 回传给调用方
String bodyPreview = responseBodyPreview(res);
log.error("解析失败: json格式异常: {}", bodyPreview);
fail("解析失败: json格式异常: {}", bodyPreview);
fail("解析失败: json格式异常");
}
return JsonObject.of();
}
@@ -341,7 +418,18 @@ public abstract class PanBase implements IPanTool, Closeable {
protected void completeWithMeta(String url, Map<String, String> headers) {
shareLinkInfo.getOtherParam().put("downloadUrl", url);
if (headers != null && !headers.isEmpty()) {
shareLinkInfo.getOtherParam().put("downloadHeaders", headers);
// 过滤 null/空值,避免 cookie:null 覆盖入口参数或污染 curl 命令
Map<String, String> clean = new HashMap<>();
headers.forEach((k, v) -> {
if (k != null && v != null && !v.isBlank()) {
clean.put(k, v);
}
});
if (!clean.isEmpty()) {
shareLinkInfo.getOtherParam().put("downloadHeaders", clean);
// UC/夸克等需带 cookie 的直链,标记前端走下载器
shareLinkInfo.getOtherParam().put("needDownloader", true);
}
}
promise.complete(url);
}
@@ -449,6 +537,34 @@ public abstract class PanBase implements IPanTool, Closeable {
return shareLinkInfo.getOtherParam().getOrDefault("domainName", "").toString();
}
/**
* 将入口请求中的加密 auth 透传到子目录/下载链接,避免进入子目录后丢失认证。
* otherParam 中的 key 为 {@code _authQuery}(由 web 层写入)。
*/
protected String appendAuthQuery(String url) {
if (StringUtils.isBlank(url) || shareLinkInfo == null || shareLinkInfo.getOtherParam() == null) {
return url;
}
Object authObj = shareLinkInfo.getOtherParam().get("_authQuery");
if (authObj == null) {
return url;
}
String auth = authObj.toString();
if (StringUtils.isBlank(auth)) {
return url;
}
// 已带 auth 则不再追加
if (url.contains("auth=")) {
return url;
}
try {
String encoded = java.net.URLEncoder.encode(auth, StandardCharsets.UTF_8);
return url + (url.contains("?") ? "&" : "?") + "auth=" + encoded;
} catch (Exception e) {
return url + (url.contains("?") ? "&" : "?") + "auth=" + auth;
}
}
@Override
public ShareLinkInfo getShareLinkInfo() {
return shareLinkInfo;
@@ -121,9 +121,9 @@ public enum PanDomainTemplate {
"https://lecloud.lenovo.com/share/{shareKey}",
LeTool.class),
// https://v2.fangcloud.com/s/
// https://v2.fangcloud.com/s/ https://v2.fangcloud.cn/h5/share/ (移动端H5落地页)
FC("亿方云",
compile("https://v2\\.fangcloud\\.(com|cn)/(s|share|sharing)/(?<KEY>.+)"),
compile("https://v2\\.fangcloud\\.(com|cn)/(?:h5/)?(s|share|sharing)/(?<KEY>.+)"),
"https://v2.fangcloud.com/s/{shareKey}",
"https://www.fangcloud.com/",
FcTool.class),
@@ -208,7 +208,7 @@ public enum PanDomainTemplate {
123795.com
*/
YE("123网盘",
compile("https://www\\.(" +
compile("https://(?:[a-zA-Z\\d-]+\\.)*(" +
"123254\\.com|" +
"123957\\.com|" +
"123295\\.com|" +
@@ -232,7 +232,7 @@ public enum PanDomainTemplate {
"123635\\.com|" +
"123242\\.com|" +
"123795\\.com" +
")/s/(?<KEY>[a-zA-Z0-9_-]+)(?:\\.html)?"),
")/(?:(?:s|123pan)/|(?:[^/?#]+/)+)?(?<KEY>[a-zA-Z0-9]+-[a-zA-Z0-9]+|[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
@@ -377,6 +377,16 @@ public enum PanDomainTemplate {
MmgTool.class),
// =====================私有盘解析==========================
// 永硕E盘空间分享:https://qaiu.ysepan.com/ (空间名即 shareKey,密码为空间访问密码)
// 主域名 ysepan.com / ys168.com;备用 cccpan.com / ysupan.com / uupan.net / ysok.net
YS("永硕E盘",
compile("https?://(?!(?:www|zy|ht|api|c\\d+|ys-[a-zA-Z0-9]+)\\.)(?<KEY>[a-zA-Z\\d-]+)\\."
+ "(?:ysepan\\.com|ys168\\.com|cccpan\\.com|ysupan\\.com|uupan\\.net|ysok\\.net)"
+ "/?(?:\\?.*)?"),
"https://{shareKey}.ysepan.com/",
"https://www.ysepan.com/",
YsTool.class),
// Cloudreve自定义域名解析, 解析器CeTool兜底策略, 即任意域名如果匹配不到对应的规则, 则由CeTool统一处理,
// 如果不属于Cloudreve盘 则调用下一个自定义域名解析器, 若都处理不了则抛出异常, 这种匹配模式类似责任链
// http(s)://pan.huang1111.cn/s/xxx
@@ -0,0 +1,270 @@
package cn.qaiu.parser;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.apache.commons.lang3.StringUtils;
import java.util.Locale;
/**
* 账号密码登录撞上验证码/风控时的用户提示。
* 只识别失败形态并引导改用 Authorization,不实现验证码求解、扫码或重试。
*/
public final class PasswordLoginRisk {
/**
* 123 云盘(ye)账号密码登录被验证码/风控拦住时返回给调用方的固定说明。
* 上游 code/message 会另附在这句话后面,便于和“密码错误”区分。
*/
public static final String AUTHORIZATION_HINT =
"账号密码登录触发了验证码/风控,已停止用户名密码登录(不会尝试验证码)。"
+ "请改为配置 Authorization(浏览器登录后的 Bearer token / JWT,"
+ "例如 localStorage 的 authorToken、请求头 authorization 或 Cookie 的 sso-token)。"
+ "静态配置写在 app-dev.yml 的 auths.ye.authorization(与 auths.ye.token 等价);"
+ "临时请求使用 authType=authorization 或 authType=accesstoken,token 填该令牌(不要重复带 Bearer 前缀)。"
+ "说明见 parser/doc/auth-param/。";
/**
* 上游文案命中这些片段时视为验证码/风控,而不是单纯的密码错误。
* 依据公开客户端(AList/OpenList)实际展示过的 123 登录失败文案,以及登录页上的滑块/人机验证提示。
*/
private static final String[] RISK_KEYWORDS = {
"验证码",
"风控",
"安全风险",
"安全验证",
"安全校验",
"滑块",
"滑动验证",
"拼图验证",
"短信验证",
"微信登录",
"微信进行登录",
"境外登录",
"需要验证",
"请验证",
"请你验证",
"进行验证",
"完成验证",
"二次验证",
"人机验证",
"操作频繁",
"请求过于频繁",
"请求频繁",
"captcha",
"recaptcha",
"risk control"
};
private PasswordLoginRisk() {
}
public static boolean isLoginSuccess(JsonObject json) {
if (json == null) {
return false;
}
Integer code = readCode(json);
return code != null && code == 200 && StringUtils.isNotBlank(readToken(json));
}
public static boolean indicatesCaptchaOrRisk(JsonObject json) {
if (json == null) {
return false;
}
if (hasTruthyRiskField(json) || hasTruthyRiskField(dataObject(json))) {
return true;
}
return textIndicatesCaptchaOrRisk(collectMessageText(json));
}
public static boolean textIndicatesCaptchaOrRisk(String text) {
if (StringUtils.isBlank(text)) {
return false;
}
String lower = text.toLowerCase(Locale.ROOT);
for (String keyword : RISK_KEYWORDS) {
if (lower.contains(keyword.toLowerCase(Locale.ROOT))) {
return true;
}
}
return false;
}
/**
* 非成功登录响应的用户可见说明。验证码/风控走 Authorization 引导,其余保持“登录失败: 上游文案”。
*/
public static String describeLoginFailure(JsonObject json) {
if (json == null) {
return "登录响应格式异常";
}
if (indicatesCaptchaOrRisk(json)) {
return AUTHORIZATION_HINT + " 上游返回:" + upstreamSummary(json);
}
Integer code = readCode(json);
if (code != null && code == 200) {
return "未获取到token";
}
String message = firstMessage(json);
if (StringUtils.isBlank(message)) {
return "登录失败";
}
return "登录失败: " + message;
}
public static String nonJsonLoginFailure(String body) {
if (textIndicatesCaptchaOrRisk(body)) {
return AUTHORIZATION_HINT + " 上游返回:" + truncate(body, 300);
}
return "登录响应格式异常: " + body;
}
private static String collectMessageText(JsonObject json) {
StringBuilder text = new StringBuilder();
appendMessage(text, json);
JsonObject data = dataObject(json);
if (data != null) {
appendMessage(text, data);
}
return text.toString();
}
private static void appendMessage(StringBuilder text, JsonObject json) {
append(text, json.getString("message"));
append(text, json.getString("msg"));
}
private static void append(StringBuilder text, String value) {
if (StringUtils.isNotBlank(value)) {
if (text.length() > 0) {
text.append(' ');
}
text.append(value);
}
}
private static boolean hasTruthyRiskField(JsonObject obj) {
if (obj == null) {
return false;
}
for (String key : obj.fieldNames()) {
if (!isRiskFieldName(key)) {
continue;
}
if (isTruthyRiskValue(obj.getValue(key))) {
return true;
}
}
return false;
}
private static boolean isRiskFieldName(String key) {
String lower = key.toLowerCase(Locale.ROOT);
return lower.contains("captcha")
|| lower.contains("vcode")
|| lower.contains("risk")
|| "needverify".equals(lower)
|| "need_verify".equals(lower)
|| "slideverify".equals(lower)
|| "verifycode".equals(lower)
|| "verify_code".equals(lower);
}
private static boolean isTruthyRiskValue(Object value) {
if (value == null) {
return false;
}
if (value instanceof Boolean) {
return (Boolean) value;
}
if (value instanceof Number) {
return ((Number) value).doubleValue() != 0d;
}
if (value instanceof CharSequence) {
String text = value.toString().trim();
if (text.isEmpty()) {
return false;
}
String lower = text.toLowerCase(Locale.ROOT);
return !"false".equals(lower) && !"0".equals(lower) && !"null".equals(lower) && !"none".equals(lower);
}
if (value instanceof JsonObject) {
return !((JsonObject) value).isEmpty();
}
if (value instanceof JsonArray) {
return !((JsonArray) value).isEmpty();
}
return true;
}
private static String upstreamSummary(JsonObject json) {
StringBuilder summary = new StringBuilder();
Integer code = readCode(json);
if (code != null) {
summary.append("code=").append(code);
}
String message = firstMessage(json);
if (StringUtils.isNotBlank(message)) {
if (summary.length() > 0) {
summary.append(", ");
}
summary.append("message=").append(message);
}
if (summary.length() == 0) {
summary.append(json.encode());
}
return truncate(summary.toString(), 300);
}
private static String firstMessage(JsonObject json) {
String message = json.getString("message");
if (StringUtils.isBlank(message)) {
message = json.getString("msg");
}
if (StringUtils.isBlank(message)) {
JsonObject data = dataObject(json);
if (data != null) {
message = data.getString("message");
if (StringUtils.isBlank(message)) {
message = data.getString("msg");
}
}
}
return message;
}
static String readToken(JsonObject json) {
JsonObject data = dataObject(json);
if (data == null) {
return null;
}
Object token = data.getValue("token");
return token == null ? null : token.toString();
}
private static JsonObject dataObject(JsonObject json) {
Object data = json.getValue("data");
return data instanceof JsonObject ? (JsonObject) data : null;
}
static Integer readCode(JsonObject json) {
Object code = json.getValue("code");
if (code instanceof Number) {
return ((Number) code).intValue();
}
if (code instanceof String && StringUtils.isNumeric(((String) code).trim())) {
return Integer.parseInt(((String) code).trim());
}
return null;
}
private static String truncate(String value, int max) {
if (value == null) {
return "";
}
String trimmed = value.trim();
if (trimmed.length() <= max) {
return trimmed;
}
return trimmed.substring(0, max) + "...";
}
}
@@ -0,0 +1,149 @@
package cn.qaiu.parser;
import java.util.concurrent.ConcurrentHashMap;
/**
* 解析器 Token/Cookie 缓存 — 支持多账号隔离。
* <p>
* 以 (diskType + "#" + accountKey) 作为缓存 key,不同账号的 token 互不覆盖。
* accountKey 优先使用 _configId,其次使用 username、cookie 前16位等可区分标识。
* </p>
*/
public final class TokenCache {
private TokenCache() {}
/** token 缓存 */
private static final ConcurrentHashMap<String, String> tokenMap = new ConcurrentHashMap<>();
/** 过期时间缓存(毫秒时间戳) */
private static final ConcurrentHashMap<String, Long> expireMap = new ConcurrentHashMap<>();
/** 同一 key 下的额外字符串缓存(如 userId) */
private static final ConcurrentHashMap<String, String> extraMap = new ConcurrentHashMap<>();
/** 布尔标记缓存(如 authFlag) */
private static final ConcurrentHashMap<String, Boolean> flagMap = new ConcurrentHashMap<>();
// ============ key 构造 ============
public static String key(String diskType, String accountKey) {
return diskType + "#" + (accountKey == null ? "_default" : accountKey);
}
// ============ token ============
public static String getToken(String cacheKey) {
return tokenMap.get(cacheKey);
}
public static void putToken(String cacheKey, String token) {
if (token == null) {
tokenMap.remove(cacheKey);
} else {
tokenMap.put(cacheKey, token);
}
}
// ============ expire ============
public static long getExpire(String cacheKey) {
return expireMap.getOrDefault(cacheKey, 0L);
}
public static void putExpire(String cacheKey, long expireMs) {
expireMap.put(cacheKey, expireMs);
}
public static boolean isExpired(String cacheKey) {
long exp = getExpire(cacheKey);
return exp <= 0 || System.currentTimeMillis() > exp;
}
// ============ extra (userId 等) ============
public static String getExtra(String cacheKey) {
return extraMap.get(cacheKey);
}
public static void putExtra(String cacheKey, String value) {
if (value == null) {
extraMap.remove(cacheKey);
} else {
extraMap.put(cacheKey, value);
}
}
// ============ flag (authFlag 等) ============
public static boolean getFlag(String cacheKey, boolean defaultValue) {
return flagMap.getOrDefault(cacheKey, defaultValue);
}
public static void putFlag(String cacheKey, boolean value) {
flagMap.put(cacheKey, value);
}
// ============ 清除 ============
public static void remove(String cacheKey) {
tokenMap.remove(cacheKey);
expireMap.remove(cacheKey);
extraMap.remove(cacheKey);
flagMap.remove(cacheKey);
}
/**
* 清除指定网盘类型的所有缓存(精准清除,不影响其他网盘类型)
*/
public static void removeByDiskType(String diskType) {
String prefix = diskType + "#";
tokenMap.keySet().removeIf(k -> k.startsWith(prefix));
expireMap.keySet().removeIf(k -> k.startsWith(prefix));
extraMap.keySet().removeIf(k -> k.startsWith(prefix));
flagMap.keySet().removeIf(k -> k.startsWith(prefix));
}
public static void clear() {
tokenMap.clear();
expireMap.clear();
extraMap.clear();
flagMap.clear();
}
// ============ Token 持久化队列 ============
/** 待持久化的 cachedToken 数据 (cacheKey -> [token, expireMs]) */
private static final ConcurrentHashMap<String, String[]> persistQueue = new ConcurrentHashMap<>();
/** 待回写的凭据更新 (cacheKey -> newCredential),如 PaliTool refresh_token 轮换 */
private static final ConcurrentHashMap<String, String> credentialUpdateQueue = new ConcurrentHashMap<>();
/**
* 解析器登录成功后,将 token 加入持久化队列(下次 recordConfigUsage 回写 DB)
*/
public static void queueCachedTokenPersist(String cacheKey, String token, long expireMs) {
if (cacheKey != null && token != null) {
persistQueue.put(cacheKey, new String[]{token, String.valueOf(expireMs)});
}
}
/**
* 凭据本身被替换(如 PaliTool refresh_token 轮换),加入回写队列
*/
public static void queueCredentialUpdate(String cacheKey, String newCredential) {
if (cacheKey != null && newCredential != null) {
credentialUpdateQueue.put(cacheKey, newCredential);
}
}
/**
* 消费持久化队列:返回 [token, expireMs] 并移除;无数据返回 null
*/
public static String[] pollCachedTokenPersist(String cacheKey) {
return cacheKey == null ? null : persistQueue.remove(cacheKey);
}
/**
* 消费凭据更新队列:返回新凭据并移除;无数据返回 null
*/
public static String pollCredentialUpdate(String cacheKey) {
return cacheKey == null ? null : credentialUpdateQueue.remove(cacheKey);
}
}
@@ -1,11 +1,11 @@
package cn.qaiu.parser.clientlink.impl;
import cn.qaiu.util.Base64Encoder;
import cn.qaiu.parser.clientlink.ClientLinkGenerator;
import cn.qaiu.parser.clientlink.ClientLinkType;
import cn.qaiu.parser.clientlink.DownloadLinkMeta;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* 迅雷协议链接生成器
@@ -27,7 +27,7 @@ public class ThunderLinkGenerator implements ClientLinkGenerator {
String thunderUrl = "AA" + originalUrl + "ZZ";
// Base64编码
String encodedUrl = Base64.getEncoder().encodeToString(
String encodedUrl = Base64Encoder.encode(
thunderUrl.getBytes(StandardCharsets.UTF_8)
);
@@ -9,7 +9,6 @@ import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.WorkerExecutor;
import io.vertx.core.json.JsonObject;
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -134,15 +133,7 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
*/
private ScriptEngine initEngine() {
try {
// 使用安全的ClassFilter创建Nashorn引擎
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
// 正确的方法签名: getScriptEngine(String[] args, ClassLoader appLoader, ClassFilter classFilter)
ScriptEngine engine = factory.getScriptEngine(new String[0], null, new SecurityClassFilter());
if (engine == null) {
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
}
ScriptEngine engine = ParserScriptEngine.create();
this.engine = engine;
// 注入Java对象到JavaScript环境
@@ -151,14 +142,6 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
engine.put("shareLinkInfo", shareLinkInfoWrapper);
engine.put("JavaFetch", fetchBridge);
// 禁用Java对象访问
engine.eval("var Java = undefined;");
engine.eval("var JavaImporter = undefined;");
engine.eval("var Packages = undefined;");
engine.eval("var javax = undefined;");
engine.eval("var org = undefined;");
engine.eval("var com = undefined;");
// 加载fetch运行时(Promise和fetch API polyfill)
String fetchRuntime = loadFetchRuntime();
if (!fetchRuntime.isEmpty()) {
@@ -5,7 +5,6 @@ import cn.qaiu.entity.ShareLinkInfo;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -111,15 +110,7 @@ public class JsPlaygroundExecutor implements AutoCloseable {
*/
private ScriptEngine initEngine() {
try {
// 使用安全的ClassFilter创建Nashorn引擎
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
// 正确的方法签名: getScriptEngine(String[] args, ClassLoader appLoader, ClassFilter classFilter)
ScriptEngine engine = factory.getScriptEngine(new String[0], null, new SecurityClassFilter());
if (engine == null) {
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
}
ScriptEngine engine = ParserScriptEngine.create();
this.engine = engine;
// 注入Java对象到JavaScript环境
@@ -128,14 +119,6 @@ public class JsPlaygroundExecutor implements AutoCloseable {
engine.put("shareLinkInfo", shareLinkInfoWrapper);
engine.put("JavaFetch", fetchBridge);
// 禁用Java对象访问
engine.eval("var Java = undefined;");
engine.eval("var JavaImporter = undefined;");
engine.eval("var Packages = undefined;");
engine.eval("var javax = undefined;");
engine.eval("var org = undefined;");
engine.eval("var com = undefined;");
// 加载fetch运行时(Promise和fetch API polyfill)
String fetchRuntime = JsParserExecutor.loadFetchRuntime();
if (!fetchRuntime.isEmpty()) {
@@ -0,0 +1,28 @@
package cn.qaiu.parser.customjs;
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
final class ParserScriptEngine {
private ParserScriptEngine() {}
static ScriptEngine create() throws ScriptException {
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(
new String[]{"--no-java"}, null, new SecurityClassFilter());
// Remove host loaders and scripting-context globals before binding the parser APIs.
engine.eval("""
(function (global) {
["load", "loadWithNewGlobal", "exit", "quit", "engine", "context",
"Java", "JavaImporter", "Packages", "java", "javax", "javafx", "org",
"com", "edu"].forEach(function (name) {
Object.defineProperty(global, name, {
value: void 0, writable: false, configurable: false
});
});
})(this);
""");
return engine;
}
}
@@ -1,118 +1,11 @@
package cn.qaiu.parser.customjs;
import org.openjdk.nashorn.api.scripting.ClassFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* JavaScript执行器安全类过滤器
* 用于限制JavaScript代码可以访问的Java类,防止恶意代码执行危险操作
*
* @author <a href="https://qaiu.top">QAIU</a>
*/
/** Scripts work through the supplied parser APIs and may not resolve Java classes by name. */
public class SecurityClassFilter implements ClassFilter {
private static final Logger log = LoggerFactory.getLogger(SecurityClassFilter.class);
// 危险类黑名单
private static final String[] DANGEROUS_CLASSES = {
// 系统命令执行
"java.lang.Runtime",
"java.lang.ProcessBuilder",
"java.lang.Process",
// 文件系统访问
"java.io.File",
"java.io.FileInputStream",
"java.io.FileOutputStream",
"java.io.FileReader",
"java.io.FileWriter",
"java.io.RandomAccessFile",
"java.nio.file.Files",
"java.nio.file.Paths",
"java.nio.file.Path",
"java.nio.channels.FileChannel",
// 系统访问
"java.lang.System",
"java.lang.SecurityManager",
// 反射相关
"java.lang.Class",
"java.lang.reflect.Method",
"java.lang.reflect.Field",
"java.lang.reflect.Constructor",
"java.lang.reflect.AccessibleObject",
"java.lang.ClassLoader",
// 网络访问
"java.net.Socket",
"java.net.ServerSocket",
"java.net.DatagramSocket",
"java.net.URL",
"java.net.URLConnection",
"java.net.HttpURLConnection",
"java.net.InetAddress",
// 线程和并发
"java.lang.Thread",
"java.lang.ThreadGroup",
"java.util.concurrent.Executor",
"java.util.concurrent.ExecutorService",
// 数据库访问
"java.sql.Connection",
"java.sql.Statement",
"java.sql.PreparedStatement",
"java.sql.DriverManager",
// 脚本引擎(防止嵌套执行)
"javax.script.ScriptEngine",
"javax.script.ScriptEngineManager",
// JVM控制
"java.lang.invoke.MethodHandle",
"sun.misc.Unsafe",
// Nashorn内部类
"jdk.nashorn.internal",
"jdk.internal",
};
@Override
public boolean exposeToScripts(String className) {
// 检查是否在黑名单中
for (String dangerous : DANGEROUS_CLASSES) {
if (className.equals(dangerous) || className.startsWith(dangerous + ".")) {
log.warn("🔒 安全拦截: JavaScript尝试访问危险类 - {}", className);
return false;
}
}
// 额外的包级别限制
String[] dangerousPackages = {
"java.lang.reflect.",
"java.io.",
"java.nio.",
"java.net.",
"java.sql.",
"javax.script.",
"sun.",
"jdk.internal.",
"jdk.nashorn.internal."
};
for (String pkg : dangerousPackages) {
if (className.startsWith(pkg)) {
log.warn("🔒 安全拦截: JavaScript尝试访问危险包 - {}", className);
return false;
}
}
// 默认也拒绝(白名单策略更安全,但这里为了兼容性使用黑名单)
// 如果要更严格,可以改为 return false
log.debug("允许访问类: {}", className);
return true;
return false;
}
}
@@ -0,0 +1,264 @@
package cn.qaiu.parser.impl;
import io.vertx.core.json.JsonObject;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* ALTCHA v2(PBKDF2/SHA-256)挑战解算。
* <p>
* 口令是 nonce 的原始字节再拼上大端 uint32 计数器,盐是 salt 的原始字节。
* 找到派生密钥以 keyPrefix 开头的计数器后,按官方 widget 的方式拼出
* {@code base64({"challenge":{parameters,signature},"solution":{counter,derivedKey,time}})}。
* 计算是 CPU 密集的,调用方必须放在 Vert.x worker 上,不能占用 event loop。
*/
final class AltchaV2Solver {
static final int DEFAULT_MAX_COUNTER = 200_000;
static final long DEFAULT_TIMEOUT_MILLIS = 25_000L;
/** 城通当前 cost=1200。更高的 cost 会把解析线程占满,直接拒绝。 */
static final int MAX_COST = 20_000;
static final int MAX_KEY_LENGTH = 64;
private static final int MAX_THREADS = 4;
private AltchaV2Solver() {
}
static final class Solution {
final int counter;
final String derivedKeyHex;
final long tookMillis;
Solution(int counter, String derivedKeyHex, long tookMillis) {
this.counter = counter;
this.derivedKeyHex = derivedKeyHex;
this.tookMillis = tookMillis;
}
}
static Solution solve(JsonObject challenge) {
return solve(challenge, DEFAULT_MAX_COUNTER, DEFAULT_TIMEOUT_MILLIS);
}
static Solution solve(JsonObject challenge, int maxCounter, long timeoutMillis) {
if (challenge == null || challenge.getJsonObject("parameters") == null) {
throw new IllegalArgumentException("ALTCHA 挑战为空");
}
JsonObject parameters = challenge.getJsonObject("parameters");
String algorithm = parameters.getString("algorithm", "");
if (!"PBKDF2/SHA-256".equals(algorithm)) {
throw new IllegalArgumentException("不支持的 ALTCHA 算法: " + algorithm);
}
int cost = intValue(parameters.getValue("cost"), -1);
int keyLength = intValue(parameters.getValue("keyLength"), 32);
if (cost < 1 || cost > MAX_COST) {
throw new IllegalArgumentException("ALTCHA cost 超出可解范围: " + cost);
}
if (keyLength < 16 || keyLength > MAX_KEY_LENGTH) {
throw new IllegalArgumentException("ALTCHA keyLength 超出可解范围: " + keyLength);
}
byte[] nonce = decodeHex(parameters.getString("nonce", ""), "nonce");
byte[] salt = decodeHex(parameters.getString("salt", ""), "salt");
byte[] prefix = decodeHex(parameters.getString("keyPrefix", ""), "keyPrefix");
if (prefix.length == 0 || prefix.length > keyLength) {
throw new IllegalArgumentException("ALTCHA keyPrefix 长度无效");
}
int limit = Math.max(1, maxCounter);
long budget = Math.max(1L, timeoutMillis);
int threads = Math.min(MAX_THREADS, Math.max(1, Runtime.getRuntime().availableProcessors()));
threads = Math.min(threads, limit);
AtomicInteger winner = new AtomicInteger(-1);
AtomicBoolean stop = new AtomicBoolean(false);
String[] derivedHex = new String[1];
long started = System.nanoTime();
long deadline = started + TimeUnit.MILLISECONDS.toNanos(budget);
ExecutorService pool = Executors.newFixedThreadPool(threads, runnable -> {
Thread thread = new Thread(runnable, "ctfile-altcha");
thread.setDaemon(true);
return thread;
});
try {
Future<?>[] tasks = new Future<?>[threads];
for (int i = 0; i < threads; i++) {
int start = i;
int stride = threads;
tasks[i] = pool.submit((Callable<Void>) () -> {
search(start, stride, limit, deadline, nonce, salt, prefix, cost, keyLength, winner, stop, derivedHex);
return null;
});
}
for (Future<?> task : tasks) {
task.get(budget + 2000L, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
stop.set(true);
throw new IllegalStateException("ALTCHA 解算被中断");
} catch (IllegalStateException e) {
stop.set(true);
throw e;
} catch (Exception e) {
stop.set(true);
throw new IllegalStateException("ALTCHA 解算失败: " + e.getMessage());
} finally {
stop.set(true);
pool.shutdownNow();
}
int counter = winner.get();
if (counter < 0 || derivedHex[0] == null) {
throw new IllegalStateException("ALTCHA 人机验证解算超时,请稍后重试");
}
long took = Math.max(1L, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started));
return new Solution(counter, derivedHex[0], took);
}
/**
* 官方 altcha widget 成功后提交的 payload:标准 Base64(含填充),不是 URL-safe。
*/
static String payload(JsonObject challenge, Solution solution) {
JsonObject body = new JsonObject()
.put("challenge", new JsonObject()
.put("parameters", challenge.getJsonObject("parameters"))
.put("signature", challenge.getString("signature")))
.put("solution", new JsonObject()
.put("counter", solution.counter)
.put("derivedKey", solution.derivedKeyHex)
.put("time", solution.tookMillis));
return Base64.getEncoder().encodeToString(body.encode().getBytes(StandardCharsets.UTF_8));
}
/**
* PBKDF2-HMAC-SHA256,口令是原始字节。
* JDK 的 {@code SecretKeyFactory("PBKDF2WithHmacSHA256")} 会把 char[] 口令按 UTF-8 编码,
* nonce 里大于 0x7F 的字节会被展开,和 ALTCHA / WebCrypto 的原始字节口令对不上。
*/
static byte[] pbkdf2(byte[] password, byte[] salt, int cost, int keyLength) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(password, "HmacSHA256"));
return pbkdf2(mac, salt, cost, keyLength);
} catch (Exception e) {
throw new IllegalStateException("PBKDF2 计算失败: " + e.getMessage());
}
}
private static void search(int start, int stride, int limit, long deadline, byte[] nonce, byte[] salt,
byte[] prefix, int cost, int keyLength, AtomicInteger winner, AtomicBoolean stop,
String[] derivedHex) {
Mac mac;
try {
mac = Mac.getInstance("HmacSHA256");
} catch (Exception e) {
throw new IllegalStateException("PBKDF2 初始化失败: " + e.getMessage());
}
for (int counter = start; counter < limit && winner.get() < 0 && !stop.get(); counter += stride) {
if ((counter & 31) == start && System.nanoTime() > deadline) {
return;
}
byte[] derived;
try {
mac.init(new SecretKeySpec(password(nonce, counter), "HmacSHA256"));
derived = pbkdf2(mac, salt, cost, keyLength);
} catch (Exception e) {
throw new IllegalStateException("PBKDF2 计算失败: " + e.getMessage());
}
if (startsWith(derived, prefix) && winner.compareAndSet(-1, counter)) {
derivedHex[0] = toHex(derived);
return;
}
}
}
private static byte[] pbkdf2(Mac mac, byte[] salt, int iterations, int keyLength) throws Exception {
int hashLength = mac.getMacLength();
byte[] result = new byte[keyLength];
byte[] block = new byte[salt.length + 4];
System.arraycopy(salt, 0, block, 0, salt.length);
int offset = 0;
for (int index = 1; offset < keyLength; index++) {
block[salt.length] = (byte) (index >>> 24);
block[salt.length + 1] = (byte) (index >>> 16);
block[salt.length + 2] = (byte) (index >>> 8);
block[salt.length + 3] = (byte) index;
byte[] mixed = mac.doFinal(block);
byte[] digest = mixed.clone();
for (int round = 1; round < iterations; round++) {
mixed = mac.doFinal(mixed);
for (int i = 0; i < mixed.length; i++) {
digest[i] ^= mixed[i];
}
}
int length = Math.min(hashLength, keyLength - offset);
System.arraycopy(digest, 0, result, offset, length);
offset += length;
}
return result;
}
private static byte[] password(byte[] nonce, int counter) {
byte[] password = Arrays.copyOf(nonce, nonce.length + 4);
password[nonce.length] = (byte) (counter >>> 24);
password[nonce.length + 1] = (byte) (counter >>> 16);
password[nonce.length + 2] = (byte) (counter >>> 8);
password[nonce.length + 3] = (byte) counter;
return password;
}
private static boolean startsWith(byte[] value, byte[] prefix) {
if (prefix.length > value.length) {
return false;
}
for (int i = 0; i < prefix.length; i++) {
if (value[i] != prefix[i]) {
return false;
}
}
return true;
}
static byte[] decodeHex(String hex, String name) {
if (hex == null || hex.length() % 2 != 0 || !hex.matches("[0-9a-fA-F]*")) {
throw new IllegalArgumentException("ALTCHA " + name + " 不是合法十六进制");
}
byte[] out = new byte[hex.length() / 2];
for (int i = 0; i < out.length; i++) {
out[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return out;
}
static String toHex(byte[] bytes) {
StringBuilder builder = new StringBuilder(bytes.length * 2);
for (byte value : bytes) {
builder.append(Character.forDigit((value >> 4) & 0xF, 16));
builder.append(Character.forDigit(value & 0xF, 16));
}
return builder.toString();
}
private static int intValue(Object value, int fallback) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value == null) {
return fallback;
}
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return fallback;
}
}
}
@@ -37,6 +37,7 @@ public class Ce4Tool extends PanBase {
try {
URL url = new URL(shareLinkInfo.getShareUrl());
assertPublicHost(url);
String baseUrl = url.getProtocol() + "://" + url.getHost();
// 如果有端口,拼接上端口
if (url.getPort() != -1) {
@@ -110,7 +111,8 @@ public class Ce4Tool extends PanBase {
private void requestShareDetail(String baseUrl, String key, String pwd, String path) {
String shareApiUrl = baseUrl + SHARE_API_PATH + key;
HttpRequest<Buffer> httpRequest = clientSession.getAbs(shareApiUrl);
// 禁止跟随重定向:防止公网 host 302 到内网/元数据绕过 assertPublicHost
HttpRequest<Buffer> httpRequest = clientNoRedirects.getAbs(shareApiUrl);
if (pwd != null && !pwd.isEmpty()) {
httpRequest.addQueryParam("password", pwd);
}
@@ -231,7 +233,7 @@ public class Ce4Tool extends PanBase {
.put("uris", new JsonArray().add(filePath))
.put("download", true);
clientSession.postAbs(fileUrlApi)
clientNoRedirects.postAbs(fileUrlApi)
.putHeader("Content-Type", "application/json")
.sendJsonObject(requestBody)
.onSuccess(res -> {
@@ -43,6 +43,7 @@ public class CeTool extends PanBase {
String pwd = shareLinkInfo.getSharePassword();
try {
URL url = new URL(shareLinkInfo.getShareUrl());
assertPublicHost(url);
String baseUrl = url.getProtocol() + "://" + url.getHost();
// 如果有端口,拼接上端口
if (url.getPort() != -1) {
@@ -77,7 +78,8 @@ public class CeTool extends PanBase {
private void tryV4Ping(String baseUrl, String key, String pwd) {
String pingUrlV4 = baseUrl + PING_API_V4_PATH;
clientSession.getAbs(pingUrlV4).send().onSuccess(res -> {
// 禁止跟随重定向:assertPublicHost 只校验初始 host,自动 30x 会绕过 SSRF 防护
clientNoRedirects.getAbs(pingUrlV4).send().onSuccess(res -> {
if (res.statusCode() == 200) {
try {
JsonObject json = asJson(res);
@@ -107,7 +109,7 @@ public class CeTool extends PanBase {
private void tryV3Ping(String baseUrl, String key, String pwd) {
String pingUrlV3 = baseUrl + PING_API_V3_PATH;
clientSession.getAbs(pingUrlV3).send().onSuccess(res -> {
clientNoRedirects.getAbs(pingUrlV3).send().onSuccess(res -> {
if (res.statusCode() == 200) {
try {
JsonObject json = asJson(res);
@@ -138,7 +140,7 @@ public class CeTool extends PanBase {
*/
private void verifyV3AndParse(String baseUrl, String key, String pwd) {
String shareApiUrl = baseUrl + SHARE_API_PATH + key;
HttpRequest<Buffer> httpRequest = clientSession.getAbs(shareApiUrl);
HttpRequest<Buffer> httpRequest = clientNoRedirects.getAbs(shareApiUrl);
if (pwd != null && !pwd.isEmpty()) {
httpRequest.addQueryParam("password", pwd);
}
@@ -174,7 +176,7 @@ public class CeTool extends PanBase {
*/
private void tryV4ShareApi(String baseUrl, String key, String pwd) {
String shareApiUrl = baseUrl + "/api/v4/share/info/" + key;
HttpRequest<Buffer> httpRequest = clientSession.getAbs(shareApiUrl);
HttpRequest<Buffer> httpRequest = clientNoRedirects.getAbs(shareApiUrl);
if (pwd != null && !pwd.isEmpty()) {
httpRequest.addQueryParam("password", pwd);
}
@@ -290,7 +292,8 @@ public class CeTool extends PanBase {
}
private void getDownURL(String shareApiUrl) {
clientSession.putAbs(shareApiUrl)
// PUT 默认不跟随重定向,但仍统一使用 no-redirect 客户端避免配置漂移
clientNoRedirects.putAbs(shareApiUrl)
.putHeader("Referer", shareLinkInfo.getShareUrl())
.send().onSuccess(res -> {
JsonObject jsonObject = asJson(res);
@@ -1,345 +1,112 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.PanBase;
import cn.qaiu.parser.impl.CtfileSession.CtfileException;
import cn.qaiu.parser.impl.CtfileSession.DirectLink;
import cn.qaiu.parser.impl.CtfileSession.ShareTarget;
import cn.qaiu.parser.impl.CtfileSession.VerificationMismatch;
import cn.qaiu.util.CommonUtils;
import cn.qaiu.util.FileSizeConverter;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.WorkerExecutor;
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>
* 城通网盘。免密和带访问密码的分享都先走匿名网页接口和 ALTCHA v2。
* 官方客户端 {@code /v4} 只在匿名结果仍是 Turnstile、且调用方自己配置了登录令牌时回退。
*/
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;
private static final int DEFAULT_MAX_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
private static final String API1 = API_URL_PREFIX + "/getfile.php?path={path}" +
"&f={shareKey}&passcode={pwd}&r={rand}&ref=&url={url}";
private static final Object WORKER_LOCK = new Object();
private static volatile WorkerExecutor sharedWorker;
private static volatile boolean workerShutdown;
// 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/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*['\"]([^'\"]+)['\"]\\)");
/**
* 子类重写此构造方法不需要添加额外逻辑
* 如:
* <blockquote><pre>
* public XxTool(String key, String pwd) {
* super(key, pwd);
* }
* </pre></blockquote>
*
* @param shareLinkInfo 分享链接信息
*/
public CtTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
}
public static void shutdownWorkerExecutor() {
synchronized (WORKER_LOCK) {
workerShutdown = true;
if (sharedWorker != null) {
sharedWorker.close();
sharedWorker = null;
}
}
}
@Override
public Future<String> parse() {
final String shareKey = shareLinkInfo.getShareKey();
if (shareKey == null || shareKey.indexOf('-') == -1) {
fail("shareKey格式不正确找不到'-': {}", shareKey);
String shareKey = shareLinkInfo.getShareKey();
if (shareKey == null || shareKey.isBlank()) {
fail("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());
HttpRequest<Buffer> bufferHttpRequest1 = withCtAjaxHeaders(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());
bufferHttpRequest1
.send().onSuccess(res -> {
try {
var resJson = asJson(res);
if (resJson == null || resJson.isEmpty()) {
fail("解析失败, 上游返回空响应或非JSON响应");
return;
}
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());
}
}).onFailure(t -> fail("文件信息请求失败: {}", t.getMessage()));
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());
worker().executeBlocking(() -> {
ParsedDownload link = resolveDownload(shareKey);
shareLinkInfo.getOtherParam().put("fileInfo", fileInfoFrom(link.file));
if (link.fileDir != null && !link.fileDir.isBlank()) {
shareLinkInfo.getOtherParam().put("ctFileDir", link.fileDir);
}
return link;
}, false).onSuccess(link -> {
if (link.headers == null || link.headers.isEmpty()) {
complete(link.url);
} else {
completeWithMeta(link.url, link.headers);
}
}).onFailure(error -> fail("{}", rootMessage(error)));
} catch (RuntimeException e) {
fail("{}", e.getMessage());
}
return promise.future();
}
@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为空");
String shareKey = shareLinkInfo.getShareKey();
if (shareKey == null || shareKey.isBlank()) {
listPromise.fail(baseMsg() + " - 解析异常: shareKey为空");
return listPromise.future();
}
String[] split = shareKey.split("-");
if (split.length < 2) {
listPromise.fail(baseMsg() + " shareKey格式不正确: " + shareKey);
return listPromise.future();
try {
worker().executeBlocking(() -> listDirectory(shareKey), false)
.onSuccess(listPromise::complete)
.onFailure(error -> {
if (!listPromise.future().isComplete()) {
listPromise.fail(baseMsg() + " - 解析异常: " + rootMessage(error));
}
});
} catch (RuntimeException e) {
listPromise.fail(baseMsg() + " - 解析异常: " + e.getMessage());
}
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();
fail("缺少下载参数paramJson");
return promise.future();
}
JsonObject paramJson = (JsonObject) paramValue;
if (!applyFileParam(shareLinkInfo, paramJson)) {
Promise<String> parsePromise = Promise.promise();
parsePromise.fail(baseMsg() + " 下载参数id为空");
return parsePromise.future();
if (!applyFileParam(shareLinkInfo, (JsonObject) paramValue)) {
fail("下载参数id为空");
return promise.future();
}
return parse();
}
@@ -350,324 +117,298 @@ public class CtTool extends PanBase {
return false;
}
shareLinkInfo.setSharePassword(paramJson.getString("pwd", ""));
String xtlink = paramJson.getString("xtlink", "");
if (!xtlink.isBlank()) {
shareLinkInfo.getOtherParam().put("ctXtlink", xtlink);
shareLinkInfo.getOtherParam().put("ctV4FileId", fileShareKey);
String parentKey = paramJson.getString("shareKey", "");
if (!parentKey.isBlank()) {
shareLinkInfo.setShareKey(parentKey);
} else if (shareLinkInfo.getShareKey() == null || shareLinkInfo.getShareKey().isBlank()) {
shareLinkInfo.setShareKey(fileShareKey);
}
return true;
}
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);
private ParsedDownload resolveDownload(String shareKey) throws Exception {
if (requiresV4()) {
return downloadWithV4(shareKey);
}
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);
VerificationMismatch mismatch = null;
for (int attempt = 0; attempt < 2; attempt++) {
try (CtfileSession session = CtfileSession.open(shareLinkInfo)) {
try {
return downloadOnce(session, shareKey);
} catch (VerificationMismatch retryable) {
// verifycode 和签发它的那次连接绑在一起。换一个客户端再取一次。
mismatch = retryable;
} catch (CtfileException e) {
if (turnstile(e) && CtfileV4Client.hasCredentials(shareLinkInfo)) {
return downloadWithV4(shareKey);
}
throw e;
}
}
if (folderId == null || folderId.isBlank()) {
}
throw mismatch == null ? new CtfileException("未返回下载地址") : mismatch;
}
private ParsedDownload downloadWithV4(String shareKey) throws Exception {
if (!CtfileV4Client.hasCredentials(shareLinkInfo)) {
throw new CtfileException(CtfileV4Client.missingAccountMessage());
}
CtfileV4Client.DirectLink link = new CtfileV4Client(shareLinkInfo).downloadShare(shareKey, directoryShare());
return new ParsedDownload(link.url, java.util.Map.of(), link.file, "");
}
/** 只有 v4 目录列表生成的文件参数才直接走客户端协议。访问密码本身不触发登录。 */
static boolean requiresV4(ShareLinkInfo info) {
if (info == null || info.getOtherParam() == null) {
return false;
}
Object fileId = info.getOtherParam().get("ctV4FileId");
return fileId != null && !fileId.toString().isBlank();
}
private boolean requiresV4() {
return requiresV4(shareLinkInfo);
}
private static boolean turnstile(CtfileException error) {
return error.getMessage() != null && error.getMessage().contains("Turnstile");
}
private boolean directoryShare() {
String type = shareLinkInfo.getType();
if (type != null && type.equalsIgnoreCase("ctd")) {
return true;
}
String url = shareLinkInfo.getShareUrl();
return url != null && url.matches("(?i).*/d/[^/].*");
}
private ParsedDownload downloadOnce(CtfileSession session, String shareKey) throws Exception {
String password = shareLinkInfo.getSharePassword();
ShareTarget target = ShareTarget.from(shareLinkInfo);
JsonObject resource = session.loadResource("file", shareKey, target, password, turnstileToken());
JsonObject data = CtfileSession.dataOf(resource);
JsonObject file = data == null ? null : data.getJsonObject("file");
if (file == null) {
throw new CtfileException("下载参数不完整:上游没有返回文件信息");
}
DirectLink link = session.download(shareKey, target, password, resource);
return new ParsedDownload(link.url, link.headers, file, file.getString("file_dir", ""));
}
private List<FileInfo> listDirectory(String shareKey) throws Exception {
String password = shareLinkInfo.getSharePassword();
ShareTarget target = ShareTarget.from(shareLinkInfo);
int maxPages = maxListPages();
try (CtfileSession session = CtfileSession.open(shareLinkInfo)) {
JsonObject resource = session.loadResource("dir", shareKey, target, password, turnstileToken());
List<FileInfo> files = new ArrayList<>();
int start = 0;
for (int page = 0; page < maxPages; page++) {
JsonObject listing = session.listing("dir", shareKey, target, password, resource, start,
CtfileSession.pageSize());
int code = CtfileSession.intValue(listing.getValue("code"), 200);
if (code != 200) {
throw new CtfileException(CtfileSession.classify(listing, code, password).message);
}
JsonArray rows = CtfileSession.rowsOf(listing);
for (int i = 0; i < rows.size(); i++) {
if (rows.getValue(i) instanceof JsonObject row) {
FileInfo info = toFileInfo(row, shareLinkInfo);
if (info != null) {
files.add(info);
}
}
}
if (rows.isEmpty() || !CtfileSession.hasMore(listing, rows.size())) {
return files;
}
start += rows.size();
}
if (maxPages != DEFAULT_MAX_LIST_PAGES || shareLinkInfo.getOtherParam().containsKey("ctMaxListPages")) {
return files;
}
throw new CtfileException("目录文件过多,已超过 " + maxPages + " 页");
} catch (CtfileException e) {
if (turnstile(e) && CtfileV4Client.hasCredentials(shareLinkInfo)) {
return new CtfileV4Client(shareLinkInfo).listShare(shareKey, target.folderId, maxPages);
}
throw e;
}
}
static FileInfo toFileInfo(JsonObject row, ShareLinkInfo info) {
if (row == null) {
return null;
}
String name = row.getString("name", "").trim();
if (name.isBlank()) {
return null;
}
String kind = row.getString("kind", "");
String password = info.getSharePassword() == null ? "" : info.getSharePassword();
FileInfo fileInfo = new FileInfo()
.setFileName(name)
.setPanType(info.getType())
.setCreateBy(CtfileSession.text(row.getValue("ownerId")));
String date = row.getString("date", "");
if (!date.isBlank()) {
fileInfo.setCreateTime(date).setUpdateTime(date);
}
if ("folder".equals(kind)) {
String folderId = CtfileSession.text(row.getValue("folderId"));
if (folderId.isBlank()) {
return null;
}
String dirId = folderId + ":" + folderKey;
FileInfo fileInfo = new FileInfo()
.setFileName(fileName.trim())
.setFileId(folderId)
.setSize(0L)
.setSizeStr(sizeStr.isBlank() ? "0B" : sizeStr)
String folderKey = row.getString("folderKey", "");
fileInfo.setFileId(folderId)
.setFileType("folder")
.setFileIcon(fileIcon)
.setPanType(panType)
.setParserUrl(buildFolderParserUrl(domainName, shareUrl, dirId, pwd));
if (!dateStr.isBlank()) {
fileInfo.setCreateTime(dateStr).setUpdateTime(dateStr);
}
.setSize(0L)
.setSizeStr("0B")
.setParserUrl(buildFolderParserUrl(info, folderId + ":" + (folderKey == null ? "" : folderKey), password));
return fileInfo;
}
String fileShareKey = matchFirst(FILE_HREF_PATTERN, nameCellHtml);
if (fileShareKey == null || fileShareKey.isBlank()) {
if (!"file".equals(kind)) {
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) {
String fileKey = fileKeyFromHref(row.getString("href", ""));
if (fileKey.isBlank()) {
fileKey = CtfileSession.text(row.getValue("fileId"));
}
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);
if (fileKey.isBlank()) {
return null;
}
long size = CtfileSession.longValue(row.getValue("size_bytes"), 0L);
JsonObject param = new JsonObject()
.put("id", fileKey)
.put("fileName", name)
.put("pwd", password);
String encoded = CommonUtils.urlBase64Encode(param.encode());
String domain = info.getOtherParam() == null ? "" : info.getOtherParam().getOrDefault("domainName", "").toString();
fileInfo.setFileId(CtfileSession.firstNonBlank(CtfileSession.text(row.getValue("fileId")), fileKey))
.setFileType(CtfileSession.firstNonBlank(row.getString("extension"), "file"))
.setSize(size)
.setSizeStr(row.getString("size", ""))
.setParserUrl(domain + "/v2/redirectUrl/" + info.getType() + "/" + encoded);
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);
private static String buildFolderParserUrl(ShareLinkInfo info, String dirId, String password) {
String domain = info.getOtherParam() == null ? "" : info.getOtherParam().getOrDefault("domainName", "").toString();
String shareUrl = info.getShareUrl() == null ? "" : info.getShareUrl();
String url = domain + "/v2/getFileList?url=" + urlEncode(shareUrl) + "&dirId=" + urlEncode(dirId);
if (password != null && !password.isBlank()) {
url += "&pwd=" + urlEncode(password);
}
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);
private static String fileKeyFromHref(String href) {
if (href == null || href.isBlank()) {
return "";
}
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));
int marker = href.indexOf("/f/");
int skip = 3;
if (marker < 0) {
marker = href.indexOf("/file/");
skip = 6;
}
if (marker < 0) {
return "";
}
String rest = href.substring(marker + skip);
int cut = rest.length();
for (int i = 0; i < rest.length(); i++) {
char c = rest.charAt(i);
if (c == '?' || c == '#' || c == '/') {
cut = i;
break;
}
}
return null;
return rest.substring(0, cut);
}
static String extractPath(String shareUrl) {
if (shareUrl == null) {
private FileInfo fileInfoFrom(JsonObject file) {
long size = CtfileSession.longValue(file.getValue("file_size_bytes"), 0L);
FileInfo info = new FileInfo()
.setFileName(file.getString("file_name", ""))
.setFileId(CtfileSession.text(file.getValue("file_id")))
.setSize(size)
.setSizeStr(file.getString("file_size", ""))
.setFileType("file")
.setCreateBy(file.getString("username", ""))
.setPanType(shareLinkInfo.getType());
String created = file.getString("file_time", "");
if (!created.isBlank()) {
info.setCreateTime(created);
}
return info;
}
private String turnstileToken() {
if (shareLinkInfo.getOtherParam() == null) {
return "";
}
int comIdx = shareUrl.indexOf("com/");
if (comIdx < 0) {
return "";
Object value = shareLinkInfo.getOtherParam().get("turnstileToken");
return value == null ? "" : value.toString().trim();
}
private int maxListPages() {
if (shareLinkInfo.getOtherParam() == null || !shareLinkInfo.getOtherParam().containsKey("ctMaxListPages")) {
return DEFAULT_MAX_LIST_PAGES;
}
int configured = CtfileSession.intValue(shareLinkInfo.getOtherParam().get("ctMaxListPages"), DEFAULT_MAX_LIST_PAGES);
return configured < 1 ? 1 : configured;
}
int pathStart = comIdx + 4;
int pathEnd = shareUrl.indexOf('/', pathStart);
if (pathEnd < 0) {
pathEnd = shareUrl.indexOf('?', pathStart);
private static String rootMessage(Throwable error) {
Throwable current = error;
while (current.getCause() != null && current.getCause() != current
&& (current.getMessage() == null || current.getMessage().isBlank()
|| current.getClass().getName().contains("CompletionException")
|| current.getClass().getName().contains("ExecutionException"))) {
current = current.getCause();
}
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();
String message = current.getMessage();
return message == null || message.isBlank() ? current.getClass().getSimpleName() : message;
}
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 "";
private static WorkerExecutor worker() {
synchronized (WORKER_LOCK) {
if (workerShutdown) {
throw new IllegalStateException("城通解析线程池已关闭");
}
String origin = uri.getScheme() + "://" + uri.getHost();
return uri.getPort() > 0 ? origin + ":" + uri.getPort() : origin;
} catch (Exception e) {
return "";
if (sharedWorker == null) {
sharedWorker = WebClientVertxInit.get().createSharedWorkerExecutor("ctfile-worker", 4);
}
return sharedWorker;
}
}
static final class DirectoryContext {
final String folderId;
final String folderKey;
private static final class ParsedDownload {
final String url;
final java.util.Map<String, String> headers;
final JsonObject file;
final String fileDir;
DirectoryContext(String folderId, String folderKey) {
this.folderId = folderId;
this.folderKey = folderKey;
ParsedDownload(String url, java.util.Map<String, String> headers, JsonObject file, String fileDir) {
this.url = url;
this.headers = headers;
this.file = file;
this.fileDir = fileDir;
}
}
}
@@ -0,0 +1,692 @@
package cn.qaiu.parser.impl;
import cn.qaiu.entity.ShareLinkInfo;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 城通新版分享接口(api.ctfile.com/url/*)。
* <p>
* 一次解析专用一个 HttpClient:资源接口签发的 verifycode 绑定本次连接的出口 IP,
* 下载必须跟在同一次连接上的 resource 之后。访问令牌 access_pass 约 24 小时、按分享者复用,
* 用来跳过重复的 ALTCHA 计算。
*/
final class CtfileSession implements AutoCloseable {
static final String API = "https://api.ctfile.com";
private static final String CHALLENGE_PATH = "/url/captcha/altcha?captcha_action=share_passcode";
private static final String 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 Duration REQUEST_TIMEOUT = Duration.ofSeconds(20);
private static final int PAGE_SIZE = 200;
private static final long PASS_SKEW_MILLIS = 60_000L;
private static final ConcurrentHashMap<String, CachedPass> ACCESS_PASSES = new ConcurrentHashMap<>();
private final HttpClient client;
private final String origin;
private final String referer;
private CtfileSession(HttpClient client, String origin, String referer) {
this.client = client;
this.origin = origin;
this.referer = referer;
}
static CtfileSession open(ShareLinkInfo info) {
String shareUrl = info == null ? "" : info.getShareUrl();
String origin = originOf(shareUrl);
if (origin.isBlank()) {
origin = "https://www.ctfile.com";
}
String referer = shareUrl == null || shareUrl.isBlank() ? origin + "/" : shareUrl;
return new CtfileSession(newClient(info), origin, referer);
}
JsonObject loadResource(String kind, String id, ShareTarget target, String password, String turnstileToken)
throws Exception {
JsonObject body = getResource(kind, id, target, password, null, null, null);
Decision decision = classify(body, 200, password);
if (decision.kind == Kind.OK) {
remember(decision, password, null);
return body;
}
// 带密码分享的首次响应经常标成 turnstile,但提交一次 ALTCHA 后正确密码会直接 200。
// 过期的 access_pass 同样会回到这个分支,丢弃后重新计算。
if (shouldSolveAltcha(decision)) {
String cached = cachedPass(decision.ownerId, password);
if (cached != null) {
JsonObject retry = getResource(kind, id, target, password, null, null, cached);
Decision again = classify(retry, 200, password);
if (again.kind == Kind.OK) {
remember(again, password, cached);
return retry;
}
forget(decision.ownerId, password);
}
JsonObject challenge = challenge();
if (expiresSoon(challenge)) {
challenge = challenge();
}
AltchaV2Solver.Solution solution = AltchaV2Solver.solve(challenge);
String token = AltchaV2Solver.payload(challenge, solution);
JsonObject retry = getResource(kind, id, target, password, token, null, null);
Decision solved = classify(retry, 200, password);
if (solved.kind == Kind.OK) {
remember(solved, password, null);
return retry;
}
if (solved.kind == Kind.ALTCHA) {
throw new CtfileException("ALTCHA 人机验证未通过,请重试");
}
if (solved.kind == Kind.TURNSTILE && turnstileToken != null && !turnstileToken.isBlank()) {
JsonObject withTurnstile = getResource(kind, id, target, password, null, turnstileToken, null);
Decision afterTurnstile = classify(withTurnstile, 200, password);
if (afterTurnstile.kind == Kind.OK) {
remember(afterTurnstile, password, null);
return withTurnstile;
}
throw new CtfileException(afterTurnstile.message);
}
throw new CtfileException(solved.message);
}
throw new CtfileException(decision.message);
}
/** 匿名分享优先解 ALTCHA。首次响应写成 turnstile 时,正确密码仍可能被 ALTCHA 放行。 */
static boolean shouldSolveAltcha(Decision decision) {
return decision != null && (decision.kind == Kind.ALTCHA || decision.kind == Kind.TURNSTILE);
}
DirectLink download(String id, ShareTarget target, String password, JsonObject resource) throws Exception {
JsonObject data = dataOf(resource);
JsonObject file = data == null ? null : data.getJsonObject("file");
if (file == null) {
throw new CtfileException("下载参数不完整:上游没有返回文件信息");
}
String pass = firstNonBlank(data.getString("access_pass"), cachedPass(ownerId(data), password));
return postDownload(id, target, password, file, pass, 0);
}
JsonObject listing(String kind, String id, ShareTarget target, String password, JsonObject resource,
int start, int length) throws Exception {
JsonObject data = dataOf(resource);
String pass = data == null ? null : firstNonBlank(data.getString("access_pass"), cachedPass(ownerId(data), password));
Map<String, String> query = resourceQuery(kind, id, target, password, null, null, pass);
query.put("start", String.valueOf(Math.max(0, start)));
query.put("length", String.valueOf(Math.max(1, length)));
return exchange("GET", "/url/listing?" + form(query), null, origin, referer);
}
static int pageSize() {
return PAGE_SIZE;
}
private DirectLink postDownload(String id, ShareTarget target, String password, JsonObject file, String pass,
int waitedSeconds) throws Exception {
if (waitedSeconds > 120) {
throw new CtfileException("下载需要等待的时间过长");
}
String verify = file.getString("verifycode", "");
String fileChk = file.getString("file_chk", "");
if (verify.isBlank() || fileChk.isBlank() || file.getValue("file_id") == null || file.getValue("userid") == null) {
throw new CtfileException("下载参数不完整:缺少 file_chk 或 verifycode");
}
JsonObject context = new JsonObject()
.put("kind", "file")
.put("id", id)
.put("folder_id", target.folderId)
.put("fk", target.fk)
.put("passcode", password == null ? "" : password)
.put("type_id", target.typeId);
if (pass != null && !pass.isBlank()) {
context.put("access_pass", pass);
}
JsonObject original = new JsonObject()
.put("file_id", file.getValue("file_id"))
.put("userid", file.getValue("userid"))
.put("file_chk", fileChk)
.put("start_time", file.getValue("start_time"))
.put("wait_seconds", file.getValue("wait_seconds"));
JsonObject body = new JsonObject()
.put("context", context)
.put("app", false)
.put("verifycode", verify)
.put("original_file", original)
.put("carrier", 0);
JsonObject response = exchange("POST", "/url/download", body.encode().getBytes(StandardCharsets.UTF_8),
origin, referer);
int top = codeOf(response, 200);
JsonObject data = dataOf(response);
int code = data != null && data.getValue("code") != null ? codeOf(data, top) : top;
String message = firstNonBlank(response.getString("msg"), response.getString("message"),
data == null ? "" : firstNonBlank(data.getString("msg"), data.getString("message")));
if (code == 218) {
int remaining = intValue(data == null ? null : data.getValue("remaining_seconds"),
intValue(response.getValue("remaining_seconds"), 1));
remaining = Math.max(1, Math.min(remaining, 30));
sleepSeconds(remaining);
return postDownload(id, target, password, file, pass, waitedSeconds + remaining);
}
if (code == 219) {
throw new CtfileException("需要登录后才能下载");
}
if (code == 403 && message.toLowerCase().contains("verification")) {
throw new VerificationMismatch("下载校验未通过或已过期,请重试");
}
String downurl = data == null ? null : data.getString("downurl");
if (code != 200 || downurl == null || downurl.isBlank()) {
throw new CtfileException(message.isBlank()
? "未返回下载地址 (code=" + code + ")"
: "未返回下载地址: " + message);
}
Map<String, String> headers = new LinkedHashMap<>();
if (data.getValue("headers") instanceof JsonObject headerJson) {
for (String key : headerJson.fieldNames()) {
Object value = headerJson.getValue(key);
if (key != null && value != null && !value.toString().isBlank()) {
headers.put(key, value.toString());
}
}
}
return new DirectLink(downurl, headers);
}
private JsonObject getResource(String kind, String id, ShareTarget target, String password,
String altchaToken, String turnstileToken, String accessPass) throws Exception {
Map<String, String> params = resourceQuery(kind, id, target, password, altchaToken, turnstileToken, accessPass);
return exchange("GET", "/url/resource?" + form(params), null, origin, referer);
}
private JsonObject challenge() throws Exception {
return exchange("GET", CHALLENGE_PATH, null, "https://h5.ctfile.com",
"https://h5.ctfile.com/captcha/altcha.html");
}
private JsonObject exchange(String method, String path, byte[] body, String requestOrigin, String requestReferer)
throws Exception {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(API + path))
.timeout(REQUEST_TIMEOUT)
.header("User-Agent", UA)
.header("Accept", "application/json, text/plain, */*")
.header("Origin", requestOrigin)
.header("Referer", requestReferer);
if (body == null) {
builder.method(method, HttpRequest.BodyPublishers.noBody());
} else {
builder.header("Content-Type", "application/json");
builder.method(method, HttpRequest.BodyPublishers.ofByteArray(body));
}
HttpResponse<String> response;
try {
response = client.send(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CtfileException("请求被中断");
} catch (IOException e) {
throw new CtfileException("请求失败: " + e.getMessage());
}
String text = response.body();
if (text == null || text.isBlank()) {
throw new CtfileException("上游返回空响应 (HTTP " + response.statusCode() + ")");
}
try {
return new JsonObject(text);
} catch (Exception e) {
throw new CtfileException("上游返回了无法识别的响应 (HTTP " + response.statusCode() + ")");
}
}
static Map<String, String> resourceQuery(String kind, String id, ShareTarget target, String password,
String altchaToken, String turnstileToken, String accessPass) {
Map<String, String> query = new LinkedHashMap<>();
query.put("kind", kind == null || kind.isBlank() ? "file" : kind);
query.put("id", id == null ? "" : id);
query.put("folder_id", target.folderId);
query.put("fk", target.fk);
query.put("passcode", password == null ? "" : password);
query.put("type_id", target.typeId);
if (altchaToken != null && !altchaToken.isBlank()) {
query.put("altcha_token", altchaToken);
}
if (turnstileToken != null && !turnstileToken.isBlank()) {
query.put("turnstile_token", turnstileToken);
}
if (accessPass != null && !accessPass.isBlank()) {
query.put("access_pass", accessPass);
}
return query;
}
static String form(Map<String, String> query) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : query.entrySet()) {
if (entry.getValue() == null) {
continue;
}
if (builder.length() > 0) {
builder.append('&');
}
builder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
builder.append('=');
builder.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
}
return builder.toString();
}
static Decision classify(JsonObject body, int httpStatus, String password) {
int code = codeOf(body, httpStatus);
JsonObject data = dataOf(body);
String message = firstNonBlank(body == null ? "" : body.getString("msg"),
body == null ? "" : body.getString("message"));
String errorType = data == null ? "" : text(data.getValue("error_type"));
String captcha = data == null ? "" : text(data.getValue("captcha_type"));
JsonObject capabilities = data == null ? null : data.getJsonObject("capabilities");
boolean passcodeRequired = capabilities != null && Boolean.TRUE.equals(capabilities.getValue("passcodeRequired"));
String owner = capabilities == null ? "" : text(capabilities.getValue("ownerId"));
boolean passwordMissing = password == null || password.isBlank();
boolean captchaAsked = "captcha_required".equals(errorType) || errorType.startsWith("captcha_");
if (code == 200) {
return Decision.ok(owner, accessPass(data));
}
if (code == 404) {
return Decision.of(Kind.NOT_FOUND, owner, "分享不存在或已过期" + suffix(message));
}
if (code == 403) {
return Decision.of(Kind.INVALID, owner, "分享链接无效或已失效" + suffix(message));
}
if (code == 423) {
if ("passcode_incorrect".equals(errorType)) {
return Decision.of(Kind.BAD_PASSWORD, owner, "访问密码不正确" + suffix(message));
}
if (passwordMissing && passcodeRequired && !captchaAsked) {
return Decision.of(Kind.NEED_PASSWORD, owner, "需要访问密码");
}
if ("turnstile".equalsIgnoreCase(captcha)) {
return Decision.of(Kind.TURNSTILE, owner, "触发 Cloudflare Turnstile 人机验证,暂不支持服务端自动通过");
}
if ("altcha".equalsIgnoreCase(captcha)) {
return Decision.of(Kind.ALTCHA, owner, "需要完成 ALTCHA 人机验证");
}
if (passwordMissing && passcodeRequired) {
return Decision.of(Kind.NEED_PASSWORD, owner, "需要访问密码");
}
return Decision.of(Kind.OTHER, owner, "分享暂时无法访问" + suffix(message) + " (code=423)");
}
return Decision.of(Kind.OTHER, owner,
"上游返回异常 (code=" + code + ")" + suffix(message));
}
private static void remember(Decision decision, String password, String fallbackPass) {
String token = firstNonBlank(decision.accessPass, fallbackPass);
if (decision.ownerId == null || decision.ownerId.isBlank() || token == null || token.isBlank()) {
return;
}
long expiry = passExpiry(token);
if (expiry < System.currentTimeMillis() + PASS_SKEW_MILLIS) {
return;
}
ACCESS_PASSES.put(cacheKey(decision.ownerId, password), new CachedPass(token, expiry));
}
private static String cachedPass(String ownerId, String password) {
if (ownerId == null || ownerId.isBlank()) {
return null;
}
CachedPass cached = ACCESS_PASSES.get(cacheKey(ownerId, password));
if (cached == null) {
return null;
}
if (cached.expiresAtMillis < System.currentTimeMillis() + PASS_SKEW_MILLIS) {
ACCESS_PASSES.remove(cacheKey(ownerId, password), cached);
return null;
}
return cached.token;
}
private static void forget(String ownerId, String password) {
if (ownerId != null && !ownerId.isBlank()) {
ACCESS_PASSES.remove(cacheKey(ownerId, password));
}
}
static void clearCachedPasses() {
ACCESS_PASSES.clear();
}
private static String cacheKey(String ownerId, String password) {
return ownerId + "\n" + (password == null ? "" : password);
}
private static long passExpiry(String token) {
try {
String[] parts = token.split("\\.");
if (parts.length < 2) {
return System.currentTimeMillis() + Duration.ofMinutes(30).toMillis();
}
byte[] json = Base64.getUrlDecoder().decode(padBase64(parts[1]));
JsonObject payload = new JsonObject(new String(json, StandardCharsets.UTF_8));
Object expiry = payload.getValue("e");
if (expiry instanceof Number) {
return ((Number) expiry).longValue() * 1000L;
}
} catch (Exception ignored) {
// 解析不了有效期时按半小时使用,失效后会重新计算 ALTCHA。
}
return System.currentTimeMillis() + Duration.ofMinutes(30).toMillis();
}
private static boolean expiresSoon(JsonObject challenge) {
JsonObject parameters = challenge.getJsonObject("parameters");
if (parameters == null) {
return false;
}
Object expiry = parameters.getValue("expiresAt");
if (!(expiry instanceof Number)) {
return false;
}
long expiresAtMillis = ((Number) expiry).longValue() * 1000L;
return expiresAtMillis < System.currentTimeMillis() + 15_000L;
}
private static String accessPass(JsonObject data) {
return data == null ? "" : text(data.getValue("access_pass"));
}
private static String ownerId(JsonObject data) {
if (data == null) {
return "";
}
JsonObject capabilities = data.getJsonObject("capabilities");
return capabilities == null ? "" : text(capabilities.getValue("ownerId"));
}
static JsonObject dataOf(JsonObject body) {
if (body == null || !(body.getValue("data") instanceof JsonObject)) {
return null;
}
return body.getJsonObject("data");
}
static JsonArray rowsOf(JsonObject listing) {
JsonObject data = dataOf(listing);
if (data == null || !(data.getValue("rows") instanceof JsonArray)) {
return new JsonArray();
}
return data.getJsonArray("rows");
}
static boolean hasMore(JsonObject listing, int rowCount) {
JsonObject data = dataOf(listing);
if (data != null && data.getValue("hasMore") instanceof Boolean) {
return data.getBoolean("hasMore");
}
return rowCount >= PAGE_SIZE;
}
private static int codeOf(JsonObject body, int fallback) {
if (body == null) {
return fallback;
}
return intValue(body.getValue("code"), fallback);
}
static int intValue(Object value, int fallback) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value == null) {
return fallback;
}
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return fallback;
}
}
static long longValue(Object value, long fallback) {
if (value instanceof Number) {
return ((Number) value).longValue();
}
if (value == null) {
return fallback;
}
try {
return Long.parseLong(value.toString());
} catch (NumberFormatException e) {
return fallback;
}
}
private static String suffix(String message) {
return message == null || message.isBlank() ? "" : "(" + message + ")";
}
static String text(Object value) {
return value == null ? "" : value.toString().trim();
}
static String firstNonBlank(String... values) {
if (values == null) {
return "";
}
for (String value : values) {
if (value != null && !value.isBlank()) {
return value;
}
}
return "";
}
private static String padBase64(String value) {
int mod = value.length() % 4;
if (mod == 0) {
return value;
}
return value + "=".repeat(4 - mod);
}
private static void sleepSeconds(int seconds) throws CtfileException {
try {
Thread.sleep(seconds * 1000L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CtfileException("下载等待被中断");
}
}
private static String originOf(String shareUrl) {
if (shareUrl == null || shareUrl.isBlank()) {
return "";
}
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 String queryParam(String url, String name) {
if (url == null || name == null) {
return "";
}
int query = url.indexOf('?');
if (query < 0) {
return "";
}
String raw = url.substring(query + 1);
int hash = raw.indexOf('#');
if (hash >= 0) {
raw = raw.substring(0, hash);
}
for (String part : raw.split("&")) {
int eq = part.indexOf('=');
if (eq <= 0) {
continue;
}
String key = decode(part.substring(0, eq));
if (name.equals(key)) {
return decode(part.substring(eq + 1));
}
}
return "";
}
private static String decode(String value) {
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8);
} catch (Exception e) {
return value;
}
}
private static HttpClient newClient(ShareLinkInfo info) {
HttpClient.Builder builder = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NEVER);
Object proxyValue = info == null || info.getOtherParam() == null ? null : info.getOtherParam().get("proxy");
if (proxyValue instanceof JsonObject proxy) {
String host = proxy.getString("host");
Integer port = proxy.getInteger("port");
if (host != null && !host.isBlank() && port != null) {
builder.proxy(ProxySelector.of(new InetSocketAddress(host, port)));
String username = proxy.getString("username");
String password = proxy.getString("password", "");
if (username != null && !username.isBlank()) {
builder.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == RequestorType.PROXY) {
return new PasswordAuthentication(username, password.toCharArray());
}
return null;
}
});
}
}
}
return builder.build();
}
@Override
public void close() {
try {
client.getClass().getMethod("close").invoke(client);
} catch (NoSuchMethodException ignored) {
// JDK 17 的 HttpClient 还不能关闭,连接会按空闲超时回收。
} catch (Exception ignored) {
// 关闭失败不影响解析结果。
}
}
static final class ShareTarget {
final String folderId;
final String fk;
final String typeId;
ShareTarget(String folderId, String fk, String typeId) {
this.folderId = folderId == null || folderId.isBlank() ? "0" : folderId;
this.fk = fk == null ? "" : fk;
this.typeId = typeId == null || typeId.isBlank() ? "0" : typeId;
}
static ShareTarget from(ShareLinkInfo info) {
String dirId = "";
if (info.getOtherParam() != null && info.getOtherParam().get("dirId") != null) {
dirId = decode(info.getOtherParam().get("dirId").toString().trim());
}
if (!dirId.isBlank()) {
String[] parts = dirId.split(":", 2);
return new ShareTarget(parts[0], parts.length > 1 ? parts[1] : "",
queryParam(info.getShareUrl(), "type_id"));
}
String shareUrl = info.getShareUrl();
String folderId = firstNonBlank(queryParam(shareUrl, "folder_id"), queryParam(shareUrl, "d"));
return new ShareTarget(folderId, queryParam(shareUrl, "fk"), queryParam(shareUrl, "type_id"));
}
}
static final class DirectLink {
final String url;
final Map<String, String> headers;
DirectLink(String url, Map<String, String> headers) {
this.url = url;
this.headers = headers;
}
}
enum Kind {
OK, NOT_FOUND, INVALID, NEED_PASSWORD, BAD_PASSWORD, TURNSTILE, ALTCHA, OTHER
}
static final class Decision {
final Kind kind;
final String ownerId;
final String accessPass;
final String message;
private Decision(Kind kind, String ownerId, String accessPass, String message) {
this.kind = kind;
this.ownerId = ownerId == null ? "" : ownerId;
this.accessPass = accessPass == null ? "" : accessPass;
this.message = message == null ? "" : message;
}
static Decision ok(String ownerId, String accessPass) {
return new Decision(Kind.OK, ownerId, accessPass, "");
}
static Decision of(Kind kind, String ownerId, String message) {
return new Decision(kind, ownerId, "", message);
}
}
static class CtfileException extends Exception {
CtfileException(String message) {
super(message);
}
}
static final class VerificationMismatch extends CtfileException {
VerificationMismatch(String message) {
super(message);
}
}
private static final class CachedPass {
final String token;
final long expiresAtMillis;
CachedPass(String token, long expiresAtMillis) {
this.token = token;
this.expiresAtMillis = expiresAtMillis;
}
}
}
@@ -0,0 +1,679 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.TokenCache;
import cn.qaiu.parser.impl.CtfileSession.CtfileException;
import cn.qaiu.util.CommonUtils;
import io.vertx.core.MultiMap;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* 城通官方客户端协议 {@code /v4}。匿名 ALTCHA 仍被 Turnstile 拦住时的可选回退,
* 需要调用方自己的登录令牌。带访问密码的分享默认不走这里。
*/
final class CtfileV4Client {
static final String API = "https://api.ctfile.com";
private static final String UA = "Mozilla/5.0 CTFileApp/5.1.24";
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(20);
private static final long EXPIRY_SKEW_MILLIS = 60_000L;
private static final int PAGE_SIZE = 100;
private static final ConcurrentHashMap<String, Session> SESSIONS = new ConcurrentHashMap<>();
private static final HttpClient HTTP = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NEVER)
.build();
private final ShareLinkInfo shareLinkInfo;
CtfileV4Client(ShareLinkInfo shareLinkInfo) {
this.shareLinkInfo = shareLinkInfo;
}
static boolean hasCredentials(ShareLinkInfo info) {
return credentials(info).usable();
}
static String missingAccountMessage() {
return "匿名解析仍被 Cloudflare Turnstile 拦住,且未配置城通账号。"
+ "可在 app-dev.yml 配置 auths.ct.refresh_token 作为可选回退,或在请求 auth 中传入。"
+ "refresh_token 来自浏览器登录 pan.ctfile.com 后 Session Storage 中的 refresh_token;"
+ "token 可填当前 access token。目录类型 ctd 未单独配置时回退使用 ct。";
}
DirectLink downloadShare(String shareKey, boolean directory) throws Exception {
String explicitFileId = text(shareLinkInfo.getOtherParam().get("ctV4FileId"));
String xtlink = text(shareLinkInfo.getOtherParam().get("ctXtlink"));
if (xtlink.isBlank()) {
xtlink = CtfileXtlink.fromShare(shareKey, shareLinkInfo.getSharePassword(), directory && explicitFileId.isBlank());
}
if (xtlink == null) {
throw new CtfileException("这个分享标识不能转换成官方 xtlink");
}
String fileId = explicitFileId.isBlank()
? CtfileXtlink.prefixedId(shareId(shareKey), false)
: CtfileXtlink.prefixedId(explicitFileId, false);
if (fileId.isBlank()) {
throw new CtfileException("分享标识里没有文件 id,无法取直链");
}
String token = accessToken(false);
JsonObject listed = null;
try {
listed = post("/v4/public/browser/list", listBody(xtlink, "0", 0, 20), token);
} catch (V4CallException e) {
if (e.authenticationFailure()) {
token = recoverAuth(e, token);
try {
listed = post("/v4/public/browser/list", listBody(xtlink, "0", 0, 20), token);
} catch (V4CallException again) {
if (terminal(again)) {
throw again;
}
}
} else if (terminal(e)) {
throw e;
}
}
JsonObject matched = listed == null ? null : findItem(listed, fileId);
String url = fetchDownloadUrl(xtlink, fileId, token);
JsonObject file = new JsonObject()
.put("file_name", matched == null ? shareLinkInfo.getShareKey() : itemName(matched))
.put("file_id", CtfileXtlink.bareId(fileId))
.put("file_size_bytes", matched == null ? 0 : itemSize(matched))
.put("file_size", matched == null ? "" : String.valueOf(itemSize(matched)))
.put("username", "");
if (matched != null && !itemDate(matched).isBlank()) {
file.put("file_time", itemDate(matched));
}
return new DirectLink(url, file);
}
List<FileInfo> listShare(String shareKey, String folderId, int maxPages) throws Exception {
boolean directory = true;
String xtlink = CtfileXtlink.fromShare(shareKey, shareLinkInfo.getSharePassword(), directory);
if (xtlink == null) {
throw new CtfileException("这个分享标识不能转换成官方 xtlink");
}
String token = accessToken(false);
List<FileInfo> files = new ArrayList<>();
int start = 0;
String apiFolder = folderId == null || folderId.isBlank() || "0".equals(folderId) ? "0" : CtfileXtlink.bareId(folderId);
for (int page = 0; page < maxPages; page++) {
JsonObject body;
try {
body = post("/v4/public/browser/list", listBody(xtlink, apiFolder, start, PAGE_SIZE), token);
} catch (V4CallException e) {
token = recoverAuth(e, token);
body = post("/v4/public/browser/list", listBody(xtlink, apiFolder, start, PAGE_SIZE), token);
}
JsonArray rows = resultsOf(body);
if (rows.isEmpty()) {
return files;
}
for (int i = 0; i < rows.size(); i++) {
if (rows.getValue(i) instanceof JsonObject row) {
FileInfo info = toFileInfo(row, shareLinkInfo, xtlink);
if (info != null) {
files.add(info);
}
}
}
int total = totalOf(body);
start += rows.size();
if (rows.size() < PAGE_SIZE || (total >= 0 && start >= total)) {
return files;
}
}
return files;
}
private String fetchDownloadUrl(String xtlink, String fileId, String token) throws Exception {
JsonObject auth;
try {
auth = post("/v4/public/browser/create-download-auth", authBody(xtlink, CtfileXtlink.prefixedId(fileId, false)), token);
} catch (V4CallException e) {
token = recoverAuth(e, token);
auth = post("/v4/public/browser/create-download-auth", authBody(xtlink, CtfileXtlink.prefixedId(fileId, false)), token);
}
String signature = signatureOf(auth);
if (signature.isBlank()) {
throw new CtfileException("城通没有返回下载签名,可能是密码错误、分享失效或账号没有下载权限");
}
JsonObject fetched;
try {
fetched = post("/v4/public/browser/fetch-url", fetchBody(xtlink, CtfileXtlink.bareId(fileId), signature), token);
} catch (V4CallException e) {
token = recoverAuth(e, token);
fetched = post("/v4/public/browser/fetch-url", fetchBody(xtlink, CtfileXtlink.bareId(fileId), signature), token);
}
String url = downloadUrlOf(fetched);
if (url.isBlank()) {
throw new CtfileException("城通没有返回下载直链");
}
return url;
}
private String recoverAuth(V4CallException error, String currentToken) throws Exception {
if (!error.authenticationFailure()) {
throw error;
}
String refreshed = accessToken(true);
if (refreshed == null || refreshed.isBlank() || refreshed.equals(currentToken)) {
throw error;
}
return refreshed;
}
private String accessToken(boolean forceRefresh) throws Exception {
Credentials credentials = credentials(shareLinkInfo);
if (!credentials.usable()) {
throw new CtfileException(missingAccountMessage());
}
Session session = SESSIONS.computeIfAbsent(credentials.accountKey, key -> new Session());
synchronized (session) {
long now = System.currentTimeMillis();
if ((session.refreshToken == null || session.refreshToken.isBlank()) && credentials.refreshToken != null) {
session.refreshToken = credentials.refreshToken;
}
if ((session.accessToken == null || session.accessToken.isBlank()) && credentials.accessToken != null) {
session.accessToken = credentials.accessToken;
}
if (!forceRefresh && session.accessToken != null && !session.accessToken.isBlank()
&& (session.expiresAtMillis == 0 || session.expiresAtMillis - EXPIRY_SKEW_MILLIS > now)) {
return session.accessToken;
}
if (session.refreshToken == null || session.refreshToken.isBlank()) {
if (session.accessToken != null && !session.accessToken.isBlank() && !forceRefresh) {
session.expiresAtMillis = 0;
return session.accessToken;
}
throw new CtfileException("城通 access token 已失效,且没有可用的 refresh_token。请重新登录后更新配置。");
}
RefreshResult refreshed = refresh(session.refreshToken);
session.accessToken = refreshed.accessToken;
session.expiresAtMillis = now + refreshed.expiresInSeconds * 1000L;
if (refreshed.refreshToken != null && !refreshed.refreshToken.isBlank()
&& !refreshed.refreshToken.equals(session.refreshToken)) {
session.refreshToken = refreshed.refreshToken;
rememberRefreshToken(credentials, refreshed.refreshToken);
} else {
session.refreshToken = refreshed.refreshToken == null || refreshed.refreshToken.isBlank()
? session.refreshToken : refreshed.refreshToken;
}
TokenCache.putToken(credentials.cacheKey(), session.accessToken);
TokenCache.putExpire(credentials.cacheKey(), session.expiresAtMillis);
TokenCache.queueCachedTokenPersist(credentials.cacheKey(), session.accessToken, session.expiresAtMillis);
return session.accessToken;
}
}
private RefreshResult refresh(String refreshToken) throws Exception {
V4CallException first = null;
try {
return readRefresh(post("/v4/user/auth/refresh-token", refreshBody(refreshToken, false), null), refreshToken);
} catch (V4CallException e) {
first = e;
}
try {
return readRefresh(post("/v4/user/auth/refresh-token", refreshBody(refreshToken, true), null), refreshToken);
} catch (V4CallException e) {
throw first.messageKey.contains("invalid_refresh") ? first : e;
}
}
private JsonObject post(String path, JsonObject body, String accessToken) throws Exception {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(API + path))
.timeout(REQUEST_TIMEOUT)
.header("User-Agent", UA)
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.header("X-Client-Type", "native")
.header("X-Client-Version", "5.1.24")
.header("X-Client-Platform", "linux")
.header("X-Client-OS-Version", "6.1.0")
.header("X-Client-Arch", "x64")
.header("X-Client-Captcha", "image,turnstile,altcha,cap")
.POST(HttpRequest.BodyPublishers.ofString(body.encode()));
if (accessToken != null && !accessToken.isBlank()) {
builder.header("Authorization", "Bearer " + accessToken);
}
HttpResponse<String> response;
try {
response = HTTP.send(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CtfileException("城通客户端请求被中断");
} catch (IOException e) {
throw new CtfileException("城通客户端请求失败: " + e.getMessage());
}
String text = response.body() == null ? "" : response.body();
JsonObject json;
try {
json = new JsonObject(text);
} catch (Exception e) {
throw new CtfileException("城通客户端返回了无法识别的响应 (HTTP " + response.statusCode() + ")");
}
int code = CtfileSession.intValue(json.getValue("code"), response.statusCode());
if (code != 200) {
throw new V4CallException(code, json.getString("message", ""), json.getString("message_key", ""));
}
return json;
}
private void rememberRefreshToken(Credentials credentials, String refreshToken) {
if (credentials.auths != null) {
credentials.auths.set("refresh_token", refreshToken);
}
TokenCache.queueCredentialUpdate(credentials.cacheKey(), refreshToken);
try {
Object auths = WebClientVertxInit.get().sharedData().getLocalMap("local").get("auths");
if (auths instanceof JsonObject json) {
for (String type : new String[] {"ct", "ctd"}) {
JsonObject config = json.getJsonObject(type);
if (config != null && config.containsKey("refresh_token")) {
config.put("refresh_token", refreshToken);
}
}
}
} catch (RuntimeException ignored) {
// 单测或未启动服务时没有共享配置,进程内的 TokenCache 仍然保存新令牌。
}
}
static JsonObject listBody(String xtlink, String folderId, int start, int pageSize) {
Object folder = folderId != null && folderId.matches("\\d+") ? Long.parseLong(folderId) : folderId;
return new JsonObject()
.put("xtlink", xtlink)
.put("folder_id", folder)
.put("start", start)
.put("pagesize", pageSize);
}
static JsonObject authBody(String xtlink, String ids) {
return new JsonObject().put("xtlink", xtlink).put("ids", ids);
}
static JsonObject fetchBody(String xtlink, String fileId, String signature) {
return new JsonObject()
.put("file_id", fileId)
.put("download_sign", signature)
.put("xtlink", xtlink)
.put("carrier", 0);
}
static JsonObject refreshBody(String refreshToken, boolean rotate) {
JsonObject body = new JsonObject().put("refresh_token", refreshToken);
if (rotate) {
body.put("rotate_token", true);
}
return body;
}
static String describeFailure(int code, String message, String messageKey) {
String text = message == null ? "" : message;
String key = messageKey == null ? "" : messageKey;
String lower = (text + " " + key).toLowerCase();
if (lower.contains("invalid_refresh") || lower.contains("refresh token") || text.contains("refresh token")) {
return "城通 refresh_token 无效或已过期,请重新登录 pan.ctfile.com 后更新 auths.ct.refresh_token";
}
if (text.contains("扫码") || text.contains("登录保护") || lower.contains("qr") || lower.contains("captcha_required")) {
return "城通账号需要扫码或完成登录保护后,再更新 refresh_token";
}
if (text.contains("锁定") && !text.contains("无效的令牌") && !text.contains("令牌无效")) {
return "城通账号已锁定";
}
if (code == 401 || text.contains("无效的令牌") || text.contains("未登录") || text.contains("令牌无效")) {
return "城通登录令牌无效或账号已锁定";
}
if (code == 404 || text.contains("不存在") || text.contains("失效") || lower.contains("not found")) {
return "分享不存在或已过期";
}
if (text.contains("密码") || lower.contains("passcode") || lower.contains("password")) {
return "访问密码不正确";
}
if (code == 403) {
return "城通拒绝了这次下载" + (text.isBlank() ? "" : "(" + text + ")");
}
return "城通客户端接口返回错误 (code=" + code + ")" + (text.isBlank() ? "" : ":" + text);
}
static FileInfo toFileInfo(JsonObject item, ShareLinkInfo info, String xtlink) {
if (item == null) {
return null;
}
String name = itemName(item);
if (name.isBlank()) {
return null;
}
String key = itemKey(item);
boolean folder = isFolder(item, key);
String password = info.getSharePassword() == null ? "" : info.getSharePassword();
FileInfo fileInfo = new FileInfo()
.setFileName(name)
.setPanType(info.getType())
.setFileId(CtfileXtlink.bareId(key));
String date = itemDate(item);
if (!date.isBlank()) {
fileInfo.setCreateTime(date).setUpdateTime(date);
}
String domain = info.getOtherParam() == null ? "" : String.valueOf(info.getOtherParam().getOrDefault("domainName", ""));
if (folder) {
return fileInfo.setFileType("folder")
.setSize(0L)
.setSizeStr("0B")
.setParserUrl(domain + "/v2/getFileList?url=" + url(info.getShareUrl())
+ "&dirId=" + url(CtfileXtlink.bareId(key))
+ (password.isBlank() ? "" : "&pwd=" + url(password)));
}
long size = itemSize(item);
JsonObject param = new JsonObject()
.put("id", CtfileXtlink.prefixedId(key, false))
.put("pwd", password)
.put("fileName", name)
.put("xtlink", xtlink)
.put("shareKey", info.getShareKey() == null ? "" : info.getShareKey());
String kind = CtfileSession.firstNonBlank(text(item.getValue("icon")), text(item.getValue("ext")), "file");
return fileInfo.setFileType(kind)
.setSize(size)
.setSizeStr(size > 0 ? size + "B" : text(item.getValue("size")))
.setParserUrl(domain + "/v2/redirectUrl/" + info.getType() + "/"
+ CommonUtils.urlBase64Encode(param.encode()));
}
static Credentials credentials(ShareLinkInfo info) {
MultiMap auths = null;
if (info != null && info.getOtherParam() != null && info.getOtherParam().get("auths") instanceof MultiMap map) {
auths = map;
}
String refresh = firstAuth(auths, "refresh_token", "refreshToken");
String access = firstAuth(auths, "token", "authorization", "access_token", "accessToken");
String accountId = firstAuth(auths, "_configId");
if ((refresh == null || refresh.isBlank()) && (access == null || access.isBlank())) {
JsonObject shared = sharedAuth(info == null ? "" : info.getType());
if (shared != null) {
refresh = firstJson(shared, "refresh_token", "refreshToken");
access = firstJson(shared, "token", "authorization", "access_token", "accessToken");
}
}
if (accountId == null || accountId.isBlank()) {
accountId = refresh != null && !refresh.isBlank() ? "refresh" : "access";
}
return new Credentials(auths, accountId, blankToNull(refresh), blankToNull(stripBearer(access)));
}
static void clearSessions() {
SESSIONS.clear();
}
private static JsonObject sharedAuth(String type) {
try {
Object auths = WebClientVertxInit.get().sharedData().getLocalMap("local").get("auths");
if (!(auths instanceof JsonObject json)) {
return null;
}
JsonObject config = type == null ? null : json.getJsonObject(type);
if ((config == null || config.isEmpty()) && "ctd".equalsIgnoreCase(type)) {
config = json.getJsonObject("ct");
}
return config;
} catch (RuntimeException e) {
return null;
}
}
private static RefreshResult readRefresh(JsonObject json, String previous) throws CtfileException {
String token = firstJson(json, "token", "access_token", "accessToken");
JsonObject data = json.getJsonObject("data");
if ((token == null || token.isBlank()) && data != null) {
token = firstJson(data, "token", "access_token", "accessToken");
}
if (token == null || token.isBlank()) {
throw new CtfileException("刷新城通登录状态失败:上游没有返回 access token");
}
String rotated = firstJson(json, "refresh_token", "refreshToken");
if ((rotated == null || rotated.isBlank()) && data != null) {
rotated = firstJson(data, "refresh_token", "refreshToken");
}
int expires = CtfileSession.intValue(json.getValue("expires_in"), -1);
if (expires < 0 && data != null) {
expires = CtfileSession.intValue(data.getValue("expires_in"), 900);
}
if (expires < 0) {
expires = 900;
}
return new RefreshResult(token, rotated == null || rotated.isBlank() ? previous : rotated, expires);
}
private static String signatureOf(JsonObject json) {
JsonObject data = json.getJsonObject("data");
String signature = data == null ? "" : data.getString("download_signature", "");
if (signature.isBlank()) {
signature = json.getString("download_signature", "");
}
return signature;
}
private static String downloadUrlOf(JsonObject json) {
JsonObject data = json.getJsonObject("data");
String url = data == null ? "" : data.getString("download_url", "");
if (url.isBlank() && data != null) {
url = data.getString("url", "");
}
if (url.isBlank()) {
url = json.getString("download_url", "");
}
return url;
}
private static JsonArray resultsOf(JsonObject json) {
JsonObject data = json.getJsonObject("data");
if (data != null && data.getValue("results") instanceof JsonArray rows) {
return rows;
}
if (json.getValue("results") instanceof JsonArray rows) {
return rows;
}
return new JsonArray();
}
private static int totalOf(JsonObject json) {
JsonObject data = json.getJsonObject("data");
if (data == null) {
return -1;
}
int total = CtfileSession.intValue(data.getValue("totalNum"), -1);
return total >= 0 ? total : CtfileSession.intValue(data.getValue("num"), -1);
}
private static JsonObject findItem(JsonObject listed, String fileId) {
String bare = CtfileXtlink.bareId(fileId);
for (int i = 0; i < resultsOf(listed).size(); i++) {
if (!(resultsOf(listed).getValue(i) instanceof JsonObject row)) {
continue;
}
if (bare.equals(CtfileXtlink.bareId(itemKey(row)))) {
return row;
}
}
JsonArray rows = resultsOf(listed);
if (rows.size() == 1 && rows.getValue(0) instanceof JsonObject only && !isFolder(only, itemKey(only))) {
return only;
}
return null;
}
private static boolean isFolder(JsonObject item, String key) {
if (Boolean.TRUE.equals(item.getValue("is_folder"))) {
return true;
}
String type = item.getString("type", "");
String icon = item.getString("icon", "");
String ext = item.getString("ext", "");
return "folder".equalsIgnoreCase(type) || "folder".equalsIgnoreCase(icon) || "folder".equalsIgnoreCase(ext)
|| (key != null && key.startsWith("d"));
}
private static String itemKey(JsonObject item) {
return CtfileSession.firstNonBlank(text(item.getValue("fid")), text(item.getValue("key")), text(item.getValue("id")));
}
private static String itemName(JsonObject item) {
return item.getString("name", "").trim();
}
private static long itemSize(JsonObject item) {
long size = CtfileSession.longValue(item.getValue("size_bytes"), -1);
if (size >= 0) {
return size;
}
return CtfileSession.longValue(item.getValue("size"), 0);
}
private static String itemDate(JsonObject item) {
return CtfileSession.firstNonBlank(text(item.getValue("date")), text(item.getValue("file_time")));
}
private static String shareId(String shareKey) {
if (shareKey == null) {
return "";
}
String[] parts = shareKey.split("-");
return parts.length >= 2 ? parts[1] : "";
}
private static String firstAuth(MultiMap auths, String... keys) {
if (auths == null) {
return null;
}
for (String key : keys) {
String value = auths.get(key);
if (value != null && !value.isBlank()) {
return value.trim();
}
}
return null;
}
private static String firstJson(JsonObject json, String... keys) {
if (json == null) {
return null;
}
for (String key : keys) {
String value = json.getString(key);
if (value != null && !value.isBlank()) {
return value.trim();
}
}
return null;
}
private static String stripBearer(String token) {
if (token == null) {
return null;
}
String value = token.trim();
if (value.regionMatches(true, 0, "Bearer ", 0, 7)) {
return value.substring(7).trim();
}
return value;
}
private static String blankToNull(String value) {
return value == null || value.isBlank() ? null : value;
}
private static String text(Object value) {
return value == null ? "" : value.toString().trim();
}
private static String url(String value) {
return java.net.URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8);
}
static final class Credentials {
final MultiMap auths;
final String accountId;
final String refreshToken;
final String accessToken;
final String accountKey;
Credentials(MultiMap auths, String accountId, String refreshToken, String accessToken) {
this.auths = auths;
this.accountId = accountId;
this.refreshToken = refreshToken;
this.accessToken = accessToken;
this.accountKey = accountId == null ? "default" : accountId;
}
boolean usable() {
return (refreshToken != null && !refreshToken.isBlank()) || (accessToken != null && !accessToken.isBlank());
}
String cacheKey() {
return TokenCache.key("ct", accountKey);
}
}
static final class DirectLink {
final String url;
final JsonObject file;
DirectLink(String url, JsonObject file) {
this.url = url;
this.file = file;
}
}
private static final class Session {
String refreshToken;
String accessToken;
long expiresAtMillis;
}
private static final class RefreshResult {
final String accessToken;
final String refreshToken;
final int expiresInSeconds;
RefreshResult(String accessToken, String refreshToken, int expiresInSeconds) {
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.expiresInSeconds = expiresInSeconds;
}
}
static final class V4CallException extends CtfileException {
final int code;
final String messageKey;
V4CallException(int code, String message, String messageKey) {
super(describeFailure(code, message, messageKey));
this.code = code;
this.messageKey = messageKey == null ? "" : messageKey;
}
boolean authenticationFailure() {
return code == 401 || getMessage().contains("令牌") || getMessage().contains("锁定");
}
}
private static boolean terminal(V4CallException error) {
String message = error.getMessage() == null ? "" : error.getMessage();
return message.contains("密码") || message.contains("不存在") || message.contains("已过期") || message.contains("失效");
}
}
@@ -0,0 +1,71 @@
package cn.qaiu.parser.impl;
/**
* 把网页分享 key 转成官方客户端 xtlink。
* 免密是 {@code xturl{userid}-{f|d}{id}[-checksum]},
* 带密码是 {@code xtc{userid}-{f|d}{id}-{checksum}-{password}}。
*/
final class CtfileXtlink {
private CtfileXtlink() {
}
static String fromShare(String shareKey, String password, boolean directory) {
if (shareKey == null || shareKey.isBlank()) {
throw new IllegalArgumentException("分享标识为空,无法生成 xtlink");
}
String key = shareKey.trim();
if (key.startsWith("ctfile://")) {
key = key.substring("ctfile://".length());
}
if (key.startsWith("xturl") || key.startsWith("xtc")) {
return key;
}
if (key.startsWith("t-")) {
return null;
}
String[] parts = key.split("-");
if (parts.length < 2 || parts[0].isBlank() || parts[1].isBlank()) {
throw new IllegalArgumentException("分享标识无法转换成 xtlink: " + shareKey);
}
String userId = parts[0];
String rawId = parts[1];
String checksum = parts.length >= 3 ? parts[2] : "";
if (!rawId.matches("[fd]\\d+")) {
rawId = (directory ? "d" : "f") + rawId;
}
boolean hasPassword = password != null && !password.isBlank();
if (!hasPassword) {
return checksum.isEmpty()
? "xturl" + userId + "-" + rawId
: "xturl" + userId + "-" + rawId + "-" + checksum;
}
if (checksum.isEmpty()) {
return "xtc" + userId + "-" + rawId + "-" + password;
}
return "xtc" + userId + "-" + rawId + "-" + checksum + "-" + password;
}
static String prefixedId(String fileId, boolean directory) {
if (fileId == null || fileId.isBlank()) {
return "";
}
String value = fileId.trim();
if (value.matches("[fd]\\d+")) {
return value;
}
String digits = value.replaceAll("\\D", "");
if (digits.isEmpty()) {
return value;
}
return (directory || value.startsWith("d") ? "d" : "f") + digits;
}
static String bareId(String fileId) {
String prefixed = prefixedId(fileId, false);
if (prefixed.matches("[fd]\\d+")) {
return prefixed.substring(1);
}
return prefixed;
}
}
@@ -22,6 +22,7 @@ public class FcTool extends PanBase {
public static final String SHARE_URL_PREFIX = "https://v2.fangcloud.com/sharing/";
public static final String SHARE_URL_PREFIX2 = "https://v2.fangcloud.cn/sharing/";
private static final String SHARE_INFO_URL = "https://v2.fangcloud.cn/apps/share_links/info/";
private static final String DOWN_REQUEST_URL = "https://v2.fangcloud.cn/apps/files/download?file_id={fid}" +
"&scenario=share&unique_name={uname}";
@@ -38,6 +39,25 @@ public class FcTool extends PanBase {
final String dataKey = shareLinkInfo.getShareKey();
final String pwd = shareLinkInfo.getSharePassword();
WebClientSession sClient = WebClientSession.create(client);
// 先查询分享有效性, 避免分享已失效/已过期时仍去解析HTML, 报出令人困惑的技术错误
sClient.getAbs(SHARE_INFO_URL + dataKey).send().onSuccess(infoRes -> {
JsonObject infoJson = asJson(infoRes);
if (promise.future().isComplete()) {
return;
}
JsonObject process = infoJson.getJsonObject("process");
boolean isClosed = process != null && Boolean.TRUE.equals(process.getBoolean("is_closed"));
boolean isExpired = process != null && Boolean.TRUE.equals(process.getBoolean("is_expired"));
if (process == null || isClosed || isExpired) {
fail("分享已失效或不存在");
return;
}
doParse(dataKey, pwd, sClient);
}).onFailure(handleFail(SHARE_INFO_URL + dataKey));
return promise.future();
}
private void doParse(String dataKey, String pwd, WebClientSession sClient) {
// 第一次请求 自动重定向
sClient.getAbs(SHARE_URL_PREFIX + dataKey).send().onSuccess(res -> {
@@ -67,7 +87,6 @@ public class FcTool extends PanBase {
}
getDownURL(dataKey, promise, res, sClient);
}).onFailure(handleFail(SHARE_URL_PREFIX + dataKey));
return promise.future();
}
private void getDownURL(String dataKey, Promise<String> promise, HttpResponse<Buffer> res,
@@ -0,0 +1,71 @@
package cn.qaiu.parser.impl;
import cn.qaiu.util.AESUtils;
import io.vertx.core.json.JsonObject;
import org.apache.commons.lang3.StringUtils;
final class FjDownloadParams {
private FjDownloadParams() {
}
static JsonObject create(String fileId, String userId, String uuid, String shareId, long timestamp) {
if (StringUtils.isBlank(fileId) || StringUtils.isBlank(shareId)) {
throw new IllegalArgumentException("缺少 fileId 或 shareId");
}
return JsonObject.of("fileId", fileId,
"fidEncode", AESUtils.encrypt2Hex(fileId + "|" + StringUtils.defaultString(userId)),
"uuid", uuid, "shareId", shareId,
"ts", AESUtils.encrypt2Hex(Long.toString(timestamp)),
"auth", AESUtils.encrypt2Hex(fileId + "|" + timestamp));
}
static String fileId(JsonObject params) throws Exception {
String fileId = params.getString("fileId");
if (StringUtils.isNotBlank(fileId)) {
return fileId;
}
// 兼容已生成的目录链接,但不再复用其中的身份和过期签名。
String decoded = AESUtils.decryptByHexAES(params.getString("fidEncode"), AESUtils.CIPHER_AES0);
int separator = decoded.indexOf('|');
if (separator <= 0) {
throw new IllegalArgumentException("无效的 fidEncode");
}
return decoded.substring(0, separator);
}
static String ownerId(JsonObject params) throws Exception {
Object id = params.getValue("userId");
if (id != null && StringUtils.isNotBlank(id.toString())) {
return id.toString();
}
String encoded = params.getString("fidEncode");
if (StringUtils.isBlank(encoded)) {
return null;
}
String decoded = AESUtils.decryptByHexAES(encoded, AESUtils.CIPHER_AES0);
int separator = decoded.indexOf('|');
String owner = separator < 0 ? null : decoded.substring(separator + 1);
return StringUtils.isBlank(owner) || "null".equals(owner) ? null : owner;
}
static String missingLocation(int status, String body) {
String message = "未获取到下载重定向地址, HTTP " + status;
if (StringUtils.isBlank(body)) {
return message + ", 响应体为空";
}
try {
JsonObject json = new JsonObject(body);
if (StringUtils.isNotBlank(json.getString("msg"))) {
return message + ", 上游返回: " + preview(json.getString("msg"))
+ " (code=" + json.getValue("code") + ")";
}
} catch (RuntimeException ignored) {
// 非 JSON 错误页同样保留有限长度的诊断内容。
}
return message + ", 响应体: " + preview(body);
}
private static String preview(String value) {
return value.length() > 500 ? value.substring(0, 500) + "..." : value;
}
}
@@ -2,6 +2,7 @@ package cn.qaiu.parser.impl;
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.vertx.core.Future;
@@ -60,7 +61,10 @@ public class FjTool extends PanBase {
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
"={uuid}&extra=2&timestamp={ts}&shareId={shareId}&folderId" +
"={folderId}&offset=1&limit=60";
"={folderId}&offset={offset}&limit={limit}";
/** share/list 每页条数;offset 是从 1 开始的页码。 */
static final int LIST_LIMIT = 60;
private static final MultiMap header;
private static final MultiMap header0;
@@ -129,8 +133,6 @@ public class FjTool extends PanBase {
if (auths.contains("userId")) {
FjTool.userId = auths.get("userId");
log.info("已配置用户ID: {}", FjTool.userId);
} else {
log.warn("未配置用户ID, 可能会导致解析失败");
}
}
@@ -199,7 +201,7 @@ public class FjTool extends PanBase {
// 其他参数
long nowTs2 = System.currentTimeMillis();
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId);
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
// 检查是否有认证信息
@@ -223,7 +225,7 @@ public class FjTool extends PanBase {
log.warn("登录失败: {}", failRes.getMessage());
fail(failRes.getMessage());
}).onSuccess(r-> {
httpRequest.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId))
httpRequest.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + userId))
.putHeaders(header);
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
});
@@ -245,7 +247,7 @@ public class FjTool extends PanBase {
});
} else {
httpRequest
.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId))
.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + userId))
.putHeaders(header);
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
}
@@ -444,8 +446,15 @@ public class FjTool extends PanBase {
private void down(HttpResponse<Buffer> res2) {
MultiMap headers = res2.headers();
if (!headers.contains("Location") || headers.get("Location") == null) {
fail("找不到下载链接可能服务器已被禁止或者配置的认证信息有误: " + res2.bodyAsString());
if (StringUtils.isBlank(headers.get("Location"))) {
String body;
try {
body = asText(res2);
} catch (IllegalArgumentException | UnsupportedOperationException e) {
fail(e, "读取下载错误响应失败, HTTP {}", res2.statusCode());
return;
}
fail("{}", FjDownloadParams.missingLocation(res2.statusCode(), body));
return;
}
promise.complete(headers.get("Location"));
@@ -487,7 +496,11 @@ public class FjTool extends PanBase {
.setParserUrl(id)
.setPanType(shareLinkInfo.getType());
List<FileInfo> result = new ArrayList<>();
result.add(fileInfo);
int page = FolderPaging.pageOrFirst(shareLinkInfo);
if (page == 1) {
result.add(fileInfo);
}
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
promise.complete(result);
return;
}
@@ -501,84 +514,101 @@ public class FjTool extends PanBase {
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode)
.setTemplateParam("folderId", id)
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
.send().onSuccess(res -> {
JsonArray list;
JsonObject jsonObject;
try {
JsonObject jsonObject = asJson(res);
jsonObject = asJson(res);
log.debug("目录列表: {}", jsonObject.encodePrettily());
list = jsonObject.getJsonArray("list");
} catch (Exception e) {
log.error("解析目录失败: {}", res.bodyAsString());
promise.tryFail("目录解析失败: 响应不是 JSON");
return;
}
if (list == null) {
promise.tryFail("目录解析失败: 响应缺少 list 字段: " + jsonObject);
return;
}
ArrayList<FileInfo> result = new ArrayList<>();
list.forEach(item->{
JsonObject fileJson = (JsonObject) item;
FileInfo fileInfo = new FileInfo();
try {
list.forEach(item->{
JsonObject fileJson = (JsonObject) item;
FileInfo fileInfo = new FileInfo();
// 映射已知字段fileInfo
String fileId = fileJson.getString("fileId");
String userId = fileJson.getString("userId");
// 映射已知字段fileInfo
String fileId = fileJson.getString("fileId");
String userId = fileJson.getString("userId");
// 其他参数
long nowTs2 = System.currentTimeMillis();
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId);
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
// 其他参数
long nowTs2 = System.currentTimeMillis();
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
// 回传用到的参数
//"fidEncode", paramJson.getString("fidEncode"))
//"uuid", paramJson.getString("uuid"))
//"ts", paramJson.getString("ts"))
//"auth", paramJson.getString("auth"))
//"shareId", paramJson.getString("shareId"))
JsonObject entries = JsonObject.of(
"fidEncode", fidEncode,
"uuid", uuid,
"ts", tsEncode2,
"auth", auth,
"shareId", shareId);
String param = CommonUtils.urlBase64Encode(entries.encode());
// 回传用到的参数
//"fidEncode", paramJson.getString("fidEncode"))
//"uuid", paramJson.getString("uuid"))
//"ts", paramJson.getString("ts"))
//"auth", paramJson.getString("auth"))
//"shareId", paramJson.getString("shareId"))
JsonObject entries = JsonObject.of(
"fileId", fileId,
"userId", userId,
"fidEncode", fidEncode,
"uuid", uuid,
"ts", tsEncode2,
"auth", auth,
"shareId", shareId);
String param = CommonUtils.urlBase64Encode(entries.encode());
if (fileJson.getInteger("fileType") == 2) {
// 如果是目录
fileInfo.setFileName(fileJson.getString("name"))
.setFileId(fileJson.getString("folderId"))
.setCreateTime(fileJson.getString("updTime"))
.setFileType("folder")
.setSize(0L)
.setSizeStr("0B")
if (fileJson.getInteger("fileType") == 2) {
// 如果是目录
fileInfo.setFileName(fileJson.getString("name"))
.setFileId(fileJson.getString("folderId"))
.setCreateTime(fileJson.getString("updTime"))
.setFileType("folder")
.setSize(0L)
.setSizeStr("0B")
.setCreateBy(fileJson.getLong("userId").toString())
.setDownloadCount(fileJson.getInteger("fileDownloads"))
.setCreateTime(fileJson.getString("updTime"))
.setFileIcon(fileJson.getString("fileIcon"))
.setPanType(shareLinkInfo.getType())
// 设置目录解析的URL
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&uuid=%s", getDomainName(),
shareLinkInfo.getShareUrl(), fileJson.getString("folderId"), uuid));
result.add(fileInfo);
return;
}
long fileSize = fileJson.getLong("fileSize") * 1024;
fileInfo.setFileName(fileJson.getString("fileName"))
.setFileId(fileJson.getString("fileId"))
.setCreateTime(fileJson.getString("createTime"))
.setFileType("file")
.setSize(fileSize)
.setSizeStr(FileSizeConverter.convertToReadableSize(fileSize))
.setCreateBy(fileJson.getLong("userId").toString())
.setDownloadCount(fileJson.getInteger("fileDownloads"))
.setCreateTime(fileJson.getString("updTime"))
.setFileIcon(fileJson.getString("fileIcon"))
.setPanType(shareLinkInfo.getType())
// 设置目录解析的URL
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&uuid=%s", getDomainName(),
shareLinkInfo.getShareUrl(), fileJson.getString("folderId"), uuid));
.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);
return;
}
long fileSize = fileJson.getLong("fileSize") * 1024;
fileInfo.setFileName(fileJson.getString("fileName"))
.setFileId(fileJson.getString("fileId"))
.setCreateTime(fileJson.getString("createTime"))
.setFileType("file")
.setSize(fileSize)
.setSizeStr(FileSizeConverter.convertToReadableSize(fileSize))
.setCreateBy(fileJson.getLong("userId").toString())
.setDownloadCount(fileJson.getInteger("fileDownloads"))
.setCreateTime(fileJson.getString("updTime"))
.setFileIcon(fileJson.getString("fileIcon"))
.setPanType(shareLinkInfo.getType())
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(),
shareLinkInfo.getType(), param))
.setPreviewUrl(String.format("%s/v2/viewUrl/%s/%s", getDomainName(),
shareLinkInfo.getType(), param));
result.add(fileInfo);
});
});
} catch (Exception e) {
log.error("目录列表条目解析失败: {}", jsonObject, e);
promise.tryFail("目录解析失败: 列表条目格式异常 " + e);
return;
}
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
promise.complete(result);
});
}).onFailure(err -> promise.tryFail("目录解析失败: " + err.getMessage()));
}
@Override
@@ -590,20 +620,24 @@ public class FjTool extends PanBase {
promise.fail("缺少 paramJson 参数");
return promise.future();
}
clientNoRedirects.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
.setTemplateParam("fidEncode", paramJson.getString("fidEncode"))
.setTemplateParam("uuid", paramJson.getString("uuid"))
.setTemplateParam("ts", paramJson.getString("ts"))
.setTemplateParam("auth", paramJson.getString("auth"))
.setTemplateParam("dataKey", paramJson.getString("shareId"))
.putHeaders(header).send().onSuccess(res2 -> {
MultiMap headers = res2.headers();
if (!headers.contains("Location")) {
fail(SECOND_REQUEST_URL_VIP + " 未找到重定向URL: \n" + res2.headers());
return;
}
promise.complete(headers.get("Location"));
}).onFailure(handleFail(SECOND_REQUEST_URL_VIP));
try {
String ownerId = FjDownloadParams.ownerId(paramJson);
if (StringUtils.isBlank(ownerId) || "null".equals(ownerId)) {
fail("目录下载参数缺少分享者 userId,请刷新文件列表后重试");
return promise.future();
}
JsonObject params = FjDownloadParams.create(FjDownloadParams.fileId(paramJson), ownerId,
paramJson.getString("uuid"), paramJson.getString("shareId"), System.currentTimeMillis());
clientNoRedirects.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
.setTemplateParam("fidEncode", params.getString("fidEncode"))
.setTemplateParam("uuid", params.getString("uuid"))
.setTemplateParam("ts", params.getString("ts"))
.setTemplateParam("auth", params.getString("auth"))
.setTemplateParam("dataKey", params.getString("shareId"))
.putHeaders(header).send().onSuccess(this::down).onFailure(handleFail("下载请求"));
} catch (Exception e) {
fail(e, "下载参数无效");
}
return promise.future();
}
@@ -1,5 +1,6 @@
package cn.qaiu.parser.impl;
import cn.qaiu.util.Base64Encoder;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.PanBase;
import io.netty.handler.codec.http.cookie.Cookie;
@@ -14,7 +15,6 @@ import org.slf4j.LoggerFactory;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -48,7 +48,7 @@ public class GenShortUrl extends PanBase {
public Future<String> parse() {
String longUrl = shareLinkInfo.getShareUrl();
String url = WRAPPER_URL + Base64.getEncoder().encodeToString(longUrl.getBytes());
String url = WRAPPER_URL + Base64Encoder.encode(longUrl.getBytes());
String payload = "mid=" + MID + "&content=" + URLEncoder.encode(url, StandardCharsets.UTF_8);
clientSession.cookieStore().put(cookie);
@@ -2,7 +2,9 @@ package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.FolderPaging;
import cn.qaiu.parser.PanBase;
import cn.qaiu.parser.TokenCache;
import cn.qaiu.util.AESUtils;
import cn.qaiu.util.AcwScV2Generator;
import cn.qaiu.util.CommonUtils;
@@ -55,7 +57,10 @@ public class IzTool extends PanBase {
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
"={uuid}&extra=2&timestamp={ts}&shareId={shareId}&folderId" +
"={folderId}&offset=1&limit=60";
"={folderId}&offset={offset}&limit={limit}";
/** share/list 每页条数;offset 是从 1 开始的页码。 */
static final int LIST_LIMIT = 60;
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
@@ -85,12 +90,31 @@ public class IzTool extends PanBase {
}
public IzTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
IzXffHeader.apply(header);
String accountId = "_default";
if (shareLinkInfo.getOtherParam().containsKey("auths")) {
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
if (auths.contains("_configId")) {
accountId = auths.get("_configId");
} else if (auths.contains("username")) {
accountId = auths.get("username");
}
}
this.cacheKey = TokenCache.key("iz", accountId);
}
String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
public static volatile String token = null;
public static volatile boolean authFlag = true;
// 多账号隔离:用 TokenCache 代替 static 变量
private final String cacheKey;
private String token() {
return TokenCache.getToken(cacheKey);
}
private boolean authFlag() {
return TokenCache.getFlag(cacheKey, true);
}
public Future<String> parse() {
@@ -101,22 +125,21 @@ public class IzTool extends PanBase {
// 检查并输出认证状态
if (shareLinkInfo.getOtherParam().containsKey("auths")) {
boolean isTempAuth = shareLinkInfo.getOtherParam().containsKey("__TEMP_AUTH_ADDED");
String token = token();
log.info("文件解析检测到认证信息: isTempAuth={}, authFlag={}, token={}",
isTempAuth, authFlag, token != null ? "已登录(" + token.substring(0, Math.min(8, token.length())) + "...)" : "未登录");
isTempAuth, authFlag(), token != null ? "已登录(" + token.substring(0, Math.min(8, token.length())) + "...)" : "未登录");
// 如果需要认证但还没有token,先执行登录
if ((isTempAuth || authFlag) && token == null) {
if ((isTempAuth || authFlag()) && token == null) {
log.info("文件解析需要登录,开始执行登录流程...");
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
return login(tsEncode, auths)
.compose(v -> {
log.info("文件解析预登录成功,继续解析流程");
return parseWithAuth(shareId, tsEncode);
.recover(err -> {
// 预登录失败不终止解析,继续走免登录
log.warn("文件解析预登录失败: {},使用免登录模式", err.getMessage());
return Future.succeededFuture();
})
.onFailure(err -> {
log.warn("文件解析预登录失败: {},尝试使用免登录模式", err.getMessage());
// 登录失败,继续使用免登录模式
});
.compose(v -> parseWithAuth(shareId, tsEncode));
} else if (token != null) {
log.info("文件解析使用已有token: {}...", token.substring(0, Math.min(8, token.length())));
}
@@ -231,8 +254,8 @@ public class IzTool extends PanBase {
// 检查是否为临时认证(临时认证每次都尝试登录)
boolean isTempAuth = shareLinkInfo.getOtherParam().containsKey("__TEMP_AUTH_ADDED");
// 如果是临时认证,或者是后台配置且authFlag为true,则尝试使用认证
if (isTempAuth || authFlag) {
log.debug("尝试使用认证信息解析, isTempAuth={}, authFlag={}", isTempAuth, authFlag);
if (isTempAuth || authFlag()) {
log.debug("尝试使用认证信息解析, isTempAuth={}, authFlag={}", isTempAuth, authFlag());
HttpRequest<Buffer> httpRequest =
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
.setTemplateParam("fidEncode", fidEncode)
@@ -241,18 +264,19 @@ public class IzTool extends PanBase {
.setTemplateParam("auth", auth)
.setTemplateParam("dataKey", dataKey);
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
if (token == null) {
// 执行登录
if (token() == null) {
// 执行登录,失败则回退免登录
login(tsEncode2, auths).onFailure(failRes-> {
log.warn("登录失败: {}", failRes.getMessage());
fail(failRes.getMessage());
log.warn("登录失败,回退免登录: {}", failRes.getMessage());
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
}).onSuccess(r-> {
httpRequest.setTemplateParam("appToken", token)
httpRequest.setTemplateParam("appToken", token())
.putHeaders(header);
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
});
} else {
// 验证token
// 验证token — 先从缓存恢复到 header
header.set("appToken", token());
webClientSession.postAbs(UriTemplate.of(TOKEN_VERIFY_URL))
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode2)
@@ -260,15 +284,15 @@ public class IzTool extends PanBase {
// log.info("res: {}",asJson(res));
if (asJson(res).getInteger("code") != 200) {
login(tsEncode2, auths).onFailure(failRes -> {
log.warn("重新登录失败: {}", failRes.getMessage());
fail(failRes.getMessage());
log.warn("重新登录失败,回退免登录: {}", failRes.getMessage());
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
}).onSuccess(r-> {
httpRequest.setTemplateParam("appToken", token)
httpRequest.setTemplateParam("appToken", token())
.putHeaders(header);
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
});
} else {
httpRequest.setTemplateParam("appToken", token)
httpRequest.setTemplateParam("appToken", token())
.putHeaders(header);
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
}
@@ -277,29 +301,27 @@ public class IzTool extends PanBase {
} else {
// authFlag 为 false,使用免登录解析
log.debug("authFlag=false,使用免登录解析");
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
.putHeaders(header)
.setTemplateParam("fidEncode", fidEncode)
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode2)
.setTemplateParam("auth", auth)
.setTemplateParam("dataKey", dataKey).send()
.onSuccess(this::down).onFailure(handleFail("请求2"));
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
}
} else {
// 没有认证信息,使用免登录解析
log.debug("无认证信息,使用免登录解析");
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
.putHeaders(header)
.setTemplateParam("fidEncode", fidEncode)
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode2)
.setTemplateParam("auth", auth)
.setTemplateParam("dataKey", dataKey).send()
.onSuccess(this::down).onFailure(handleFail("请求2"));
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
}
}
private void downloadAnonymous(String fidEncode, String tsEncode2, String auth, String dataKey) {
log.debug("使用免登录解析");
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
.putHeaders(header)
.setTemplateParam("fidEncode", fidEncode)
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode2)
.setTemplateParam("auth", auth)
.setTemplateParam("dataKey", dataKey).send()
.onSuccess(this::down).onFailure(handleFail("请求2"));
}
private Future<Void> login(String tsEncode2, MultiMap auths) {
Promise<Void> promise1 = Promise.promise();
webClientSession.postAbs(UriTemplate.of(LOGIN_URL))
@@ -310,8 +332,13 @@ public class IzTool extends PanBase {
.onSuccess(res2->{
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");
String loginToken = json.getJsonObject("data").getString("appToken");
TokenCache.putToken(cacheKey, loginToken);
TokenCache.queueCachedTokenPersist(cacheKey, loginToken, System.currentTimeMillis() + 24 * 60 * 60 * 1000L);
if (loginToken != null) {
header.set("appToken", loginToken);
}
log.info("登录成功 token: {}...", loginToken != null ? loginToken.substring(0, Math.min(8, loginToken.length())) : "null");
promise1.complete();
} else {
// 检查是否为临时认证
@@ -323,7 +350,7 @@ public class IzTool extends PanBase {
} else {
// 后台配置的认证失败,设置authFlag并返回失败,让下次请求使用免登陆解析
log.warn("后台配置认证失败: {}, authFlag将设为false,请重新解析", json.getString("msg"));
authFlag = false;
TokenCache.putFlag(cacheKey, false);
promise1.fail("认证失败: " + json.getString("msg") + ", 请重新解析将使用免登陆模式");
}
}
@@ -443,75 +470,75 @@ 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();
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) + "...";
}
// 目录解析
@Override
public Future<List<FileInfo>> parseFileList() {
Promise<List<FileInfo>> promise = Promise.promise();
@@ -546,7 +573,11 @@ public class IzTool extends PanBase {
.setParserUrl(id)
.setPanType(shareLinkInfo.getType());
List<FileInfo> result = new ArrayList<>();
result.add(fileInfo);
int page = FolderPaging.pageOrFirst(shareLinkInfo);
if (page == 1) {
result.add(fileInfo);
}
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
promise.complete(result);
return;
}
@@ -563,6 +594,8 @@ public class IzTool extends PanBase {
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode)
.setTemplateParam("folderId", id)
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
.send().onSuccess(res -> {
String resBody = asText(res);
// 检查是否包含 cookie 验证
@@ -577,6 +610,8 @@ public class IzTool extends PanBase {
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode)
.setTemplateParam("folderId", id)
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
.send().onSuccess(res2 -> {
processDirResponse(res2, shareId, promise);
}).onFailure(err -> {
@@ -668,6 +703,7 @@ public class IzTool extends PanBase {
shareLinkInfo.getType(), param));
result.add(fileInfo);
});
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
promise.complete(result);
} catch (Exception e) {
log.error("处理目录响应异常: {}", e.getMessage(), e);
@@ -691,7 +727,6 @@ public class IzTool extends PanBase {
}
public static void resetToken() {
token = null;
authFlag = true;
TokenCache.removeByDiskType("iz");
}
}
@@ -2,6 +2,7 @@ package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.FolderPaging;
import cn.qaiu.parser.PanBase;
import cn.qaiu.util.AESUtils;
import cn.qaiu.util.AcwScV2Generator;
@@ -54,7 +55,10 @@ public class IzToolWithAuth extends PanBase {
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
"={uuid}&extra=2&timestamp={ts}&shareId={shareId}&folderId" +
"={folderId}&offset=1&limit=60";
"={folderId}&offset={offset}&limit={limit}";
/** share/list 每页条数;offset 是从 1 开始的页码。 */
static final int LIST_LIMIT = 60;
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
@@ -84,6 +88,7 @@ public class IzToolWithAuth extends PanBase {
}
public IzToolWithAuth(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
IzXffHeader.apply(header);
}
String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
@@ -213,8 +218,8 @@ public class IzToolWithAuth extends PanBase {
if (token == null) {
// 执行登录
login(tsEncode2, auths).onFailure(failRes-> {
log.warn("登录失败: {}", failRes.getMessage());
fail(failRes.getMessage());
log.warn("登录失败,回退免登录: {}", failRes.getMessage());
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
}).onSuccess(r-> {
httpRequest.setTemplateParam("appToken", token)
.putHeaders(header);
@@ -229,8 +234,8 @@ public class IzToolWithAuth extends PanBase {
// log.info("res: {}",asJson(res));
if (asJson(res).getInteger("code") != 200) {
login(tsEncode2, auths).onFailure(failRes -> {
log.warn("重新登录失败: {}", failRes.getMessage());
fail(failRes.getMessage());
log.warn("重新登录失败,回退免登录: {}", failRes.getMessage());
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
}).onSuccess(r-> {
httpRequest.setTemplateParam("appToken", token)
.putHeaders(header);
@@ -246,29 +251,27 @@ public class IzToolWithAuth extends PanBase {
} else {
// authFlag 为 false,使用免登录解析
log.debug("authFlag=false,使用免登录解析");
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
.putHeaders(header)
.setTemplateParam("fidEncode", fidEncode)
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode2)
.setTemplateParam("auth", auth)
.setTemplateParam("dataKey", dataKey).send()
.onSuccess(this::down).onFailure(handleFail("请求2"));
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
}
} else {
// 没有认证信息,使用免登录解析
log.debug("无认证信息,使用免登录解析");
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
.putHeaders(header)
.setTemplateParam("fidEncode", fidEncode)
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode2)
.setTemplateParam("auth", auth)
.setTemplateParam("dataKey", dataKey).send()
.onSuccess(this::down).onFailure(handleFail("请求2"));
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
}
}
private void downloadAnonymous(String fidEncode, String tsEncode2, String auth, String dataKey) {
log.debug("使用免登录解析");
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
.putHeaders(header)
.setTemplateParam("fidEncode", fidEncode)
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode2)
.setTemplateParam("auth", auth)
.setTemplateParam("dataKey", dataKey).send()
.onSuccess(this::down).onFailure(handleFail("请求2"));
}
private Future<Void> login(String tsEncode2, MultiMap auths) {
Promise<Void> promise1 = Promise.promise();
webClientSession.postAbs(UriTemplate.of(LOGIN_URL))
@@ -513,7 +516,11 @@ public class IzToolWithAuth extends PanBase {
.setParserUrl(id)
.setPanType(shareLinkInfo.getType());
List<FileInfo> result = new ArrayList<>();
result.add(fileInfo);
int page = FolderPaging.pageOrFirst(shareLinkInfo);
if (page == 1) {
result.add(fileInfo);
}
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
promise.complete(result);
return;
}
@@ -566,6 +573,8 @@ public class IzToolWithAuth extends PanBase {
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode)
.setTemplateParam("folderId", id)
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
.send().onSuccess(res -> {
String resBody = asText(res);
// 检查是否包含 cookie 验证
@@ -580,6 +589,8 @@ public class IzToolWithAuth extends PanBase {
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode)
.setTemplateParam("folderId", id)
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
.send().onSuccess(res2 -> {
processDirResponse(res2, shareId, promise);
}).onFailure(err -> {
@@ -672,6 +683,7 @@ public class IzToolWithAuth extends PanBase {
shareLinkInfo.getType(), param));
result.add(fileInfo);
});
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
promise.complete(result);
} catch (Exception e) {
log.error("处理目录响应异常: {}", e.getMessage(), e);
@@ -0,0 +1,60 @@
package cn.qaiu.parser.impl;
import io.vertx.core.MultiMap;
import org.apache.commons.lang3.StringUtils;
import java.util.concurrent.ThreadLocalRandom;
/**
* 蓝奏云优享 X-Forwarded-For 配置。
* <p>
* 读取系统属性 {@code nfd.iz.xff},其次环境变量 {@code NFD_IZ_XFF}:
* <ul>
* <li>未设置 / 空 / {@code off}:不发送该头(默认)</li>
* <li>{@code random}:每次创建解析器时随机一个国内常见网段 IP</li>
* <li>其它值:原样作为头的值,例如 {@code 113.96.181.18}</li>
* </ul>
*/
public final class IzXffHeader {
public static final String PROP = "nfd.iz.xff";
public static final String ENV = "NFD_IZ_XFF";
private static final String HEADER = "X-Forwarded-For";
/** 国内运营商常见 /8 段首字节 */
private static final int[] CN_PREFIX = {36, 39, 42, 58, 59, 60, 61, 101, 106, 110, 111, 112, 113, 114,
115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 175, 180, 182, 183, 202, 210, 211, 218, 219, 220, 221, 222, 223};
private IzXffHeader() {
}
static String configured() {
String v = System.getProperty(PROP);
if (StringUtils.isBlank(v)) {
v = System.getenv(ENV);
}
return v == null ? "" : v.trim();
}
/** 根据配置得到头的值,返回 null 表示不发送 */
static String resolve(String mode) {
if (StringUtils.isBlank(mode) || "off".equalsIgnoreCase(mode)) {
return null;
}
if ("random".equalsIgnoreCase(mode)) {
ThreadLocalRandom r = ThreadLocalRandom.current();
return CN_PREFIX[r.nextInt(CN_PREFIX.length)] + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + (1 + r.nextInt(254));
}
return mode;
}
/** 按当前配置写入或移除请求头 */
public static void apply(MultiMap headers) {
String value = resolve(configured());
if (value == null) {
headers.remove(HEADER);
} else {
headers.set(HEADER, value);
}
}
}
@@ -1,5 +1,6 @@
package cn.qaiu.parser.impl;
import cn.qaiu.util.Base64Encoder;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.PanBase;
@@ -13,7 +14,6 @@ import io.vertx.core.json.JsonObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Random;
import java.util.UUID;
@@ -232,7 +232,7 @@ public class LeTool extends PanBase {
"shareId", shareId,
"fileId", fileId
);
String paramBase64 = Base64.getEncoder().encodeToString(paramJson.encode().getBytes());
String paramBase64 = Base64Encoder.encode(paramJson.encode().getBytes());
// 设置解析URL和预览URL
fileInfo.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
@@ -0,0 +1,116 @@
package cn.qaiu.parser.impl;
import cn.qaiu.util.CommonUtils;
import io.vertx.core.json.JsonObject;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;
/**
* 蓝奏目录「下一页」游标。
* <p>
* filemoreajax 的 t/k 由分享页下发,上游按这组令牌记录已翻到第几页:同一组令牌可以取
* 「已取过的最大页 + 1」以内的任意页;换一组新令牌直接跳到第 N 页会返回 zt=4「请刷新,重试」。
* 所以加载更多时把上一页用过的表单(不含密码和页码)交还给客户端,下次直接续翻。
* <p>
* 游标来自客户端,不可信:只用于表单字段,POST 主机仍由服务端按分享链接决定;
* 分享 key、页码、路径对不上一律当作没有游标,回退到从第 1 页顺序翻。
*/
final class LzFolderCursor {
private static final int VERSION = 1;
private static final Pattern PATH = Pattern.compile("/filemoreajax\\.php\\?file=(\\d+)");
private static final Pattern KEY = Pattern.compile("\\w{1,32}");
private static final int MAX_VALUE_LENGTH = 256;
private static final int MAX_FIELDS = 32;
final String path;
final Map<String, String> form;
final String webpage;
private LzFolderCursor(String path, Map<String, String> form, String webpage) {
this.path = path;
this.form = form;
this.webpage = webpage;
}
static String encode(String shareKey, String path, Map<String, String> form, int nextPage, String webpage) {
JsonObject f = new JsonObject();
form.forEach((k, v) -> {
if (!"pwd".equals(k) && !"pg".equals(k)) {
f.put(k, v);
}
});
JsonObject json = new JsonObject()
.put("v", VERSION)
.put("s", shareKey)
.put("p", path)
.put("n", nextPage)
.put("f", f);
if (webpage != null && !webpage.isBlank()) {
json.put("w", webpage);
}
return CommonUtils.urlBase64Encode(json.encode());
}
/**
* @return 校验通过的游标;任何不匹配或格式问题都返回 null
*/
static LzFolderCursor decode(String raw, String shareKey, int page) {
if (raw == null || raw.isBlank() || raw.length() > 4096) {
return null;
}
try {
JsonObject json = new JsonObject(CommonUtils.urlBase64Decode(raw));
if (json.getInteger("v", 0) != VERSION) {
return null;
}
if (shareKey == null || !shareKey.equals(json.getString("s"))) {
return null;
}
if (json.getInteger("n", -1) != page) {
return null;
}
String path = json.getString("p");
var m = path == null ? null : PATH.matcher(path);
if (m == null || !m.matches()) {
return null;
}
JsonObject f = json.getJsonObject("f");
if (f == null || f.size() > MAX_FIELDS) {
return null;
}
Map<String, String> form = new LinkedHashMap<>();
for (String key : f.fieldNames()) {
Object v = f.getValue(key);
if (!KEY.matcher(key).matches() || v == null) {
return null;
}
String s = String.valueOf(v);
if (s.length() > MAX_VALUE_LENGTH || s.chars().anyMatch(c -> c < 0x20)) {
return null;
}
form.put(key, s);
}
if (!m.group(1).equals(form.get("fid")) || !form.containsKey("t") || !form.containsKey("k")) {
return null;
}
String webpage = json.getString("w");
if (webpage != null && (webpage.length() > MAX_VALUE_LENGTH || !webpage.matches("[\\w\\-=.%]+"))) {
webpage = null;
}
return new LzFolderCursor(path, form, webpage);
} catch (Exception e) {
return null;
}
}
/** 本次请求用的表单:游标字段 + 当前密码 + 目标页。 */
Map<String, String> formFor(String pwd, int page) {
Map<String, String> out = new LinkedHashMap<>(form);
out.put("pg", String.valueOf(page));
out.put("pwd", pwd == null ? "" : pwd);
return out;
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,699 @@
package cn.qaiu.parser.impl;
import io.vertx.core.Future;
import io.vertx.core.MultiMap;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* 夸克 / UC 单文件下载策略。
* <p>
* 体积不大于 {@link #NORMAL_PARSE_MAX_BYTES}(10MiB,即 {@code 10 * 1024 * 1024},等于阈值仍走原解析)时,
* 调用方保持现有分享下载。更大且能读到体积的文件:先用会员接口确认未过期的 SVIP/VIP,
* 再用该账号已有的 {@code /file/download} 直链;否则只接受 H5 预览返回、并经匿名探测确认为文件字节的
* {@code https://dl-c-* .drive.quark.cn|drive.uc.cn} 地址,附上真实文件名。
* 预览网页、HTML、JSON、m3u8 播放列表和登录态 CDN 都不当作下载成功。
* UC 不因为尝试 H5 就变成免登录。
* </p>
*/
public final class QuarkFamilyDownloadPolicy {
/** 10MiB。仓库没有另一套 10MB 常量,按二进制兆字节 {@code 10 * 1024 * 1024}。 */
public static final long NORMAL_PARSE_MAX_BYTES = 10L * 1024 * 1024;
private static final Set<String> PAID_TYPES = Set.of(
"SUPER_VIP", "EXP_SVIP", "Z_VIP", "VIP", "EXP_VIP");
private static final List<String> BARE_QUERY = List.of("auth_key", "sp", "token");
private static final String GUEST_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
private static final int PROBE_PREFIX_BYTES = 64;
private QuarkFamilyDownloadPolicy() {
}
/** 已知体积且严格大于 10MiB。缺少体积或无法解析时返回 false,调用方继续原解析。 */
public static boolean knownLarge(long size) {
return size > NORMAL_PARSE_MAX_BYTES && size < Long.MAX_VALUE;
}
public static long sizeOf(JsonObject item) {
if (item == null || !item.containsKey("size")) {
return Long.MAX_VALUE;
}
return sizeOf(item.getValue("size"));
}
public static long sizeOf(Object value) {
if (value instanceof Number number) {
return number.longValue();
}
if (value instanceof String text && !text.isBlank()) {
try {
return Long.parseLong(text.trim());
} catch (NumberFormatException ignored) {
return Long.MAX_VALUE;
}
}
return Long.MAX_VALUE;
}
public static final class Membership {
public final boolean validPaid;
public final String memberType;
public final Long expAtMs;
public final String reason;
Membership(boolean validPaid, String memberType, Long expAtMs, String reason) {
this.validPaid = validPaid;
this.memberType = memberType;
this.expAtMs = expAtMs;
this.reason = reason;
}
static Membership notPaid(String type, Long expAtMs, String reason) {
return new Membership(false, type, expAtMs, reason);
}
}
/**
* 只认会员接口的 {@code member_type} 和 {@code exp_at}。Cookie 是否存在不参与判断。
* 体验会员(EXP_SVIP / EXP_VIP)和 Z_VIP 在到期前算有效;NORMAL、未知档位、缺少到期时间或已到期都无效。
*/
public static Membership judgeMembership(JsonObject data, long nowMs) {
if (data == null) {
return Membership.notPaid(null, null, "会员接口没有 data");
}
String raw = data.getString("member_type");
if (raw == null || raw.isBlank()) {
return Membership.notPaid(null, null, "会员接口没有 member_type");
}
String type = raw.trim().toUpperCase(Locale.ROOT);
Long expAt = epochMillis(data.getValue("exp_at"));
if (!PAID_TYPES.contains(type)) {
return Membership.notPaid(type, expAt, "当前档位不是未过期的 SVIP/VIP");
}
if (expAt == null) {
return Membership.notPaid(type, null, "会员接口没有 exp_at,不能确认未过期");
}
if (expAt <= nowMs) {
return Membership.notPaid(type, expAt, "会员已过期");
}
return new Membership(true, type, expAt, null);
}
static Long epochMillis(Object value) {
Long raw = null;
if (value instanceof Number number) {
raw = number.longValue();
} else if (value instanceof String text && !text.isBlank()) {
try {
raw = Long.parseLong(text.trim());
} catch (NumberFormatException ignored) {
return null;
}
}
if (raw == null || raw <= 0) {
return null;
}
return raw < 100_000_000_000L ? raw * 1000L : raw;
}
public static Future<Membership> fetchMembership(WebClient client, MultiMap apiHeaders, boolean uc) {
String url = uc
? "https://pc-api.uc.cn/1/clouddrive/member?pr=UCBrowser&fr=pc&fetch_subscribe=true&_ch=home&fetch_identity=true"
: "https://drive-pc.quark.cn/1/clouddrive/member?pr=ucpro&fr=pc&fetch_subscribe=true&_ch=home&fetch_identity=true";
return fetchMembership(client, apiHeaders, url, uc);
}
static Future<Membership> fetchMembership(WebClient client, MultiMap apiHeaders, String memberUrl, boolean uc) {
String cookie = apiHeaders == null ? null : apiHeaders.get(HttpHeaders.COOKIE);
if (cookie == null || cookie.isBlank()) {
return Future.succeededFuture(Membership.notPaid(null, null, "未配置 Cookie"));
}
String referer = uc ? "https://drive.uc.cn/" : "https://pan.quark.cn/";
String ua = apiHeaders.get(HttpHeaders.USER_AGENT);
if (ua == null || ua.isBlank()) {
ua = GUEST_UA;
}
return client.getAbs(memberUrl)
.putHeader(HttpHeaders.COOKIE.toString(), cookie)
.putHeader(HttpHeaders.USER_AGENT.toString(), ua)
.putHeader(HttpHeaders.REFERER.toString(), referer)
.timeout(10_000)
.send()
.map(res -> membershipFromResponse(res))
.recover(err -> Future.succeededFuture(
Membership.notPaid(null, null, "会员接口不可用")));
}
static Membership membershipFromResponse(HttpResponse<?> res) {
int status = res.statusCode();
if (status == 401 || status == 403) {
return Membership.notPaid(null, null, "会员接口拒绝访问 HTTP " + status);
}
String type = res.getHeader(HttpHeaders.CONTENT_TYPE.toString());
if (type != null && type.toLowerCase(Locale.ROOT).contains("text/html")) {
return Membership.notPaid(null, null, "会员接口返回了 HTML");
}
JsonObject json;
try {
json = res.bodyAsJsonObject();
} catch (Exception e) {
return Membership.notPaid(null, null, "会员接口没有返回 JSON");
}
if (json == null) {
return Membership.notPaid(null, null, "会员接口没有返回 JSON");
}
Integer code = json.getInteger("code");
if (code != null && code != 0) {
return Membership.notPaid(null, null, "会员接口失败 code=" + code);
}
return judgeMembership(json.getJsonObject("data"), System.currentTimeMillis());
}
/**
* H5 预览签发的公开文件地址。不带登录 Cookie。探测只读响应头和最多 64 字节,不把文件收进内存。
*/
public static Future<String> resolveH5Download(WebClient client, Vertx vertx, String pan,
String pwdId, String stoken, String fid,
String fidToken, String fileName) {
if (isBlank(fid) || isBlank(fidToken) || isBlank(pwdId) || isBlank(stoken)) {
return Future.failedFuture("分享参数不完整,无法请求 H5 预览");
}
if (isBlank(fileName)) {
return Future.failedFuture("没有真实文件名,不能把预览地址当作下载");
}
return requestRichText(client, pan, pwdId, stoken, fid, fidToken)
.compose(raw -> acceptProbed(vertx, pan, raw, fileName))
.recover(richErr -> requestVideo(client, pan, pwdId, stoken, fid, fidToken)
.compose(raw -> acceptProbed(vertx, pan, raw, fileName))
.recover(videoErr -> Future.failedFuture(joinReasons(richErr, videoErr))));
}
private static Future<String> acceptProbed(Vertx vertx, String pan, String raw, String fileName) {
if (raw != null && raw.toLowerCase(Locale.ROOT).contains(".m3u8")) {
return Future.failedFuture("只得到 m3u8 播放列表,不是文件");
}
if (!isPublicFileUrl(raw, pan)) {
return Future.failedFuture("预览地址不是公开文件 CDN");
}
return probeBody(vertx, raw, pan, 1).compose(hit -> {
if (!hit.ok) {
return Future.failedFuture(hit.reason);
}
return Future.succeededFuture(withFilename(bareFileUrl(raw), fileName));
});
}
private static Future<String> requestRichText(WebClient client, String pan, String pwdId, String stoken,
String fid, String fidToken) {
boolean uc = isUc(pan);
String base = uc ? "https://pc-api.uc.cn/1/clouddrive" : "https://drive.quark.cn/1/clouddrive";
String site = uc ? "https://drive.uc.cn" : "https://vt.quark.cn";
return requestPreview(client, pan, base, "h5", site, "/share/sharepage/rich_text/preview",
pwdId, stoken, fid, fidToken, false);
}
private static Future<String> requestVideo(WebClient client, String pan, String pwdId, String stoken,
String fid, String fidToken) {
List<String[]> attempts = isUc(pan)
? List.of(
new String[]{"https://pc-api.uc.cn/1/clouddrive", "h5", "https://drive.uc.cn"},
new String[]{"https://pc-api.uc.cn/1/clouddrive", "pc", "https://drive.uc.cn"})
: List.of(
new String[]{"https://drive.quark.cn/1/clouddrive", "h5", "https://vt.quark.cn"},
new String[]{"https://drive.quark.cn/1/clouddrive", "pc", "https://pan.quark.cn"},
new String[]{"https://drive-h.quark.cn/1/clouddrive", "h5", "https://pan.quark.cn"});
return requestVideoAt(client, pan, attempts, 0, pwdId, stoken, fid, fidToken, null);
}
private static Future<String> requestVideoAt(WebClient client, String pan, List<String[]> attempts, int index,
String pwdId, String stoken, String fid, String fidToken,
Throwable last) {
if (index >= attempts.size()) {
return Future.failedFuture(last == null ? new IllegalStateException("视频预览没有公开文件地址") : last);
}
String[] attempt = attempts.get(index);
return requestPreview(client, pan, attempt[0], attempt[1], attempt[2],
"/share/sharepage/video/preview", pwdId, stoken, fid, fidToken, true)
.recover(err -> requestVideoAt(client, pan, attempts, index + 1, pwdId, stoken, fid, fidToken, err));
}
private static Future<String> requestPreview(WebClient client, String pan, String base, String fr, String site,
String path, String pwdId, String stoken, String fid,
String fidToken, boolean video) {
String pr = isUc(pan) ? "UCBrowser" : "ucpro";
var req = client.getAbs(base + path)
.putHeader(HttpHeaders.USER_AGENT.toString(), GUEST_UA)
.putHeader(HttpHeaders.ACCEPT.toString(), "application/json, text/plain, */*")
.putHeader(HttpHeaders.REFERER.toString(), site + "/")
.putHeader("Origin", site)
.putHeader("x-clouddrive-st", "null")
.addQueryParam("fid", fid)
.addQueryParam("fid_token", fidToken)
.addQueryParam("fr", fr)
.addQueryParam("pr", pr)
.addQueryParam("pwd_id", pwdId)
.addQueryParam("stoken", stoken);
if (video) {
req.addQueryParam("resolution", "low,normal,high,super,2k,4k");
req.addQueryParam("supports", "fmp4,m3u8,dolby_vision");
}
return req.timeout(10_000).send().compose(res -> interpretPreview(res, pan, video));
}
static Future<String> interpretPreview(HttpResponse<?> res, String pan, boolean video) {
int status = res.statusCode();
String contentType = res.getHeader(HttpHeaders.CONTENT_TYPE.toString());
if (contentType != null && contentType.toLowerCase(Locale.ROOT).contains("text/html")) {
return Future.failedFuture("H5 预览返回了 HTML 页面,不是文件");
}
if (status >= 400) {
return Future.failedFuture("H5 预览 HTTP " + status);
}
JsonObject json;
try {
json = res.bodyAsJsonObject();
} catch (Exception e) {
return Future.failedFuture("H5 预览不是 JSON");
}
if (json == null) {
return Future.failedFuture("H5 预览不是 JSON");
}
int code = json.getInteger("code", -1);
if (code != 0) {
return Future.failedFuture("H5 预览失败: " + sanitize(json.getString("message", "code=" + code)));
}
JsonObject data = json.getJsonObject("data", new JsonObject());
if (video) {
String picked = pickProgressiveFileUrl(data, pan);
if (isBlank(picked)) {
return Future.failedFuture("视频预览没有公开文件地址");
}
return Future.succeededFuture(picked);
}
String download = data.getString("download_url", "");
if (isBlank(download)) {
return Future.failedFuture("H5 预览没有 download_url");
}
return Future.succeededFuture(download);
}
/** 从视频预览里选公开 CDN 上的渐进文件。m3u8 和登录态节点丢掉。 */
static String pickProgressiveFileUrl(JsonObject data, String pan) {
if (data == null) {
return "";
}
String best = "";
int bestWidth = -1;
JsonArray list = data.getJsonArray("video_list");
if (list != null) {
for (int i = 0; i < list.size(); i++) {
Object raw = list.getValue(i);
if (!(raw instanceof JsonObject item)) {
continue;
}
JsonObject info = item.getJsonObject("video_info");
String candidate = publicFileCandidate(info == null ? "" : info.getString("url", ""), pan);
if (isBlank(candidate)) {
candidate = publicFileCandidate(item.getString("url", ""), pan);
}
if (isBlank(candidate) || candidate.toLowerCase(Locale.ROOT).contains(".m3u8")) {
continue;
}
int width = widthOf(info != null ? info : item);
if (width >= bestWidth) {
best = candidate;
bestWidth = width;
}
}
}
if (isBlank(best)) {
String direct = publicFileCandidate(data.getString("download_url", ""), pan);
if (!isBlank(direct) && !direct.toLowerCase(Locale.ROOT).contains(".m3u8")) {
best = direct;
}
}
return best;
}
private static String publicFileCandidate(String url, String pan) {
if (isBlank(url) || !isPublicFileUrl(bareFileUrl(url), pan)) {
return "";
}
return withoutFilename(url);
}
private static int widthOf(JsonObject obj) {
if (obj == null || !obj.containsKey("width")) {
return 0;
}
Object value = obj.getValue("width");
if (value instanceof Number number) {
return number.intValue();
}
return 0;
}
/**
* 公开文件 CDN。登录态节点(dl-pc、dl-guest、*.u-drive)和预览网页都不是。
*/
public static boolean isPublicFileUrl(String url, String pan) {
if (isBlank(url) || !url.startsWith("https://")) {
return false;
}
String host = hostOf(url);
if (host == null) {
return false;
}
String suffix = isUc(pan) ? ".drive.uc.cn" : ".drive.quark.cn";
return host.startsWith("dl-c-")
&& host.endsWith(suffix)
&& !host.contains(".u-drive.")
&& host.length() > "dl-c-".length() + suffix.length();
}
private static String hostOf(String url) {
int start = "https://".length();
int end = url.length();
for (int i = start; i < url.length(); i++) {
char c = url.charAt(i);
if (c == '/' || c == '?' || c == '#') {
end = i;
break;
}
}
if (end <= start) {
return null;
}
String host = url.substring(start, end);
int colon = host.indexOf(':');
if (colon >= 0) {
host = host.substring(0, colon);
}
return host.toLowerCase(Locale.ROOT);
}
public static String bareFileUrl(String url) {
if (isBlank(url) || !url.startsWith("http")) {
return url;
}
int q = url.indexOf('?');
if (q < 0) {
return url;
}
String base = url.substring(0, q);
StringBuilder kept = new StringBuilder();
for (String pair : url.substring(q + 1).split("&")) {
int eq = pair.indexOf('=');
String key = eq >= 0 ? pair.substring(0, eq) : pair;
if (BARE_QUERY.contains(key)) {
kept.append(kept.length() == 0 ? '?' : '&').append(pair);
}
}
return base + kept;
}
public static String withoutFilename(String url) {
if (isBlank(url) || url.indexOf('?') < 0 || !url.contains("filename=")) {
return url;
}
int q = url.indexOf('?');
String base = url.substring(0, q);
StringBuilder kept = new StringBuilder();
for (String pair : url.substring(q + 1).split("&")) {
int eq = pair.indexOf('=');
String key = eq >= 0 ? pair.substring(0, eq) : pair;
if ("filename".equals(key)) {
continue;
}
kept.append(kept.length() == 0 ? '?' : '&').append(pair);
}
return base + kept;
}
/** 登录态接口如果实际给了公开 CDN,去掉埋点并补上文件名,调用方不要再附带 Cookie / Referer。 */
public static String presentPublicDownload(String url, String pan, String fileName) {
if (!isPublicFileUrl(bareFileUrl(url), pan)) {
return url;
}
String bare = bareFileUrl(url);
if (isBlank(fileName) || bare.contains("filename=")) {
return bare;
}
return withFilename(bare, fileName);
}
/** CDN 用 {@code filename} 生成 Content-Disposition。跨域时浏览器会忽略 a[download]。 */
public static String withFilename(String url, String fileName) {
if (isBlank(url) || isBlank(fileName)) {
return url;
}
String encoded = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replace("+", "%20");
return url + (url.contains("?") ? "&" : "?") + "filename=" + encoded;
}
static final class ProbeHit {
final boolean ok;
final String reason;
final int prefixLength;
ProbeHit(boolean ok, String reason, int prefixLength) {
this.ok = ok;
this.reason = reason;
this.prefixLength = prefixLength;
}
static ProbeHit ok(int prefixLength) {
return new ProbeHit(true, null, prefixLength);
}
static ProbeHit fail(String reason) {
return new ProbeHit(false, reason, 0);
}
}
/**
* 匿名探测。只连接已经通过 {@link #isPublicFileUrl} 的地址;测试可直接调用以检查截断和 HTML 判断。
* 读满 {@value #PROBE_PREFIX_BYTES} 字节后立刻断开,不缓冲整份文件。
*/
static Future<ProbeHit> probeBody(Vertx vertx, String url, String pan, int redirectsLeft) {
if (isBlank(url) || !(url.startsWith("https://") || url.startsWith("http://127.0.0.1")
|| url.startsWith("http://localhost"))) {
return Future.succeededFuture(ProbeHit.fail("拒绝探测非公开文件地址"));
}
if (url.startsWith("https://") && !isPublicFileUrl(url, pan)) {
return Future.succeededFuture(ProbeHit.fail("拒绝探测非公开文件地址"));
}
HttpClient client = vertx.createHttpClient(new HttpClientOptions()
.setConnectTimeout(8_000)
.setIdleTimeout(10)
.setKeepAlive(false)
.setMaxHeaderSize(16 * 1024)
.setTrustAll(false)
.setVerifyHost(true));
RequestOptions options = new RequestOptions()
.setMethod(HttpMethod.GET)
.setAbsoluteURI(url)
.setTimeout(8_000);
Promise<ProbeHit> promise = Promise.promise();
client.request(options).compose(request -> {
request.setFollowRedirects(false);
request.putHeader(HttpHeaders.USER_AGENT.toString(), GUEST_UA);
request.putHeader(HttpHeaders.ACCEPT.toString(), "*/*");
request.putHeader("Range", "bytes=0-15");
return request.send();
}).compose(resp -> readPrefix(resp).compose(prefix -> {
int status = resp.statusCode();
if (status >= 300 && status < 400 && redirectsLeft > 0) {
String location = resp.getHeader(HttpHeaders.LOCATION.toString());
if (location != null && isPublicFileUrl(location, pan)) {
return probeBody(vertx, location, pan, redirectsLeft - 1);
}
return Future.succeededFuture(ProbeHit.fail("跳转目标不是公开文件 CDN"));
}
return Future.succeededFuture(judgeProbe(status,
resp.getHeader(HttpHeaders.CONTENT_TYPE.toString()),
resp.getHeader("Content-Range"),
resp.getHeader(HttpHeaders.CONTENT_LENGTH.toString()),
prefix));
})).onComplete(ar -> {
client.close();
if (ar.succeeded()) {
promise.tryComplete(ar.result());
} else {
promise.tryComplete(ProbeHit.fail("探测失败"));
}
});
return promise.future();
}
private static Future<Buffer> readPrefix(HttpClientResponse resp) {
Promise<Buffer> promise = Promise.promise();
Buffer prefix = Buffer.buffer();
boolean[] finished = {false};
Runnable finish = () -> {
if (finished[0]) {
return;
}
finished[0] = true;
try {
resp.request().reset();
} catch (Exception ignored) {
// 对端已结束时 reset 会失败,前缀已经够用。
}
promise.tryComplete(prefix);
};
resp.handler(buf -> {
if (prefix.length() < PROBE_PREFIX_BYTES) {
int n = Math.min(buf.length(), PROBE_PREFIX_BYTES - prefix.length());
prefix.appendBuffer(buf, 0, n);
}
if (prefix.length() >= PROBE_PREFIX_BYTES) {
finish.run();
}
});
resp.endHandler(v -> finish.run());
resp.exceptionHandler(err -> {
if (!finished[0]) {
promise.tryFail(err);
}
});
resp.fetch(PROBE_PREFIX_BYTES);
return promise.future();
}
static ProbeHit judgeProbe(int status, String contentType, String contentRange, String contentLength, Buffer prefix) {
if (status != 200 && status != 206) {
return ProbeHit.fail("HTTP " + status);
}
if (looksLikeHtml(contentType, prefix)) {
return ProbeHit.fail("响应是 HTML,不是文件");
}
if (contentType != null && contentType.toLowerCase(Locale.ROOT).contains("json")) {
return ProbeHit.fail("响应是 JSON,不是文件");
}
boolean ranged = status == 206 && contentRange != null && !contentRange.isBlank();
long length = -1;
if (contentLength != null && !contentLength.isBlank()) {
try {
length = Long.parseLong(contentLength.trim());
} catch (NumberFormatException ignored) {
length = -1;
}
}
if (!ranged && length == 0) {
return ProbeHit.fail("响应没有文件内容");
}
if (!ranged && (contentType == null || contentType.isBlank())) {
return ProbeHit.fail("响应没有 Content-Type,不能确认是文件");
}
return ProbeHit.ok(prefix == null ? 0 : prefix.length());
}
static boolean looksLikeHtml(String contentType, Buffer prefix) {
if (contentType != null) {
String type = contentType.toLowerCase(Locale.ROOT);
if (type.contains("text/html") || type.contains("application/xhtml")) {
return true;
}
}
if (prefix == null || prefix.length() == 0) {
return false;
}
int n = Math.min(prefix.length(), 32);
String head = prefix.getString(0, n, "UTF-8").stripLeading().toLowerCase(Locale.ROOT);
return head.startsWith("<!doctype") || head.startsWith("<html") || head.startsWith("<head");
}
/**
* 公开文件地址不沿用目录参数里的账号请求头。返回值表示浏览器是否必须改走下载器。
*/
public static boolean prepareDownloader(Map<String, String> headers, boolean paramNeedsDownloader, boolean publicDirect) {
if (publicDirect) {
if (headers != null) {
headers.clear();
}
return false;
}
return paramNeedsDownloader || (headers != null && !headers.isEmpty());
}
public static String largeFileError(String pan, Throwable directError, Throwable h5Error) {
boolean uc = isUc(pan);
StringBuilder message = new StringBuilder();
if (uc) {
message.append("UC 超过 10MiB(").append(NORMAL_PARSE_MAX_BYTES)
.append(" 字节)的文件不能免登录下载。当前没有未过期的 SVIP/VIP,");
} else {
message.append("夸克超过 10MiB(").append(NORMAL_PARSE_MAX_BYTES)
.append(" 字节)的文件没有可用的未过期 SVIP/VIP 直链。");
}
message.append("H5 预览也没有返回可下载的文件地址。");
if (h5Error != null) {
message.append(" 预览: ").append(sanitize(h5Error.getMessage()));
}
if (directError != null) {
message.append(" 账号直链: ").append(sanitize(directError.getMessage()));
}
if (uc) {
message.append(" 请配置未过期的 UC SVIP/VIP Cookie:auths.uc.cookie。");
} else {
message.append(" 请配置未过期的夸克 SVIP/VIP Cookie:auths.qk.cookie。普通或已过期账号不会当作会员。");
}
return message.toString();
}
static String sanitize(String message) {
if (message == null || message.isBlank()) {
return "无详情";
}
String text = message.replaceAll("(?i)(cookie|__pus|__puus|__kp|__kps|__uid)=[^\\s;&,]+", "$1=***");
String lower = text.toLowerCase(Locale.ROOT);
if (lower.contains("<html") || lower.contains("<!doctype") || lower.contains("<head")) {
return "上游返回了 HTML 页面";
}
if (text.length() > 180) {
return text.substring(0, 180);
}
return text;
}
private static String joinReasons(Throwable first, Throwable second) {
String a = first == null ? "" : sanitize(first.getMessage());
String b = second == null ? "" : sanitize(second.getMessage());
if (a.isBlank()) {
return b;
}
if (b.isBlank() || b.equals(a)) {
return a;
}
return a + ";" + b;
}
private static boolean isUc(String pan) {
return pan != null && pan.equalsIgnoreCase("uc");
}
private static boolean isBlank(String value) {
return value == null || value.isBlank();
}
}
@@ -1,13 +1,16 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.PanBase;
import cn.qaiu.parser.TokenCache;
import cn.qaiu.util.CommonUtils;
import cn.qaiu.util.CookieUtils;
import cn.qaiu.util.DateTimeUtils;
import cn.qaiu.util.FileSizeConverter;
import cn.qaiu.util.HeaderUtils;
import cn.qaiu.util.QuarkAccountScope;
import io.vertx.core.Future;
import io.vertx.core.MultiMap;
import io.vertx.core.Promise;
@@ -28,10 +31,7 @@ import java.util.Map;
*/
public class UcTool extends PanBase {
private static final String API_URL_PREFIX = "https://pc-api.uc.cn/1/clouddrive/";
// 静态变量:缓存 __puus cookie 和过期时间
private static volatile String cachedPuus = null;
private static volatile long puusExpireTime = 0;
// __puus 有效期,默认 55 分钟(服务器实际 1 小时过期,提前 5 分钟刷新)
private static final long PUUS_TTL_MS = 55 * 60 * 1000L;
@@ -67,9 +67,17 @@ public class UcTool extends PanBase {
// 保存 auths 引用,用于更新 cookie
private MultiMap auths;
private final String cacheKey;
/** 本次解析得到的是不带账号的公开文件地址。UC 大文件没有这条地址时不能当成免登录成功。 */
private boolean publicDirectLink;
public UcTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
String accountId = QuarkAccountScope.suffix(shareLinkInfo.getOtherParam());
if (accountId == null) {
accountId = "_default";
}
this.cacheKey = TokenCache.key("uc", accountId);
// 参考其它网盘实现,从认证配置中取 cookie 放到请求头
if (shareLinkInfo.getOtherParam() != null && shareLinkInfo.getOtherParam().containsKey("auths")) {
auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
@@ -77,18 +85,20 @@ public class UcTool extends PanBase {
if (cookie != null && !cookie.isEmpty()) {
// 过滤出 UC 网盘所需的 cookie 字段
cookie = CookieUtils.filterUcQuarkCookie(cookie);
// 如果有缓存的 __puus 且未过期,使用缓存的值更新 cookie
if (cachedPuus != null && System.currentTimeMillis() < puusExpireTime) {
// 按账号读取 __puus,避免把别的账号的会话写进当前请求
String cachedPuus = TokenCache.getToken(cacheKey);
long puusExpire = TokenCache.getExpire(cacheKey);
if (cachedPuus != null && System.currentTimeMillis() < puusExpire) {
cookie = CookieUtils.updateCookieValue(cookie, "__puus", cachedPuus);
log.debug("UC: 使用缓存的 __puus (剩余有效期: {}s)", (puusExpireTime - System.currentTimeMillis()) / 1000);
log.debug("UC: 使用缓存的 __puus (剩余有效期: {}s)", (puusExpire - System.currentTimeMillis()) / 1000);
}
header.set(HttpHeaders.COOKIE, cookie);
// 同步更新 auths
auths.set("cookie", cookie);
}
}
// 如果 __puus 已过期或不存在,触发异步刷新
if (needRefreshPuus()) {
log.debug("UC: __puus 需要刷新,触发异步刷新");
@@ -110,7 +120,7 @@ public class UcTool extends PanBase {
return false;
}
// 缓存过期或不存在时需要刷新
return cachedPuus == null || System.currentTimeMillis() >= puusExpireTime;
return TokenCache.getToken(cacheKey) == null || System.currentTimeMillis() >= TokenCache.getExpire(cacheKey);
}
/**
@@ -164,11 +174,10 @@ public class UcTool extends PanBase {
auths.set("cookie", updatedCookie);
}
// 更新静态缓存
cachedPuus = newPuus;
puusExpireTime = System.currentTimeMillis() + PUUS_TTL_MS;
log.info("UC: __puus cookie 刷新成功,有效期至: {}ms", puusExpireTime);
TokenCache.putToken(cacheKey, newPuus);
TokenCache.putExpire(cacheKey, System.currentTimeMillis() + PUUS_TTL_MS);
log.info("UC: __puus cookie 刷新成功,有效期至: {}ms", TokenCache.getExpire(cacheKey));
refreshPromise.complete(true);
} else {
log.debug("UC: 响应中未包含 __puus,可能 cookie 仍然有效");
@@ -242,40 +251,16 @@ public class UcTool extends PanBase {
log.warn("UC 提取文件信息失败,继续解析: {}", e.getMessage());
}
// 第三次请求获取下载链接
var bodyJson = JsonObject.of()
.put("fids", JsonArray.of(info.getString("fid")))
.put("pwd_id", dataKey)
.put("stoken", stoken)
.put("fids_token", JsonArray.of(info.getString("share_fid_token")));
client.postAbs(THIRD_REQUEST_URL)
.putHeaders(header)
.sendJsonObject(bodyJson)
.onSuccess(res3 -> {
log.debug("第三阶段 {}", res3.body());
var resJson3 = res3.bodyAsJsonObject();
if (resJson3.getInteger("code") != 0) {
fail(FIRST_REQUEST_URL + " 返回异常: " + resJson2);
return;
}
try {
JsonArray dataList = resJson3.getJsonArray("data");
if (dataList == null || dataList.isEmpty()) {
fail("UC API 返回的下载链接列表为空");
return;
}
String downloadUrl = dataList.getJsonObject(0).getString("download_url");
// UC网盘需要配合aria2下载,保存下载请求头
Map<String, String> downloadHeaders = new HashMap<>();
// 将header转换为Map 只需要包含cookie,user-agent,referer
downloadHeaders.put(HttpHeaders.COOKIE.toString(), header.get(HttpHeaders.COOKIE));
downloadHeaders.put(HttpHeaders.USER_AGENT.toString(), header.get(HttpHeaders.USER_AGENT));
downloadHeaders.put(HttpHeaders.REFERER.toString(), "https://fast.uc.cn/");
completeWithMeta(downloadUrl, downloadHeaders);
} catch (Exception e) {
fail("解析 UC 下载链接失败: " + e.getMessage());
}
}).onFailure(handleFail(THIRD_REQUEST_URL));
String fid = info.getString("fid");
String shareFidToken = info.getString("share_fid_token");
Future<String> download;
if (QuarkFamilyDownloadPolicy.knownLarge(QuarkFamilyDownloadPolicy.sizeOf(info))) {
download = resolveUcLarge(fid, dataKey, stoken, shareFidToken, info.getString("file_name"));
} else {
download = requestUcDownload(fid, dataKey, stoken, shareFidToken);
}
download.onSuccess(this::finishUcParse)
.onFailure(t -> fail(t.getMessage() == null ? "解析失败" : t.getMessage()));
} catch (Exception e) {
fail("解析 UC 文件信息失败: " + e.getMessage());
}
@@ -286,6 +271,108 @@ public class UcTool extends PanBase {
return promise.future();
}
/**
* 大于 10MiB 才检查会员。有效 SVIP/VIP 仍走原来的账号 {@code /file/download};
* 否则只接受探测通过的 H5 文件地址。没有该地址时明确失败,不把 UC 说成免登录。
*/
private Future<String> resolveUcLarge(String fid, String pwdId, String stoken, String shareFidToken, String fileName) {
if (fid == null || fid.isEmpty()) {
return Future.failedFuture(QuarkFamilyDownloadPolicy.largeFileError("uc", null,
new IllegalStateException("缺少 fid")));
}
return QuarkFamilyDownloadPolicy.fetchMembership(client, header, true)
.compose(member -> {
if (!member.validPaid) {
return ucH5(pwdId, stoken, fid, shareFidToken, fileName)
.recover(h5Error -> Future.failedFuture(
QuarkFamilyDownloadPolicy.largeFileError("uc", null, h5Error)));
}
return requestUcDownload(fid, pwdId, stoken, shareFidToken)
.recover(directError -> ucH5(pwdId, stoken, fid, shareFidToken, fileName)
.recover(h5Error -> Future.failedFuture(
QuarkFamilyDownloadPolicy.largeFileError("uc", directError, h5Error))));
});
}
private Future<String> ucH5(String pwdId, String stoken, String fid, String shareFidToken, String fileName) {
return QuarkFamilyDownloadPolicy.resolveH5Download(clientNoRedirects, WebClientVertxInit.get(),
"uc", pwdId, stoken, fid, shareFidToken, fileName)
.map(url -> {
publicDirectLink = true;
shareLinkInfo.getOtherParam().put("publicDirectLink", true);
shareLinkInfo.getOtherParam().put("previewUrl", QuarkFamilyDownloadPolicy.bareFileUrl(url));
return url;
});
}
private Future<String> requestUcDownload(String fid, String pwdId, String stoken, String shareFidToken) {
Promise<String> downloadPromise = Promise.promise();
JsonObject bodyJson = JsonObject.of()
.put("fids", JsonArray.of(fid))
.put("pwd_id", pwdId)
.put("stoken", stoken);
if (shareFidToken != null && !shareFidToken.isEmpty()) {
bodyJson.put("fids_token", JsonArray.of(shareFidToken));
}
client.postAbs(THIRD_REQUEST_URL)
.putHeaders(header)
.sendJsonObject(bodyJson)
.onSuccess(res3 -> {
log.debug("UC 下载接口 {}", res3.body());
JsonObject resJson3 = res3.bodyAsJsonObject();
if (resJson3.getInteger("code") == null || resJson3.getInteger("code") != 0) {
downloadPromise.fail(THIRD_REQUEST_URL + " 返回异常: " + resJson3);
return;
}
try {
JsonArray dataList = resJson3.getJsonArray("data");
if (dataList == null || dataList.isEmpty()) {
downloadPromise.fail("UC API 返回的下载链接列表为空");
return;
}
String downloadUrl = dataList.getJsonObject(0).getString("download_url");
if (downloadUrl == null || downloadUrl.isEmpty()) {
downloadPromise.fail("未找到下载链接");
return;
}
downloadPromise.complete(downloadUrl);
} catch (Exception e) {
downloadPromise.fail("解析 UC 下载链接失败: " + e.getMessage());
}
})
.onFailure(t -> downloadPromise.fail("请求下载链接失败: " + t.getMessage()));
return downloadPromise.future();
}
private void finishUcParse(String downloadUrl) {
String presented = presentUcIfPublic(downloadUrl);
if (publicDirectLink) {
completeWithMeta(presented, Map.of());
shareLinkInfo.getOtherParam().put("needDownloader", false);
return;
}
completeWithMeta(presented, buildDownloadHeaders(null));
}
private String presentUcIfPublic(String downloadUrl) {
String presented = QuarkFamilyDownloadPolicy.presentPublicDownload(downloadUrl, "uc", currentUcFileName());
if (!presented.equals(downloadUrl) || QuarkFamilyDownloadPolicy.isPublicFileUrl(presented, "uc")) {
publicDirectLink = true;
shareLinkInfo.getOtherParam().put("publicDirectLink", true);
shareLinkInfo.getOtherParam().put("previewUrl", QuarkFamilyDownloadPolicy.bareFileUrl(presented));
}
return presented;
}
private String currentUcFileName() {
Object info = shareLinkInfo.getOtherParam().get("fileInfo");
if (info instanceof FileInfo file && file.getFileName() != null && !file.getFileName().isBlank()) {
return file.getFileName();
}
Object name = shareLinkInfo.getOtherParam().get("fileName");
return name == null ? "" : name.toString();
}
// 目录解析
@Override
public Future<List<FileInfo>> parseFileList() {
@@ -466,29 +553,41 @@ public class UcTool extends PanBase {
if (shareFidToken != null) {
extParams.put("share_fid_token", shareFidToken);
}
extParams.put("size", fileSize);
extParams.put("needDownloader", true);
Map<String, String> dlHeaders = new HashMap<>();
String listCookie = header.get(HttpHeaders.COOKIE);
if (listCookie != null && !listCookie.isEmpty()) {
dlHeaders.put(HttpHeaders.COOKIE.toString(), listCookie);
}
dlHeaders.put(HttpHeaders.USER_AGENT.toString(), header.get(HttpHeaders.USER_AGENT));
dlHeaders.put(HttpHeaders.REFERER.toString(), "https://fast.uc.cn/");
extParams.put("downloadHeaders", dlHeaders);
fileInfo.setExtParameters(extParams);
// 设置解析URL(用于下载)
JsonObject paramJson = new JsonObject(extParams);
paramJson.put("fileName", fileName);
String param = CommonUtils.urlBase64Encode(paramJson.encode());
fileInfo.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
getDomainName(), shareLinkInfo.getType(), param));
// 透传 auth,避免下载/转存时变成 guest
fileInfo.setParserUrl(appendAuthQuery(String.format("%s/v2/redirectUrl/%s/%s",
getDomainName(), shareLinkInfo.getType(), param)));
} else {
// 文件夹
fileInfo.setFileType("folder");
fileInfo.setSize(0L);
fileInfo.setSizeStr("0B");
// 设置目录解析URL(用于递归解析子目录)
// 对 URL 参数进行编码,确保特殊字符正确传递
// 递归子目录须透传 auth,否则会丢失认证
try {
String encodedUrl = URLEncoder.encode(shareLinkInfo.getShareUrl(), StandardCharsets.UTF_8.toString());
String encodedDirId = URLEncoder.encode(fid, StandardCharsets.UTF_8.toString());
String encodedStoken = URLEncoder.encode(stoken, StandardCharsets.UTF_8.toString());
fileInfo.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&stoken=%s",
getDomainName(), encodedUrl, encodedDirId, encodedStoken));
fileInfo.setParserUrl(appendAuthQuery(String.format(
"%s/v2/getFileList?url=%s&dirId=%s&stoken=%s",
getDomainName(), encodedUrl, encodedDirId, encodedStoken)));
} catch (Exception e) {
// 如果编码失败,使用原始值
fileInfo.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&stoken=%s",
getDomainName(), shareLinkInfo.getShareUrl(), fid, stoken));
fileInfo.setParserUrl(appendAuthQuery(String.format(
"%s/v2/getFileList?url=%s&dirId=%s&stoken=%s",
getDomainName(), shareLinkInfo.getShareUrl(), fid, stoken)));
}
}
@@ -510,6 +609,9 @@ public class UcTool extends PanBase {
promise.fail("缺少必要的参数");
return promise.future();
}
// 会话无 cookie 时,回退使用入口参数中已带的 cookie
ensureCookieFromParam(paramJson);
String fid = paramJson.getString("fid");
String pwdId = paramJson.getString("pwd_id");
@@ -522,48 +624,78 @@ public class UcTool extends PanBase {
}
log.debug("UC parseById: fid={}, pwd_id={}, stoken={}", fid, pwdId, stoken);
// 调用第三次请求获取下载链接
JsonObject bodyJson = JsonObject.of()
.put("fids", JsonArray.of(fid))
.put("pwd_id", pwdId)
.put("stoken", stoken);
if (shareFidToken != null && !shareFidToken.isEmpty()) {
bodyJson.put("fids_token", JsonArray.of(shareFidToken));
String fileName = paramJson.getString("fileName", "");
Future<String> download;
if (QuarkFamilyDownloadPolicy.knownLarge(QuarkFamilyDownloadPolicy.sizeOf(paramJson))) {
download = resolveUcLarge(fid, pwdId, stoken, shareFidToken, fileName);
} else {
download = requestUcDownload(fid, pwdId, stoken, shareFidToken);
}
client.postAbs(THIRD_REQUEST_URL)
.putHeaders(header)
.sendJsonObject(bodyJson)
.onSuccess(res -> {
log.debug("UC parseById 响应: {}", res.body());
JsonObject resJson = res.bodyAsJsonObject();
if (resJson.getInteger("code") != 0) {
promise.fail(THIRD_REQUEST_URL + " 返回异常: " + resJson);
return;
}
try {
JsonArray dataList = resJson.getJsonArray("data");
if (dataList == null || dataList.isEmpty()) {
promise.fail("UC API 返回的下载链接列表为空");
return;
}
String downloadUrl = dataList.getJsonObject(0).getString("download_url");
if (downloadUrl == null || downloadUrl.isEmpty()) {
promise.fail("未找到下载链接");
return;
}
promise.complete(downloadUrl);
} catch (Exception e) {
promise.fail("解析 UC 下载链接失败: " + e.getMessage());
download.onSuccess(downloadUrl -> {
shareLinkInfo.getOtherParam().put("fileName", fileName);
String presented = presentUcIfPublic(downloadUrl);
if (publicDirectLink) {
shareLinkInfo.getOtherParam().put("downloadHeaders", new HashMap<>());
shareLinkInfo.getOtherParam().put("needDownloader", false);
} else {
shareLinkInfo.getOtherParam().put("downloadHeaders", buildDownloadHeaders(paramJson));
shareLinkInfo.getOtherParam().put("needDownloader", true);
}
promise.complete(presented);
})
.onFailure(t -> promise.fail("请求下载链接失败: " + t.getMessage()));
.onFailure(t -> promise.fail(t.getMessage() == null ? "请求下载链接失败" : t.getMessage()));
return promise.future();
}
/**
* 会话无 cookie 时,从入口参数 downloadHeaders 回填到请求头。
*/
private void ensureCookieFromParam(JsonObject paramJson) {
String cookie = header.get(HttpHeaders.COOKIE);
if (cookie != null && !cookie.isEmpty()) {
return;
}
String paramCookie = extractCookieFromParam(paramJson);
if (paramCookie != null && !paramCookie.isEmpty()) {
header.set(HttpHeaders.COOKIE, CookieUtils.filterUcQuarkCookie(paramCookie));
}
}
private static String extractCookieFromParam(JsonObject paramJson) {
if (paramJson == null) {
return null;
}
JsonObject paramHeaders = paramJson.getJsonObject("downloadHeaders");
if (paramHeaders == null) {
return null;
}
String cookie = paramHeaders.getString("cookie");
return cookie != null ? cookie : paramHeaders.getString("Cookie");
}
/**
* 构建下载请求头:会话 cookie 优先,缺失时回退入口参数中的 downloadHeaders。
*/
private Map<String, String> buildDownloadHeaders(JsonObject paramJson) {
Map<String, String> downloadHeaders = new HashMap<>();
String cookie = header.get(HttpHeaders.COOKIE);
if (cookie == null || cookie.isEmpty()) {
cookie = extractCookieFromParam(paramJson);
}
if (cookie != null && !cookie.isEmpty()) {
downloadHeaders.put(HttpHeaders.COOKIE.toString(), cookie);
}
String ua = header.get(HttpHeaders.USER_AGENT);
if (ua == null || ua.isEmpty()) {
ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
}
downloadHeaders.put(HttpHeaders.USER_AGENT.toString(), ua);
downloadHeaders.put(HttpHeaders.REFERER.toString(), "https://fast.uc.cn/");
return downloadHeaders;
}
// public static void main(String[] args) {
// // https://drive.uc.cn/s/12450d1694844?public=1
// new UcTool(ShareLinkInfo.newBuilder().shareKey("12450d1694844").build()).parse().onSuccess(
File diff suppressed because it is too large. Load diff
@@ -1,9 +1,11 @@
package cn.qaiu.parser.impl;
import cn.qaiu.util.Base64Encoder;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.PanBase;
import cn.qaiu.util.CommonUtils;
import cn.qaiu.util.Base64Decoder;
import cn.qaiu.util.FileSizeConverter;
import cn.qaiu.util.JsExecUtils;
import io.vertx.core.Future;
@@ -21,7 +23,6 @@ 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.regex.Matcher;
@@ -166,7 +167,7 @@ public class YeTool extends PanBase {
try {
Map<String, String> urlParams = CommonUtils.getURLParams(downURL);
String params = urlParams.get("params");
byte[] decodeByte = Base64.getDecoder().decode(params);
byte[] decodeByte = Base64Decoder.decode(params);
String downUrl2 = new String(decodeByte);
// 获取直链
@@ -261,7 +262,7 @@ public class YeTool extends PanBase {
.put("Size", item.getLong("Size"))
.put("Etag", item.getString("Etag"));
byte[] encode = Base64.getEncoder().encode(postData.encode().getBytes());
byte[] encode = Base64Encoder.encodeBytes(postData.encode().getBytes());
String param = new String(encode);
if (item.getInteger("Type") == 0) { // 文件
@@ -0,0 +1,841 @@
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 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.ext.web.client.HttpResponse;
import org.apache.commons.lang3.StringUtils;
import java.net.URI;
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;
/**
* 永硕E盘(主 ysepan.com / ys168.com,备 cccpan.com / ysupan.com / uupan.net / ysok.net)
* <p>
* 空间分享形如 https://{space}.ysepan.com/ ,需空间访问密码时通过 sharePassword 传入。
* <p>
* 2026-11 起密码空间改为入口页:令牌在 {@code data-verification-token},登录名在 {@code data-dlmc}。
* {@code ys168.com} 会 302 到 {@code ysepan.com},密码验证必须发往跳转后的主机。
*/
public class YsTool extends PanBase {
private static final String BROWSER_UA =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36";
/** 旧版入口脚本:{@code RequestVerificationToken': '...'} */
private static final Pattern ANTIFORGERY_LEGACY_PATTERN =
Pattern.compile("RequestVerificationToken'\\s*:\\s*'([^']+)'");
/** 新版入口页:{@code data-verification-token="..."} */
private static final Pattern ANTIFORGERY_ATTR_PATTERN =
Pattern.compile("data-verification-token\\s*=\\s*([\"'])([^\"']+)\\1");
private static final Pattern DLMC_ATTR_PATTERN =
Pattern.compile("data-dlmc\\s*=\\s*([\"'])([^\"']+)\\1");
private static final Pattern HTXX_PATTERN =
Pattern.compile("window\\.htxx\\s*=\\s*(\\{.*?});", Pattern.DOTALL);
private static final int MAX_HOME_REDIRECTS = 5;
private static final Pattern JWT_COOKIE_PATTERN =
Pattern.compile("jwttk_[^=]+=([^;\\s]+)");
private static final String PARAM_DIR_ID = "dirId";
/** 永硕目录内的子目录名(API 字段 zml),用于二级层级 */
private static final String PARAM_ZML = "zml";
public YsTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
}
@Override
public Future<String> parse() {
ensureSession().onSuccess(session -> {
Object dirIdObj = shareLinkInfo.getOtherParam().get(PARAM_DIR_ID);
if (dirIdObj != null && StringUtils.isNotBlank(dirIdObj.toString())) {
int dirId = Integer.parseInt(dirIdObj.toString());
fetchFiles(session, dirId).onSuccess(filesResp -> {
List<JsonObject> files = downloadableFiles(filesResp);
if (files.isEmpty()) {
fail("目录内没有可下载文件");
return;
}
completeDownload(session, filesResp, files.get(0));
}).onFailure(err -> fail(err, err.getMessage()));
return;
}
fetchDirectories(session).compose(dirs -> collectDownloadableFiles(session, dirs))
.onSuccess(collected -> {
if (collected.isEmpty()) {
fail("空间内没有可下载文件,请检查密码或目录权限");
return;
}
if (collected.size() > 1) {
fail("空间包含多个文件(共{}个),请使用文件列表接口后再按文件解析", collected.size());
return;
}
CollectedFile only = collected.get(0);
completeDownload(session, only.filesResp, only.file);
}).onFailure(err -> fail(err, err.getMessage()));
}).onFailure(err -> fail(err, err.getMessage()));
return promise.future();
}
@Override
public Future<List<FileInfo>> parseFileList() {
Promise<List<FileInfo>> listPromise = Promise.promise();
ensureSession().onSuccess(session -> {
Object dirIdObj = shareLinkInfo.getOtherParam().get(PARAM_DIR_ID);
if (dirIdObj != null && StringUtils.isNotBlank(dirIdObj.toString())) {
int dirId = Integer.parseInt(dirIdObj.toString());
String zmlFilter = currentZmlFilter();
fetchFiles(session, dirId).onSuccess(filesResp -> {
try {
listPromise.complete(mapFiles(session, dirId, filesResp, zmlFilter));
} catch (Exception e) {
listPromise.fail(baseMsg() + " - 解析文件列表失败: " + e.getMessage());
}
}).onFailure(listPromise::fail);
return;
}
fetchDirectories(session).onSuccess(dirs -> {
try {
listPromise.complete(mapDirectories(session, dirs));
} catch (Exception e) {
listPromise.fail(baseMsg() + " - 解析目录列表失败: " + e.getMessage());
}
}).onFailure(listPromise::fail);
}).onFailure(listPromise::fail);
return listPromise.future();
}
@Override
public Future<String> parseById() {
JsonObject paramJson = (JsonObject) shareLinkInfo.getOtherParam().get("paramJson");
if (paramJson == null) {
fail("缺少 paramJson 参数");
return promise.future();
}
String downloadUrl = paramJson.getString("downloadUrl");
if (StringUtils.isNotBlank(downloadUrl)) {
completeWithMeta(downloadUrl, downloadHeaders(paramJson.getString("referer")));
return promise.future();
}
String space = paramJson.getString("space", spaceName());
String xzpz = paramJson.getString("xzpz");
String pz = paramJson.getString("pz");
String fwq = paramJson.getString("fwq");
String fileName = paramJson.getString("fileName");
if (StringUtils.isAnyBlank(space, xzpz, pz, fwq, fileName)) {
fail("下载参数不完整: {}", paramJson);
return promise.future();
}
String url = buildDownloadUrl(space, xzpz, pz, fwq, fileName);
completeWithMeta(url, downloadHeaders(paramJson.getString("referer", spaceOrigin())));
return promise.future();
}
private Future<Session> ensureSession() {
String space = spaceName();
if (StringUtils.isBlank(space)) {
return Future.failedFuture(baseMsg() + " - 空间名为空");
}
// 手动跟随跳转,才能把后续密码验证发到最终主机(ys168.com -> ysepan.com)
return fetchSpaceHome(spaceOrigin() + "/", 0)
.compose(home -> handleSpaceHome(home.origin(), space, home.response()));
}
/**
* 关闭自动重定向并逐跳记录最终地址。Cookie(含 .AspNetCore.Antiforgery.* 与 jwttk_*)
* 仍由同一个 clientSession 保存,供密码验证和接口请求带上。
*/
private Future<FetchedHome> fetchSpaceHome(String url, int redirects) {
Promise<FetchedHome> p = Promise.promise();
clientSession.getAbs(url)
.followRedirects(false)
.putHeader("User-Agent", BROWSER_UA)
.putHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
.send()
.onSuccess(res -> {
int status = res.statusCode();
if (status >= 300 && status < 400 && status != 304) {
if (redirects >= MAX_HOME_REDIRECTS) {
p.fail(baseMsg() + " - 空间首页重定向次数过多");
return;
}
String next = resolveRedirect(url, res.getHeader("Location"));
if (next == null) {
p.fail(baseMsg() + " - 空间首页重定向无效");
return;
}
fetchSpaceHome(next, redirects + 1).onComplete(p);
return;
}
String origin = originOf(url);
if (origin == null) {
p.fail(baseMsg() + " - 空间地址无效");
return;
}
p.complete(new FetchedHome(origin, res));
})
.onFailure(t -> p.fail(baseMsg() + " - 打开空间失败: " + t.getMessage()));
return p.future();
}
private Future<Session> handleSpaceHome(String origin, String space, HttpResponse<Buffer> res) {
String html = res.bodyAsString() != null ? res.bodyAsString() : "";
String jwt = extractJwt(res);
JsonObject htxx = extractHtxx(html);
// 已进入空间
if (htxx != null && StringUtils.isNotBlank(htxx.getString("qqdz"))) {
if (StringUtils.isBlank(jwt)) {
return Future.failedFuture(baseMsg() + " - 无法获取会话令牌");
}
return Future.succeededFuture(toSession(origin, space, jwt, htxx));
}
// 需要空间密码(新版入口页或旧版 loginPopup / VerifyPassword)
if (isPasswordPage(html)) {
String pwd = shareLinkInfo.getSharePassword();
if (StringUtils.isBlank(pwd)) {
return Future.failedFuture(baseMsg() + " - 空间需要访问密码");
}
String antiforgery = extractAntiforgery(html);
if (StringUtils.isBlank(antiforgery)) {
return Future.failedFuture(baseMsg() + " - 无法获取防伪令牌");
}
String dlmc = StringUtils.defaultIfBlank(extractDlmc(html), space);
// 新版 VerifyPassword 只返回 {"success":true},jwttk 在入口页就已经下发
return verifyPassword(origin, dlmc, pwd, antiforgery)
.compose(verifiedJwt -> reloadSpace(origin, space,
StringUtils.defaultIfBlank(verifiedJwt, jwt)));
}
return Future.failedFuture(baseMsg() + " - 无法解析空间信息");
}
private Future<String> verifyPassword(String origin, String dlmc, String pwd, String antiforgery) {
Promise<String> p = Promise.promise();
JsonObject body = new JsonObject()
.put("password", pwd)
.put("dlmc", dlmc)
.put("remember", false);
clientSession.postAbs(verifyPasswordEndpoint(origin))
.followRedirects(false)
.putHeader("User-Agent", BROWSER_UA)
.putHeader("Content-Type", "application/json")
.putHeader("Origin", origin)
.putHeader("Referer", origin + "/")
.putHeader("RequestVerificationToken", antiforgery)
.sendJsonObject(body)
.onSuccess(res -> {
try {
if (res.statusCode() >= 400) {
p.fail(baseMsg() + " - " + passwordFailureMessage(res.statusCode(), res.bodyAsString()));
return;
}
JsonObject json = res.bodyAsJsonObject();
if (json == null || !Boolean.TRUE.equals(json.getBoolean("success"))) {
String msg = json != null ? json.getString("message", "密码错误") : "密码验证失败";
p.fail(baseMsg() + " - " + msg);
return;
}
// 响应里若刷新了 jwttk 就用新的;否则调用方回退到入口页令牌
p.complete(StringUtils.defaultString(extractJwt(res)));
} catch (Exception e) {
p.fail(baseMsg() + " - 密码验证响应异常: " + e.getMessage());
}
})
.onFailure(t -> p.fail(baseMsg() + " - 密码验证请求失败: " + t.getMessage()));
return p.future();
}
private Future<Session> reloadSpace(String origin, String space, String verifiedJwt) {
return fetchSpaceHome(origin + "/", 0).compose(home -> {
String html = home.response().bodyAsString() != null ? home.response().bodyAsString() : "";
JsonObject htxx = extractHtxx(html);
String jwt = StringUtils.defaultIfBlank(extractJwt(home.response()), verifiedJwt);
if (htxx == null || StringUtils.isBlank(htxx.getString("qqdz"))) {
return Future.failedFuture(baseMsg() + " - 密码验证后仍无法进入空间");
}
if (StringUtils.isBlank(jwt)) {
return Future.failedFuture(baseMsg() + " - 密码验证后无法获取会话令牌");
}
return Future.succeededFuture(toSession(home.origin(), space, jwt, htxx));
});
}
private Session toSession(String origin, String space, String jwt, JsonObject htxx) {
String apiBase = htxx.getString("qqdz");
if (apiBase != null && !apiBase.endsWith("/")) {
apiBase = apiBase + "/";
}
String dlmc = htxx.getString("dlmc", space);
return new Session(origin, dlmc, jwt, apiBase);
}
private Future<JsonArray> fetchDirectories(Session session) {
Promise<JsonArray> p = Promise.promise();
apiPost(session, "ml/mldq", new JsonObject())
.onSuccess(json -> {
JsonArray lb = json.getJsonArray("lb");
p.complete(lb != null ? lb : new JsonArray());
})
.onFailure(p::fail);
return p.future();
}
private Future<JsonObject> fetchFiles(Session session, int dirId) {
Promise<JsonObject> p = Promise.promise();
JsonObject body = new JsonObject()
.put("mlbh", dirId)
.put("kqmm", "")
.put("wjbh", 0)
.put("ip1", "");
apiPost(session, "wj/wjdq", body)
.onSuccess(p::complete)
.onFailure(p::fail);
return p.future();
}
private Future<JsonObject> apiPost(Session session, String path, JsonObject body) {
Promise<JsonObject> p = Promise.promise();
String url = session.apiBase + path;
HttpRequest<Buffer> req = clientSession.postAbs(url)
.putHeader("User-Agent", BROWSER_UA)
.putHeader("Accept", "application/json, text/plain, */*")
.putHeader("Content-Type", "application/json")
.putHeader("Origin", session.origin)
.putHeader("Referer", session.origin + "/")
.putHeader("Authorization", "Bearer " + session.jwt);
req.sendJsonObject(body)
.onSuccess(res -> {
try {
if (res.statusCode() >= 400) {
p.fail(baseMsg() + " - API " + path + " HTTP " + res.statusCode());
return;
}
JsonObject json = asJson(res);
if (json == null || json.isEmpty()) {
p.fail(baseMsg() + " - API " + path + " 返回空响应");
return;
}
p.complete(json);
} catch (Exception e) {
p.fail(baseMsg() + " - API " + path + " 响应异常: " + e.getMessage());
}
})
.onFailure(t -> p.fail(baseMsg() + " - API " + path + " 请求失败: " + t.getMessage()));
return p.future();
}
private Future<List<CollectedFile>> collectDownloadableFiles(Session session, JsonArray dirs) {
Promise<List<CollectedFile>> p = Promise.promise();
List<CollectedFile> collected = new ArrayList<>();
List<Integer> dirIds = new ArrayList<>();
for (int i = 0; i < dirs.size(); i++) {
JsonObject dir = dirs.getJsonObject(i);
if (isAccessibleDirectory(dir)) {
dirIds.add(dir.getInteger("bh"));
}
}
if (dirIds.isEmpty()) {
p.complete(collected);
return p.future();
}
fetchNextDirFiles(session, dirIds, 0, collected, p);
return p.future();
}
private void fetchNextDirFiles(Session session, List<Integer> dirIds, int index,
List<CollectedFile> collected, Promise<List<CollectedFile>> promise) {
if (index >= dirIds.size()) {
promise.complete(collected);
return;
}
int dirId = dirIds.get(index);
fetchFiles(session, dirId).onSuccess(filesResp -> {
for (JsonObject file : downloadableFiles(filesResp)) {
collected.add(new CollectedFile(filesResp, file));
}
fetchNextDirFiles(session, dirIds, index + 1, collected, promise);
}).onFailure(promise::fail);
}
private List<FileInfo> mapDirectories(Session session, JsonArray dirs) {
List<FileInfo> result = new ArrayList<>();
for (int i = 0; i < dirs.size(); i++) {
JsonObject dir = dirs.getJsonObject(i);
if (!isAccessibleDirectory(dir)) {
continue;
}
Integer bh = dir.getInteger("bh");
if (bh == null) {
continue;
}
String title = StringUtils.defaultIfBlank(dir.getString("bt"), "目录" + bh);
FileInfo info = new FileInfo()
.setFileName(title)
.setFileId(bh.toString())
.setFileType("folder")
.setSize(0L)
.setSizeStr("0B")
.setDescription(dir.getString("sm", ""))
.setCreateTime(normalizeTime(dir.getString("sj")))
.setPanType(shareLinkInfo.getType())
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&pwd=%s",
getDomainName(),
urlEncode(shareLinkInfo.getShareUrl()),
bh,
urlEncode(StringUtils.defaultString(shareLinkInfo.getSharePassword()))));
result.add(info);
}
return result;
}
/**
* 将目录内文件按 zml(子目录)分层。
* <ul>
* <li>zmlFilter 为空:返回子目录(folder)+ 根级文件</li>
* <li>zmlFilter 非空:仅返回该子目录下的文件/链接</li>
* </ul>
*/
private List<FileInfo> mapFiles(Session session, int dirId, JsonObject filesResp, String zmlFilter) {
List<FileInfo> result = new ArrayList<>();
String xzpz = filesResp.getJsonObject("ml", new JsonObject()).getString("xzpz", "");
JsonArray lb = filesResp.getJsonArray("lb", new JsonArray());
boolean listingSubdir = StringUtils.isNotBlank(zmlFilter);
// 未进入子目录时,先按出现顺序收集 zml 作为二级文件夹
if (!listingSubdir) {
java.util.LinkedHashSet<String> subdirs = new java.util.LinkedHashSet<>();
for (int i = 0; i < lb.size(); i++) {
JsonObject item = lb.getJsonObject(i);
if (item == null) {
continue;
}
String zml = StringUtils.defaultString(item.getString("zml")).trim();
if (StringUtils.isNotBlank(zml)) {
subdirs.add(zml);
}
}
for (String zml : subdirs) {
result.add(new FileInfo()
.setFileName(zml)
.setFileId(dirId + ":" + zml)
.setFileType("folder")
.setSize(0L)
.setSizeStr("0B")
.setFilePath(zml)
.setPanType(shareLinkInfo.getType())
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&zml=%s&pwd=%s",
getDomainName(),
urlEncode(shareLinkInfo.getShareUrl()),
dirId,
urlEncode(zml),
urlEncode(StringUtils.defaultString(shareLinkInfo.getSharePassword())))));
}
}
for (int i = 0; i < lb.size(); i++) {
JsonObject item = lb.getJsonObject(i);
if (item == null) {
continue;
}
String itemZml = StringUtils.defaultString(item.getString("zml")).trim();
if (listingSubdir) {
if (!zmlFilter.equals(itemZml)) {
continue;
}
} else if (StringUtils.isNotBlank(itemZml)) {
// 根级列表只展示无 zml 的条目,有 zml 的归入子目录
continue;
}
Integer bh = item.getInteger("bh");
if (bh == null) {
continue;
}
String wjlx = item.getString("wjlx", "");
// URL / 公告条目
if ("url".equalsIgnoreCase(wjlx)) {
String link = StringUtils.defaultString(item.getString("wjm")).trim();
String title = StringUtils.defaultString(item.getString("bt")).trim();
// 空占位(标题和链接都空)跳过,与官网展示一致
if (StringUtils.isAllBlank(title, link)) {
continue;
}
if (StringUtils.isBlank(title)) {
title = StringUtils.defaultIfBlank(link, "链接");
}
FileInfo urlInfo = new FileInfo()
.setFileName(title)
.setFileId(bh.toString())
.setFileType("url")
.setSize(0L)
.setSizeStr("0B")
.setFilePath(itemZml)
.setCreateTime(normalizeTime(item.getString("sj")))
.setPanType(shareLinkInfo.getType())
.setPreviewUrl(link)
.setDescription(link);
// parserUrl 置空,避免前端误走下载;打开走 previewUrl
result.add(urlInfo);
continue;
}
String fileName = item.getString("wjm");
String fwq = item.getString("fwq");
String pz = item.getString("pz");
if (StringUtils.isAnyBlank(fileName, fwq, pz, xzpz)) {
continue;
}
long size = item.getLong("dx", 0L);
String downloadUrl = buildDownloadUrl(session.space, xzpz, pz, fwq, fileName);
JsonObject param = new JsonObject()
.put("space", session.space)
.put("xzpz", xzpz)
.put("pz", pz)
.put("fwq", fwq)
.put("fileName", fileName)
.put("mlbh", dirId)
.put("fileId", bh)
.put("downloadUrl", downloadUrl)
.put("referer", session.origin + "/");
String paramEncoded = CommonUtils.urlBase64Encode(param.encode());
FileInfo fileInfo = new FileInfo()
.setFileName(fileName)
.setFileId(bh.toString())
.setFileType("file")
.setSize(size)
.setSizeStr(FileSizeConverter.convertToReadableSize(size))
.setFilePath(itemZml)
.setCreateTime(normalizeTime(item.getString("sj")))
.setPanType(shareLinkInfo.getType())
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
getDomainName(), shareLinkInfo.getType(), paramEncoded))
.setPreviewUrl(String.format("%s/v2/viewUrl/%s/%s",
getDomainName(), shareLinkInfo.getType(), paramEncoded));
result.add(fileInfo);
}
return result;
}
private String currentZmlFilter() {
Object zml = shareLinkInfo.getOtherParam().get(PARAM_ZML);
if (zml == null) {
return "";
}
try {
return java.net.URLDecoder.decode(zml.toString(), StandardCharsets.UTF_8).trim();
} catch (Exception e) {
return zml.toString().trim();
}
}
private List<JsonObject> downloadableFiles(JsonObject filesResp) {
List<JsonObject> files = new ArrayList<>();
String xzpz = filesResp.getJsonObject("ml", new JsonObject()).getString("xzpz", "");
if (StringUtils.isBlank(xzpz)) {
return files;
}
JsonArray lb = filesResp.getJsonArray("lb", new JsonArray());
for (int i = 0; i < lb.size(); i++) {
JsonObject item = lb.getJsonObject(i);
if (item == null) {
continue;
}
if ("url".equalsIgnoreCase(item.getString("wjlx", ""))) {
continue;
}
if (StringUtils.isAnyBlank(item.getString("wjm"), item.getString("fwq"), item.getString("pz"))) {
continue;
}
files.add(item);
}
return files;
}
private void completeDownload(Session session, JsonObject filesResp, JsonObject file) {
String xzpz = filesResp.getJsonObject("ml", new JsonObject()).getString("xzpz");
String url = buildDownloadUrl(session.space, xzpz, file.getString("pz"),
file.getString("fwq"), file.getString("wjm"));
FileInfo fileInfo = new FileInfo()
.setFileName(file.getString("wjm"))
.setFileId(String.valueOf(file.getInteger("bh")))
.setSize(file.getLong("dx", 0L))
.setSizeStr(FileSizeConverter.convertToReadableSize(file.getLong("dx", 0L)))
.setFileType("file")
.setFilePath(file.getString("zml", ""))
.setCreateTime(normalizeTime(file.getString("sj")))
.setPanType(shareLinkInfo.getType());
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
completeWithMeta(url, downloadHeaders(session.origin + "/"));
}
/**
* 拼装直链。注意:不要在 xzpz 前加 "_",官方页面直链无此前缀,加了会 404。
*/
static String buildDownloadUrl(String space, String xzpz, String pz, String fwq, String fileName) {
String host = "X".equalsIgnoreCase(fwq)
? "y.ys168.com:8000"
: "ys-" + fwq.toLowerCase() + ".ysepan.com";
return "https://" + host + "/wap/"
+ encodePathSegment(space) + "/"
+ encodePathSegment(xzpz) + "/"
+ encodePathSegment(pz) + "/"
+ encodePathSegment(fileName);
}
private static String encodePathSegment(String value) {
// 保留永硕 token 中常见的 . , _ - 等字符,仅编码必须转义的部分
return URLEncoder.encode(value, StandardCharsets.UTF_8)
.replace("+", "%20")
.replace("%2E", ".")
.replace("%2C", ",")
.replace("%5F", "_")
.replace("%2D", "-");
}
private Map<String, String> downloadHeaders(String referer) {
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", BROWSER_UA);
if (StringUtils.isNotBlank(referer)) {
headers.put("Referer", referer);
}
return headers;
}
private boolean isAccessibleDirectory(JsonObject dir) {
if (dir == null) {
return false;
}
// 无可下载权限或需特殊打开方式的目录忽略
if (!Boolean.TRUE.equals(dir.getBoolean("qxz", true))) {
return false;
}
Integer kqfs = dir.getInteger("kqfs", 0);
return kqfs == null || kqfs == 0;
}
private String spaceName() {
String key = shareLinkInfo.getShareKey();
if (StringUtils.isBlank(key)) {
return null;
}
try {
return java.net.URLDecoder.decode(key, StandardCharsets.UTF_8);
} catch (Exception e) {
return key;
}
}
private String spaceOrigin() {
String fromUrl = originOf(shareLinkInfo.getShareUrl());
if (fromUrl != null) {
return fromUrl;
}
return "https://" + spaceName() + ".ysepan.com";
}
static boolean isPasswordPage(String html) {
if (StringUtils.isBlank(html)) {
return false;
}
return html.contains("VerifyPassword")
|| html.contains("loginPopup")
|| html.contains("data-verification-token")
|| html.contains("id=\"entryConfig\"")
|| html.contains("id=\"loginForm\"")
|| html.contains("id='entryConfig'")
|| html.contains("id='loginForm'");
}
/**
* 优先新版 data-verification-token,其次旧版脚本里的 RequestVerificationToken。
*/
static String extractAntiforgery(String html) {
if (html == null) {
return null;
}
Matcher attr = ANTIFORGERY_ATTR_PATTERN.matcher(html);
if (attr.find()) {
return attr.group(2);
}
Matcher legacy = ANTIFORGERY_LEGACY_PATTERN.matcher(html);
return legacy.find() ? legacy.group(1) : null;
}
static String extractDlmc(String html) {
if (html == null) {
return null;
}
Matcher matcher = DLMC_ATTR_PATTERN.matcher(html);
return matcher.find() ? matcher.group(2) : null;
}
/**
* 把密码接口的失败响应转成可展示的短句。上游对错误密码返回 HTTP 400,
* 正文是 {@code code=invalid_password}。不回传响应原文,避免带上令牌。
*/
static String passwordFailureMessage(int statusCode, String body) {
try {
if (body != null && body.trim().startsWith("{")) {
JsonObject json = new JsonObject(body);
String code = StringUtils.defaultString(json.getString("code"));
String message = safePasswordMessage(json.getString("message"));
if ("invalid_password".equals(code)) {
return message != null ? message : "密码错误";
}
if (message != null) {
return message;
}
}
} catch (Exception ignored) {
}
return "密码验证失败 HTTP " + statusCode;
}
private static String safePasswordMessage(String message) {
if (StringUtils.isBlank(message)) {
return null;
}
String trimmed = message.trim();
if (trimmed.length() > 80) {
return null;
}
String lower = trimmed.toLowerCase();
if (lower.contains("eyj") || trimmed.contains("CfDJ") || lower.contains("jwttk")
|| lower.contains("cookie") || lower.contains("token")) {
return null;
}
return trimmed;
}
/** 密码验证地址。origin 必须是重定向结束后的主机,不能用 ys168.com 原站。 */
static String verifyPasswordEndpoint(String origin) {
return origin + "/?handler=VerifyPassword";
}
static String resolveRedirect(String currentUrl, String location) {
if (StringUtils.isBlank(currentUrl) || StringUtils.isBlank(location)) {
return null;
}
try {
URI resolved = URI.create(currentUrl.trim()).resolve(location.trim());
if (resolved.getScheme() == null || resolved.getHost() == null) {
return null;
}
return resolved.toString();
} catch (Exception e) {
return null;
}
}
static String originOf(String url) {
if (StringUtils.isBlank(url)) {
return null;
}
try {
URI uri = URI.create(url.trim());
if (uri.getScheme() == null || uri.getHost() == null) {
return null;
}
String scheme = uri.getScheme();
int port = uri.getPort();
boolean defaultPort = port < 0
|| ("https".equalsIgnoreCase(scheme) && port == 443)
|| ("http".equalsIgnoreCase(scheme) && port == 80);
if (defaultPort) {
return scheme + "://" + uri.getHost();
}
return scheme + "://" + uri.getHost() + ":" + port;
} catch (Exception e) {
return null;
}
}
static JsonObject extractHtxx(String html) {
if (html == null) {
return null;
}
Matcher m = HTXX_PATTERN.matcher(html);
if (!m.find()) {
return null;
}
try {
return new JsonObject(m.group(1));
} catch (Exception e) {
return null;
}
}
private static String extractJwt(HttpResponse<Buffer> res) {
List<String> setCookies = res.cookies();
if (setCookies != null) {
for (String c : setCookies) {
Matcher m = JWT_COOKIE_PATTERN.matcher(c);
if (m.find()) {
return m.group(1);
}
}
}
String raw = res.getHeader("Set-Cookie");
if (raw != null) {
Matcher m = JWT_COOKIE_PATTERN.matcher(raw);
if (m.find()) {
return m.group(1);
}
}
return null;
}
private static String normalizeTime(String sj) {
if (StringUtils.isBlank(sj)) {
return sj;
}
// 2024-10-26T10:12:54.98 -> 2024-10-26 10:12:54
String t = sj.replace('T', ' ');
int dot = t.indexOf('.');
if (dot > 0) {
t = t.substring(0, dot);
}
return t;
}
private static String urlEncode(String value) {
return URLEncoder.encode(StringUtils.defaultString(value), StandardCharsets.UTF_8);
}
private record FetchedHome(String origin, HttpResponse<Buffer> response) {
}
private record Session(String origin, String space, String jwt, String apiBase) {
}
private record CollectedFile(JsonObject filesResp, JsonObject file) {
}
}
@@ -11,7 +11,6 @@ import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.HexFormat;
import java.util.regex.Matcher;
@@ -131,13 +130,13 @@ public class AESUtils {
public static String encryptBase64ByAES(String source, String keyString) throws NoSuchPaddingException,
NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
byte[] encrypted = encryptByAES(source, keyString);
return Base64.getEncoder().encodeToString(encrypted);
return Base64Encoder.encode(encrypted);
}
public static String encryptBase64ByAES(String source, Key key) throws NoSuchPaddingException,
NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
byte[] encrypted = encryptByAES(source, key);
return Base64.getEncoder().encodeToString(encrypted);
return Base64Encoder.encode(encrypted);
}
/**
@@ -219,12 +218,12 @@ public class AESUtils {
*/
public static String decryptByBase64AES(String encrypted, String keyString) throws IllegalBlockSizeException,
BadPaddingException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException {
return decryptByAES(Base64.getDecoder().decode(encrypted), keyString);
return decryptByAES(Base64Decoder.decode(encrypted), keyString);
}
public static String decryptByBase64AES(String encrypted, Key key) throws IllegalBlockSizeException,
BadPaddingException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException {
return decryptByAES(Base64.getDecoder().decode(encrypted), key);
return decryptByAES(Base64Decoder.decode(encrypted), key);
}
// ================================飞机盘Id解密========================================== //
@@ -0,0 +1,87 @@
package cn.qaiu.util;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* Strict Base64 decoding without the HotSpot Base64 intrinsic (CVE-2026-114938).
* Like the JDK's String decoder, this reads ISO-8859-1 bytes.
* Unmappable characters become '?', which is rejected by both alphabets.
*/
public final class Base64Decoder {
private static final byte[] BASIC = alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
private static final byte[] URL_SAFE = alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
private Base64Decoder() {
}
public static byte[] decode(String input) {
return decode(input.getBytes(StandardCharsets.ISO_8859_1), BASIC);
}
public static byte[] decodeUrl(String input) {
return decode(input.getBytes(StandardCharsets.ISO_8859_1), URL_SAFE);
}
private static byte[] decode(byte[] input, byte[] alphabet) {
int length = input.length;
int dataLength = length;
if (dataLength > 0 && input[dataLength - 1] == '=') {
dataLength--;
if (dataLength > 0 && input[dataLength - 1] == '=') {
dataLength--;
}
}
int remainder = dataLength % 4;
int padding = length - dataLength;
if (remainder == 1 || (padding != 0 && remainder + padding != 4)) {
throw new IllegalArgumentException("Invalid Base64 padding or length");
}
int groupEnd = dataLength - remainder;
byte[] decoded = new byte[(groupEnd / 4) * 3 + (remainder == 0 ? 0 : remainder - 1)];
int start = Base64Encoder.useVectors(groupEnd)
? VectorBase64.decode(input, groupEnd, decoded, alphabet == URL_SAFE) : 0;
int outputIndex = start / 4 * 3;
// Each complete group consumes exactly four characters and writes exactly three bytes.
for (int i = start; i < groupEnd; i += 4) {
int a = alphabet[input[i] & 0xff];
int b = alphabet[input[i + 1] & 0xff];
int c = alphabet[input[i + 2] & 0xff];
int d = alphabet[input[i + 3] & 0xff];
if ((a | b | c | d) < 0) {
throw new IllegalArgumentException("Invalid Base64 character");
}
int bits = (a << 18) | (b << 12) | (c << 6) | d;
decoded[outputIndex++] = (byte) (bits >>> 16);
decoded[outputIndex++] = (byte) (bits >>> 8);
decoded[outputIndex++] = (byte) bits;
}
// The two possible tails consume two or three characters and write one or two bytes.
if (remainder != 0) {
int a = alphabet[input[groupEnd] & 0xff];
int b = alphabet[input[groupEnd + 1] & 0xff];
int c = remainder == 3 ? alphabet[input[groupEnd + 2] & 0xff] : 0;
if ((a | b | c) < 0) {
throw new IllegalArgumentException("Invalid Base64 character");
}
decoded[outputIndex] = (byte) ((a << 2) | (b >>> 4));
if (remainder == 3) {
decoded[outputIndex + 1] = (byte) ((b << 4) | (c >>> 2));
}
}
return decoded;
}
private static byte[] alphabet(String characters) {
// Index with an unsigned byte. Every non-alphabet value, including padding, maps to -1.
byte[] table = new byte[256];
Arrays.fill(table, (byte) -1);
for (int i = 0; i < characters.length(); i++) {
table[characters.charAt(i)] = (byte) i;
}
return table;
}
}
@@ -0,0 +1,75 @@
package cn.qaiu.util;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public final class Base64Encoder {
private static final boolean VECTORS = vectorsAvailable();
static final String BASIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static final String URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
private Base64Encoder() {}
private static boolean vectorsAvailable() {
if (java.nio.ByteOrder.nativeOrder() != java.nio.ByteOrder.LITTLE_ENDIAN
|| ModuleLayer.boot().findModule("jdk.incubator.vector").isEmpty()) {
return false;
}
try {
return VectorBase64.available();
} catch (LinkageError unavailableOnThisJdk) {
return false;
}
}
static boolean useVectors(int length) {
return VECTORS && length >= 1024;
}
public static String encode(byte[] data) {
return useVectors(data.length) ? new String(vectorEncode(data, false), StandardCharsets.ISO_8859_1)
: Base64.getEncoder().encodeToString(data);
}
public static byte[] encodeBytes(byte[] data) {
return useVectors(data.length) ? vectorEncode(data, false) : Base64.getEncoder().encode(data);
}
public static String encodeUrlWithoutPadding(byte[] data) {
return useVectors(data.length) ? new String(vectorEncode(data, true), StandardCharsets.ISO_8859_1)
: Base64.getUrlEncoder().withoutPadding().encodeToString(data);
}
private static byte[] vectorEncode(byte[] input, boolean url) {
int remainder = input.length % 3;
int tailLength = remainder + 1;
if (remainder == 0) {
tailLength = 0;
} else if (!url) {
tailLength = 4;
}
long length = (long) (input.length / 3) * 4 + tailLength;
if (length > Integer.MAX_VALUE) {
throw new OutOfMemoryError("Base64 output exceeds maximum array length");
}
byte[] output = new byte[(int) length];
int src = VectorBase64.encode(input, output, url);
int dst = src / 3 * 4;
String alphabet = url ? URL : BASIC;
while (src < input.length) {
int bytes = Math.min(3, input.length - src);
int bits = (input[src++] & 255) << 16;
if (bytes >= 2) {
bits |= (input[src++] & 255) << 8;
}
if (bytes == 3) {
bits |= input[src++] & 255;
}
for (int shift = 18; shift >= 18 - bytes * 6; shift -= 6) {
output[dst++] = (byte) alphabet.charAt((bits >>> shift) & 63);
}
}
java.util.Arrays.fill(output, dst, output.length, (byte) '=');
return output;
}
}
@@ -77,32 +77,55 @@ public class CommonUtils {
}
/**
* urlEncode -> deBase64 -> string
* @param encoded 编码后的字符串
* @return 解码后的字符串
* 解码路径参数中的 Base64。
* <p>优先按 URL-Safe Base64 解;兼容历史「标准 Base64 + URLEncode」以及重复 encode。</p>
*/
public static String urlBase64Decode(String encoded) {
try {
String urlDecoded = java.net.URLDecoder.decode(encoded, StandardCharsets.UTF_8);
byte[] base64DecodedBytes = java.util.Base64.getDecoder().decode(urlDecoded);
return new String(base64DecodedBytes, java.nio.charset.StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException("URL Base64 解码失败", e);
if (encoded == null || encoded.isEmpty()) {
throw new RuntimeException("URL Base64 解码失败: empty");
}
String s = encoded.trim().replace(' ', '+');
// 兼容历史 URLEncode / 误二次 encode:有 % 则解到不再变化
for (int i = 0; i < 3 && s.contains("%"); i++) {
try {
String next = java.net.URLDecoder.decode(s, StandardCharsets.UTF_8);
if (next.equals(s)) {
break;
}
s = next;
} catch (Exception e) {
break;
}
}
Exception last = null;
for (String candidate : new String[]{s, padBase64(s)}) {
try {
return new String(Base64Decoder.decodeUrl(candidate), StandardCharsets.UTF_8);
} catch (Exception e) {
last = e;
}
try {
return new String(Base64Decoder.decode(candidate), StandardCharsets.UTF_8);
} catch (Exception e) {
last = e;
}
}
throw new RuntimeException("URL Base64 解码失败", last);
}
/**
* string -> base64Encode -> urlEncode
* @param str 原始字符串
* @return 编码后的字符串
* 编码为可直接放进 URL path 的 Base64(URL-Safe,无 padding)。
* <p>不再做 URLEncoder,避免前端/代理再 encode 时变成 %253D。</p>
*/
public static String urlBase64Encode(String str) {
try {
byte[] base64EncodedBytes = java.util.Base64.getEncoder().encode(str.getBytes(java.nio.charset.StandardCharsets.UTF_8));
String base64Encoded = new String(base64EncodedBytes, java.nio.charset.StandardCharsets.UTF_8);
return java.net.URLEncoder.encode(base64Encoded, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException("URL Base64 编码失败", e);
return Base64Encoder.encodeUrlWithoutPadding(str.getBytes(StandardCharsets.UTF_8));
}
private static String padBase64(String s) {
int mod = s.length() % 4;
if (mod == 0) {
return s;
}
return s + "====".substring(mod);
}
}
@@ -119,8 +119,18 @@ public class HttpResponseHelper {
};
}
private static boolean looksLikeGzip(Buffer compressed) {
return compressed != null && compressed.length() >= 2
&& (compressed.getByte(0) & 0xff) == 0x1f
&& (compressed.getByte(1) & 0xff) == 0x8b;
}
// -------------------- gzip --------------------
private static String decompressGzip(Buffer compressed) throws IOException {
// Vert.x 可能已解压但仍带 Content-Encoding: gzip,再走 GZIPInputStream 会变成 ZipException
if (!looksLikeGzip(compressed)) {
return compressed.toString(StandardCharsets.UTF_8);
}
try (ByteArrayInputStream bais = new ByteArrayInputStream(compressed.getBytes());
GZIPInputStream gzis = new GZIPInputStream(bais);
InputStreamReader isr = new InputStreamReader(gzis, StandardCharsets.UTF_8);
+362 -37
View File
@@ -101,59 +101,384 @@ public interface JsContent {
""";
String lz = """
/**
* 蓝奏云解析器js签名获取工具
* 蓝奏云解析器 JS 沙箱:伪装 jQuery / document / window。
* 新版页面会用 document.cookie、location.reload、querySelector、
* $('#pwd').val()、.html()、.css() 等,这里做成可链式的最小实现。
* kdns.js 在浏览器里是 `var killdns = true`,需一并注入,否则 kd 会被改成 0。
*/
var signObj;
var __lzPwd = '';
var killdns = true;
function __lzSetPwd(p) {
__lzPwd = p == null ? '' : String(p);
}
function __lzEl(id) {
var nid = String(id == null ? '' : id).replace(/^[#.]/, '');
var el = {
id: nid,
_value: nid === 'pwd' ? __lzPwd : '',
checked: false,
disabled: false,
innerHTML: '',
innerText: '',
textContent: '',
className: '',
style: { display: '', visibility: '', width: '', height: '' },
classList: {
add: function () {},
remove: function () {},
contains: function () { return false; },
toggle: function () {}
},
setAttribute: function () {},
getAttribute: function () { return null; },
removeAttribute: function () {},
addEventListener: function (t, fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
},
removeEventListener: function () {},
appendChild: function (n) { return n; },
removeChild: function (n) { return n; },
insertBefore: function (n) { return n; },
click: function () {},
focus: function () {},
blur: function () {},
submit: function () {},
select: function () {},
reset: function () {}
};
el.parentNode = el;
el.parentElement = el;
el.children = [];
el.childNodes = [];
el.firstChild = null;
el.lastChild = null;
try {
Object.defineProperty(el, 'value', {
get: function () { return nid === 'pwd' ? __lzPwd : el._value; },
set: function (v) {
el._value = v;
if (nid === 'pwd') {
__lzPwd = v == null ? '' : String(v);
}
}
});
} catch (e) {
el.value = el._value;
}
return el;
}
function __lzJq(sel) {
var id = '';
if (typeof sel === 'string') {
id = sel.replace(/^[#.]/, '');
} else if (sel && sel.id) {
id = String(sel.id);
}
var el = (sel && sel.style && sel.addEventListener) ? sel : __lzEl(id);
var api = {
0: el,
length: 1,
selector: sel,
ready: function (fn) {
if (typeof fn === 'function') {
try { fn(jQuery); } catch (e) {}
}
return api;
},
on: function (t, fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
return api;
},
off: function () { return api; },
bind: function (t, fn) { return api.on(t, fn); },
unbind: function () { return api; },
click: function (fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
return api;
},
focus: function (fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
return api;
},
blur: function () { return api; },
keyup: function (fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
return api;
},
keydown: function (fn) { return api.keyup(fn); },
keypress: function (fn) { return api.keyup(fn); },
submit: function (fn) { return api.click(fn); },
change: function (fn) { return api.click(fn); },
hover: function () { return api; },
val: function (v) {
if (arguments.length === 0) {
if (typeof el.value !== 'undefined') {
return el.value;
}
return (id === 'pwd') ? __lzPwd : '';
}
el.value = v;
return api;
},
html: function (v) {
if (arguments.length === 0) {
return el.innerHTML;
}
el.innerHTML = v;
return api;
},
text: function (v) {
if (arguments.length === 0) {
return el.innerText;
}
el.innerText = v;
el.textContent = v;
return api;
},
attr: function (k, v) {
if (arguments.length < 2) {
return null;
}
return api;
},
prop: function (k, v) {
if (arguments.length < 2) {
return false;
}
return api;
},
css: function () { return api; },
addClass: function () { return api; },
removeClass: function () { return api; },
toggleClass: function () { return api; },
hasClass: function () { return false; },
show: function () {
el.style.display = '';
return api;
},
hide: function () {
el.style.display = 'none';
return api;
},
fadeIn: function () { return api; },
fadeOut: function () { return api; },
animate: function () { return api; },
find: function () { return api; },
parent: function () { return api; },
children: function () { return api; },
eq: function () { return api; },
first: function () { return api; },
last: function () { return api; },
each: function (fn) {
if (typeof fn === 'function') {
try { fn.call(el, 0, el); } catch (e) {}
}
return api;
},
append: function () { return api; },
prepend: function () { return api; },
remove: function () { return api; },
empty: function () { return api; },
ajax: function (obj) {
signObj = obj;
return api;
},
get: function () { return el; }
};
return api;
}
var $, jQuery;
$ = jQuery = function () {
return new jQuery.fn.init();
}
$ = jQuery = function (sel) {
if (typeof sel === 'function') {
try { sel(jQuery); } catch (e) {}
return __lzJq(document);
}
return __lzJq(sel);
};
jQuery.fn = jQuery.prototype = {
init: function () {
return {
focus: function (a) {
},
keyup: function(a) {
},
ajax: function (obj) {
signObj = obj
},
val: function(a) {
},
}
},
}
init: function (sel) {
return __lzJq(sel);
}
};
jQuery.fn.init.prototype = jQuery.fn;
$.fn = jQuery.fn;
$.ajax = function (obj) {
signObj = obj
}
signObj = obj;
return {
done: function () { return this; },
fail: function () { return this; },
always: function () { return this; }
};
};
$.get = function () {};
$.post = function () {};
$.extend = function () {
var t = arguments[0] || {};
for (var i = 1; i < arguments.length; i++) {
var s = arguments[i];
if (s) {
for (var k in s) {
if (s.hasOwnProperty(k)) {
t[k] = s[k];
}
}
}
}
return t;
};
$.each = function (obj, fn) {
if (!obj || typeof fn !== 'function') {
return obj;
}
if (typeof obj.length === 'number') {
for (var i = 0; i < obj.length; i++) {
fn.call(obj[i], i, obj[i]);
}
} else {
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
fn.call(obj[k], k, obj[k]);
}
}
}
return obj;
};
$.isFunction = function (f) { return typeof f === 'function'; };
$.isArray = function (a) {
return Object.prototype.toString.call(a) === '[object Array]';
};
$.trim = function (s) {
return s == null ? '' : String(s).replace(/^\\s+|\\s+$/g, '');
};
var __lzLocation = {
href: '',
search: '',
pathname: '/',
hash: '',
host: '',
hostname: '',
protocol: 'https:',
port: '',
origin: '',
assign: function () {},
replace: function () {},
reload: function () {}
};
var document = {
getElementById: function (v) {
return {
value: 'v',
style: {
display: ''
},
addEventListener: function() {}
cookie: '',
title: '',
domain: '',
referrer: '',
readyState: 'complete',
hidden: false,
visibilityState: 'visible',
documentElement: null,
body: null,
head: null,
location: __lzLocation,
getElementById: function (id) { return __lzEl(id); },
getElementsByClassName: function () { return []; },
getElementsByTagName: function (t) {
return t === 'script' ? [] : [__lzEl(t)];
},
getElementsByName: function () { return []; },
querySelector: function (s) { return __lzEl(s); },
querySelectorAll: function (s) { return [__lzEl(s)]; },
createElement: function (t) { return __lzEl(t); },
createTextNode: function (t) { return { nodeValue: t, data: t }; },
createDocumentFragment: function () { return __lzEl('fragment'); },
addEventListener: function (t, fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
},
removeEventListener: function () {},
write: function () {},
writeln: function () {},
open: function () {},
close: function () {}
};
document.documentElement = __lzEl('html');
document.body = __lzEl('body');
document.head = __lzEl('head');
var navigator = {
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
platform: 'Win32',
language: 'zh-CN',
cookieEnabled: true,
onLine: true
};
var location = __lzLocation;
var console = {
log: function () {},
warn: function () {},
error: function () {},
info: function () {},
debug: function () {}
};
function setTimeout(fn, delay) {
if (typeof fn === 'function' && (!delay || delay <= 0)) {
try { fn(); } catch (e) {}
}
return 0;
}
var window = {location: {}}
function setInterval() { return 0; }
function clearTimeout() {}
function clearInterval() {}
var window = {
location: __lzLocation,
document: document,
navigator: navigator,
console: console,
innerWidth: 1920,
innerHeight: 1080,
setTimeout: setTimeout,
setInterval: setInterval,
clearTimeout: clearTimeout,
clearInterval: clearInterval,
addEventListener: function (t, fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
},
removeEventListener: function () {},
atob: function (s) { return s; },
btoa: function (s) { return s; }
};
window.window = window;
window.top = window;
window.self = window;
window.parent = window;
window.jQuery = jQuery;
window.$ = $;
var top = window;
var self = window;
var parent = window;
""";
String kwSignString = """
@@ -50,21 +50,47 @@ public class JsExecUtils {
*/
public static ScriptObjectMirror executeDynamicJs(String jsText, String funName) throws ScriptException,
NoSuchMethodException {
ScriptEngine engine = ENGINE_MANAGER.getEngineByName("JavaScript"); // 得到脚本引擎
return executeDynamicJs(jsText, funName, null);
}
/**
* @param pwd 分享密码,写入伪 DOM(#pwd / getElementById('pwd')),供新版页面取值
*/
public static ScriptObjectMirror executeDynamicJs(String jsText, String funName, String pwd) throws ScriptException,
NoSuchMethodException {
ScriptEngine engine = ENGINE_MANAGER.getEngineByName("JavaScript");
try {
engine.eval(JsContent.lz + "\n" + jsText);
engine.eval(JsContent.lz);
Invocable inv = (Invocable) engine;
//调用js中的函数
if (StringUtils.isNotEmpty(funName)) {
inv.invokeFunction(funName);
if (pwd != null) {
inv.invokeFunction("__lzSetPwd", pwd);
}
return (ScriptObjectMirror) engine.get("signObj");
try {
engine.eval(jsText);
if (StringUtils.isNotEmpty(funName)) {
inv.invokeFunction(funName);
}
} catch (ScriptException | NoSuchMethodException | RuntimeException e) {
ScriptObjectMirror captured = asSignObj(engine.get("signObj"));
if (captured != null) {
return captured;
}
throw e;
}
return asSignObj(engine.get("signObj"));
} finally {
// 清理引擎持有的引用,帮助 GC 回收
clearEngineBindings(engine);
}
}
private static ScriptObjectMirror asSignObj(Object sign) {
if (sign instanceof ScriptObjectMirror mirror
&& (mirror.get("url") != null || mirror.get("data") != null)) {
return mirror;
}
return null;
}
/**
* 调用执行js文件(使用缓存的 ScriptEngineManager 创建新引擎实例)
@@ -0,0 +1,49 @@
package cn.qaiu.util;
import io.vertx.core.MultiMap;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Map;
/**
* 夸克 / UC 账号缓存范围。只产出不可逆短指纹,不包含 Cookie 原文。
* 有 {@code _configId} 时按配置隔离;否则按过滤后的会话 Cookie 隔离。
*/
public final class QuarkAccountScope {
private QuarkAccountScope() {
}
/**
* @return 可放进缓存 key 的短指纹;没有账号时返回 null,调用方继续使用分享级缓存
*/
public static String suffix(Map<String, Object> otherParam) {
if (otherParam == null || !(otherParam.get("auths") instanceof MultiMap auths)) {
return null;
}
String configId = auths.get("_configId");
if (configId != null && !configId.isBlank()) {
return "cfg-" + digest(configId.trim());
}
String cookie = CookieUtils.filterUcQuarkCookie(auths.get("cookie"));
if (cookie == null || cookie.isBlank()) {
return null;
}
return "ck-" + digest(cookie);
}
private static String digest(String value) {
try {
byte[] hash = MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(StandardCharsets.UTF_8));
StringBuilder out = new StringBuilder(16);
for (int i = 0; i < 8; i++) {
out.append(String.format("%02x", hash[i]));
}
return out.toString();
} catch (Exception e) {
return Integer.toHexString(value.hashCode());
}
}
}
@@ -0,0 +1,125 @@
package cn.qaiu.util;
import jdk.incubator.vector.ByteVector;
import jdk.incubator.vector.IntVector;
import jdk.incubator.vector.VectorMask;
import jdk.incubator.vector.VectorShuffle;
import jdk.incubator.vector.VectorSpecies;
import static jdk.incubator.vector.VectorOperators.*;
final class VectorBase64 {
private static final VectorSpecies<Byte> SPECIES = ByteVector.SPECIES_PREFERRED;
private static final int WIDTH = SPECIES.length();
private static final int PACKED = WIDTH / 4 * 3;
private static final VectorMask<Byte> PACKED_MASK = SPECIES.indexInRange(0, PACKED);
// Each four-byte lane holds one quartet. Pack or expand its three binary bytes.
private static final VectorShuffle<Byte> PACK = VectorShuffle.fromOp(SPECIES,
i -> i < PACKED ? i / 3 * 4 + i % 3 : 0);
private static final VectorShuffle<Byte> EXPAND = VectorShuffle.fromOp(SPECIES,
i -> i / 4 * 3 + Math.min(i % 4, 2));
// Each low-nibble entry is a bit set of allowed high nibbles.
private static final class Alphabet {
final ByteVector lowMasks;
final ByteVector highMasks;
final ByteVector offsets;
final byte last;
final ByteVector encodeTable;
Alphabet(String letters) {
byte[] low = new byte[Math.max(WIDTH, 16)];
byte[] high = new byte[low.length];
byte[] offset = new byte[low.length];
byte[] chars = new byte[WIDTH];
if (WIDTH >= 64) {
for (int i = 0; i < 64; i++) {
chars[i] = (byte) letters.charAt(i);
}
}
encodeTable = ByteVector.fromArray(SPECIES, chars, 0);
last = (byte) letters.charAt(63);
for (int i = 0; i < letters.length(); i++) {
int ch = letters.charAt(i);
int bucket = ch >>> 4;
byte bit = (byte) (1 << bucket);
high[bucket] = bit;
low[ch & 15] |= bit;
if (ch != last) {
offset[bucket] = (byte) (i - ch);
}
}
lowMasks = ByteVector.fromArray(SPECIES, low, 0);
highMasks = ByteVector.fromArray(SPECIES, high, 0);
offsets = ByteVector.fromArray(SPECIES, offset, 0);
}
}
private static final Alphabet BASIC = new Alphabet(Base64Encoder.BASIC);
private static final Alphabet URL = new Alphabet(Base64Encoder.URL);
private VectorBase64() {}
static boolean available() {
if (WIDTH < 16) {
return false;
}
// Incubator APIs can change between JDK releases. Link both kernels before enabling them.
byte[] plain = new byte[PACKED];
byte[] encoded = new byte[WIDTH];
byte[] decoded = new byte[PACKED];
plain[0] = (byte) 0xfb;
encode(plain, encoded, true);
decode(encoded, WIDTH, decoded, true);
return encoded[0] == '-' && java.util.Arrays.equals(plain, decoded);
}
static int decode(byte[] input, int groupEnd, byte[] output, boolean url) {
Alphabet alphabet = url ? URL : BASIC;
int limit = SPECIES.loopBound(groupEnd);
int dst = 0;
for (int src = 0; src < limit; src += WIDTH) {
ByteVector ascii = ByteVector.fromArray(SPECIES, input, src);
ByteVector high = ascii.lanewise(LSHR, 4);
ByteVector low = ascii.and((byte) 15);
// The low-nibble table records which high nibbles form legal characters.
if (high.selectFrom(alphabet.highMasks).and(low.selectFrom(alphabet.lowMasks)).eq((byte) 0).anyTrue()) {
throw new IllegalArgumentException("Invalid Base64 character");
}
ByteVector values = ascii.add(high.selectFrom(alphabet.offsets)).blend((byte) 63, ascii.eq(alphabet.last));
// [a,b,c,d] -> [(a<<2)|(b>>4), (b<<4)|(c>>2), (c<<6)|d, unused].
IntVector w = values.reinterpretAsInts();
IntVector bytes = w.lanewise(LSHL, 2).and(0xfc).or(w.lanewise(LSHR, 12).and(3))
.or(w.lanewise(LSHL, 4).and(0xf000)).or(w.lanewise(LSHR, 10).and(0x0f00))
.or(w.lanewise(LSHL, 6).and(0xc00000)).or(w.lanewise(LSHR, 8).and(0x3f0000));
bytes.reinterpretAsBytes().rearrange(PACK).intoArray(output, dst, PACKED_MASK);
dst += PACKED;
}
return limit;
}
static int encode(byte[] input, byte[] output, boolean url) {
int limit = input.length / PACKED * PACKED;
int dst = 0;
for (int src = 0; src < limit; src += PACKED) {
IntVector w = ByteVector.fromArray(SPECIES, input, src, PACKED_MASK)
.rearrange(EXPAND).reinterpretAsInts();
// Undo the quartet packing, extracting four six-bit indices per lane.
IntVector indices = w.lanewise(LSHR, 2).and(63)
.or(w.lanewise(LSHL, 12).and(0x3000)).or(w.lanewise(LSHR, 4).and(0x0f00))
.or(w.lanewise(LSHL, 10).and(0x3c0000)).or(w.lanewise(LSHR, 6).and(0x030000))
.or(w.lanewise(LSHL, 8).and(0x3f000000));
ByteVector v = indices.reinterpretAsBytes();
if (WIDTH >= 64) {
v.selectFrom((url ? URL : BASIC).encodeTable).intoArray(output, dst);
} else {
v.add((byte) 'A').blend(v.add((byte) ('a' - 26)), v.compare(GE, (byte) 26))
.blend(v.add((byte) ('0' - 52)), v.compare(GE, (byte) 52))
.blend((byte) (url ? '-' : '+'), v.eq((byte) 62))
.blend((byte) (url ? '_' : '/'), v.eq((byte) 63)).intoArray(output, dst);
}
dst += WIDTH;
}
return limit;
}
}
@@ -0,0 +1,88 @@
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 hashIndex = key.indexOf('#');
if (hashIndex >= 0) {
key = key.substring(0, hashIndex);
}
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;
}
}
@@ -7,50 +7,7 @@
// 全局类型定义,使用JSDoc注释
// 这些类型定义将在VSCode中提供代码补全和类型检查
// ============================================================================
// Nashorn Java 互操作全局对象
// ============================================================================
/**
* Java 全局对象类型定义 (Nashorn引擎提供)
* 用于访问Java类型和进行Java互操作
* @typedef {Object} JavaGlobal
* @property {function(string): any} type - 获取Java类,参数为完整类名(如"java.util.zip.CRC32")
* @property {function(any): any} from - 将Java对象转换为JavaScript对象
* @property {function(any): any} to - 将JavaScript对象转换为Java对象
* @property {function(any): boolean} isType - 检查对象是否为指定Java类型
* @property {function(any): boolean} isJavaObject - 检查对象是否为Java对象
* @property {function(any): boolean} isJavaMethod - 检查对象是否为Java方法
* @property {function(any): boolean} isJavaFunction - 检查对象是否为Java函数
*/
/**
* Java 全局对象 (Nashorn引擎提供)
* @global
* @type {JavaGlobal}
*/
var Java;
/**
* java 命名空间对象类型定义 (Nashorn引擎提供)
* 用于直接访问Java包和类
* @typedef {Object} JavaNamespace
* @property {Object} lang - java.lang 包
* @property {Object} util - java.util 包
* @property {Object} io - java.io 包
* @property {Object} net - java.net 包
* @property {Object} math - java.math 包
* @property {Object} security - java.security 包
* @property {Object} text - java.text 包
* @property {Object} time - java.time 包
*/
/**
* java 命名空间对象 (Nashorn引擎提供)
* @global
* @type {JavaNamespace}
*/
var java;
// 解析脚本通过项目注入的接口访问分享信息、HTTP 和日志。
/**
* @typedef {Object} ShareLinkInfo
+362 -29
View File
@@ -1,46 +1,379 @@
/**
* 蓝奏云解析器js签名获取工具
* 蓝奏云解析器 JS 沙箱:伪装 jQuery / document / window。
* 新版页面会用 document.cookie、location.reload、querySelector、
* $('#pwd').val()、.html()、.css() 等,这里做成可链式的最小实现。
* kdns.js 在浏览器里是 `var killdns = true`,需一并注入,否则 kd 会被改成 0。
*/
var signObj;
var __lzPwd = '';
var killdns = true;
function __lzSetPwd(p) {
__lzPwd = p == null ? '' : String(p);
}
function __lzEl(id) {
var nid = String(id == null ? '' : id).replace(/^[#.]/, '');
var el = {
id: nid,
_value: nid === 'pwd' ? __lzPwd : '',
checked: false,
disabled: false,
innerHTML: '',
innerText: '',
textContent: '',
className: '',
style: { display: '', visibility: '', width: '', height: '' },
classList: {
add: function () {},
remove: function () {},
contains: function () { return false; },
toggle: function () {}
},
setAttribute: function () {},
getAttribute: function () { return null; },
removeAttribute: function () {},
addEventListener: function (t, fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
},
removeEventListener: function () {},
appendChild: function (n) { return n; },
removeChild: function (n) { return n; },
insertBefore: function (n) { return n; },
click: function () {},
focus: function () {},
blur: function () {},
submit: function () {},
select: function () {},
reset: function () {}
};
el.parentNode = el;
el.parentElement = el;
el.children = [];
el.childNodes = [];
el.firstChild = null;
el.lastChild = null;
try {
Object.defineProperty(el, 'value', {
get: function () { return nid === 'pwd' ? __lzPwd : el._value; },
set: function (v) {
el._value = v;
if (nid === 'pwd') {
__lzPwd = v == null ? '' : String(v);
}
}
});
} catch (e) {
el.value = el._value;
}
return el;
}
function __lzJq(sel) {
var id = '';
if (typeof sel === 'string') {
id = sel.replace(/^[#.]/, '');
} else if (sel && sel.id) {
id = String(sel.id);
}
var el = (sel && sel.style && sel.addEventListener) ? sel : __lzEl(id);
var api = {
0: el,
length: 1,
selector: sel,
ready: function (fn) {
if (typeof fn === 'function') {
try { fn(jQuery); } catch (e) {}
}
return api;
},
on: function (t, fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
return api;
},
off: function () { return api; },
bind: function (t, fn) { return api.on(t, fn); },
unbind: function () { return api; },
click: function (fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
return api;
},
focus: function (fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
return api;
},
blur: function () { return api; },
keyup: function (fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
return api;
},
keydown: function (fn) { return api.keyup(fn); },
keypress: function (fn) { return api.keyup(fn); },
submit: function (fn) { return api.click(fn); },
change: function (fn) { return api.click(fn); },
hover: function () { return api; },
val: function (v) {
if (arguments.length === 0) {
if (typeof el.value !== 'undefined') {
return el.value;
}
return (id === 'pwd') ? __lzPwd : '';
}
el.value = v;
return api;
},
html: function (v) {
if (arguments.length === 0) {
return el.innerHTML;
}
el.innerHTML = v;
return api;
},
text: function (v) {
if (arguments.length === 0) {
return el.innerText;
}
el.innerText = v;
el.textContent = v;
return api;
},
attr: function (k, v) {
if (arguments.length < 2) {
return null;
}
return api;
},
prop: function (k, v) {
if (arguments.length < 2) {
return false;
}
return api;
},
css: function () { return api; },
addClass: function () { return api; },
removeClass: function () { return api; },
toggleClass: function () { return api; },
hasClass: function () { return false; },
show: function () {
el.style.display = '';
return api;
},
hide: function () {
el.style.display = 'none';
return api;
},
fadeIn: function () { return api; },
fadeOut: function () { return api; },
animate: function () { return api; },
find: function () { return api; },
parent: function () { return api; },
children: function () { return api; },
eq: function () { return api; },
first: function () { return api; },
last: function () { return api; },
each: function (fn) {
if (typeof fn === 'function') {
try { fn.call(el, 0, el); } catch (e) {}
}
return api;
},
append: function () { return api; },
prepend: function () { return api; },
remove: function () { return api; },
empty: function () { return api; },
ajax: function (obj) {
signObj = obj;
return api;
},
get: function () { return el; }
};
return api;
}
var $, jQuery;
$ = jQuery = function () {
return new jQuery.fn.init();
}
$ = jQuery = function (sel) {
if (typeof sel === 'function') {
try { sel(jQuery); } catch (e) {}
return __lzJq(document);
}
return __lzJq(sel);
};
jQuery.fn = jQuery.prototype = {
init: function () {
return {
focus: function (a) {
},
keyup: function(a) {
},
ajax: function (obj) {
signObj = obj
}
}
},
}
init: function (sel) {
return __lzJq(sel);
}
};
jQuery.fn.init.prototype = jQuery.fn;
$.fn = jQuery.fn;
// 伪装jquery.ajax函数获取关键数据
$.ajax = function (obj) {
signObj = obj
}
signObj = obj;
return {
done: function () { return this; },
fail: function () { return this; },
always: function () { return this; }
};
};
$.get = function () {};
$.post = function () {};
$.extend = function () {
var t = arguments[0] || {};
for (var i = 1; i < arguments.length; i++) {
var s = arguments[i];
if (s) {
for (var k in s) {
if (s.hasOwnProperty(k)) {
t[k] = s[k];
}
}
}
}
return t;
};
$.each = function (obj, fn) {
if (!obj || typeof fn !== 'function') {
return obj;
}
if (typeof obj.length === 'number') {
for (var i = 0; i < obj.length; i++) {
fn.call(obj[i], i, obj[i]);
}
} else {
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
fn.call(obj[k], k, obj[k]);
}
}
}
return obj;
};
$.isFunction = function (f) { return typeof f === 'function'; };
$.isArray = function (a) {
return Object.prototype.toString.call(a) === '[object Array]';
};
$.trim = function (s) {
return s == null ? '' : String(s).replace(/^\s+|\s+$/g, '');
};
var __lzLocation = {
href: '',
search: '',
pathname: '/',
hash: '',
host: '',
hostname: '',
protocol: 'https:',
port: '',
origin: '',
assign: function () {},
replace: function () {},
reload: function () {}
};
var document = {
getElementById: function (v) {
return {
value: 'v'
cookie: '',
title: '',
domain: '',
referrer: '',
readyState: 'complete',
hidden: false,
visibilityState: 'visible',
documentElement: null,
body: null,
head: null,
location: __lzLocation,
getElementById: function (id) { return __lzEl(id); },
getElementsByClassName: function () { return []; },
getElementsByTagName: function (t) {
return t === 'script' ? [] : [__lzEl(t)];
},
getElementsByName: function () { return []; },
querySelector: function (s) { return __lzEl(s); },
querySelectorAll: function (s) { return [__lzEl(s)]; },
createElement: function (t) { return __lzEl(t); },
createTextNode: function (t) { return { nodeValue: t, data: t }; },
createDocumentFragment: function () { return __lzEl('fragment'); },
addEventListener: function (t, fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
},
removeEventListener: function () {},
write: function () {},
writeln: function () {},
open: function () {},
close: function () {}
};
document.documentElement = __lzEl('html');
document.body = __lzEl('body');
document.head = __lzEl('head');
var navigator = {
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
platform: 'Win32',
language: 'zh-CN',
cookieEnabled: true,
onLine: true
};
var location = __lzLocation;
var console = {
log: function () {},
warn: function () {},
error: function () {},
info: function () {},
debug: function () {}
};
function setTimeout(fn, delay) {
if (typeof fn === 'function' && (!delay || delay <= 0)) {
try { fn(); } catch (e) {}
}
return 0;
}
function setInterval() { return 0; }
function clearTimeout() {}
function clearInterval() {}
var window = {
location: __lzLocation,
document: document,
navigator: navigator,
console: console,
innerWidth: 1920,
innerHeight: 1080,
setTimeout: setTimeout,
setInterval: setInterval,
clearTimeout: clearTimeout,
clearInterval: clearInterval,
addEventListener: function (t, fn) {
if (typeof fn === 'function') {
try { fn(); } catch (e) {}
}
},
removeEventListener: function () {},
atob: function (s) { return s; },
btoa: function (s) { return s; }
};
window.window = window;
window.top = window;
window.self = window;
window.parent = window;
window.jQuery = jQuery;
window.$ = $;
var top = window;
var self = window;
var parent = window;
+50 -6
View File
@@ -55,8 +55,50 @@ def encode123(url, way, version, timestamp):
# 返回加密后的URL参数
return f"?{y}={time_long}-{a}-{final_crc}"
# 与 parser PasswordLoginRisk 保持一致:验证码/风控只提示改用 Authorization,不求解、不重试。
_RISK_KEYWORDS = (
"验证码", "风控", "安全风险", "安全验证", "安全校验", "滑块", "滑动验证",
"拼图验证", "短信验证", "微信登录", "微信进行登录", "境外登录", "需要验证", "请验证",
"请你验证", "进行验证", "完成验证", "二次验证", "人机验证", "操作频繁", "请求过于频繁",
"请求频繁", "captcha", "recaptcha", "risk control",
)
_AUTH_HINT = (
"账号密码登录触发了验证码/风控,已停止用户名密码登录(不会尝试验证码)。"
"请改为配置 Authorization(浏览器登录后的 Bearer token / JWT,"
"例如 localStorage 的 authorToken、请求头 authorization 或 Cookie 的 sso-token)。"
"静态配置写在 app-dev.yml 的 auths.ye.authorization(与 auths.ye.token 等价);"
"临时请求使用 authType=authorization 或 authType=accesstoken,token 填该令牌(不要重复带 Bearer 前缀)。"
"说明见 parser/doc/auth-param/。"
)
def format_login_failure(result):
"""把 123 登录失败响应转成用户可见说明。"""
if not isinstance(result, dict):
return "登录失败"
message = result.get("message") or result.get("msg") or ""
data = result.get("data") if isinstance(result.get("data"), dict) else {}
data_message = data.get("message") or data.get("msg") or ""
blob = f"{message} {data_message}".lower()
risk_field = any(
key.lower().find(flag) >= 0 and data.get(key) not in (None, False, 0, "", "false", "0")
for key in data
for flag in ("captcha", "vcode", "risk", "needverify", "need_verify", "slideverify", "verifycode", "verify_code")
)
if risk_field or any(keyword.lower() in blob for keyword in _RISK_KEYWORDS):
code = result.get("code")
upstream = message or data_message
extra = f"code={code}" if code is not None else ""
if upstream:
extra = f"{extra}, message={upstream}" if extra else f"message={upstream}"
return f"{_AUTH_HINT} 上游返回:{extra}" if extra else _AUTH_HINT
if result.get("code") == 200:
return "未获取到token"
return f"登录失败: {message}" if message else "登录失败"
def login_123pan(username, password):
"""登录123盘获取token"""
"""登录123盘获取token。成功返回 token,失败返回 None(错误已打印)。"""
print(f"🔐 正在登录账号: {username}")
login_data = {
@@ -73,16 +115,18 @@ def login_123pan(username, password):
)
result = response.json()
if result.get('code') == 200:
if result.get('code') == 200 and result.get('data', {}).get('token'):
token = result.get('data', {}).get('token', '')
print(f"✅ 登录成功!")
return token
else:
error_msg = result.get('message', '未知错误')
print(f"❌ 登录失败: {error_msg}")
error_msg = format_login_failure(result)
login_123pan.last_error = error_msg
print(f"❌ {error_msg}")
return None
except Exception as e:
print(f"❌ 登录请求失败: {e}")
login_123pan.last_error = f"登录请求失败: {e}"
print(f"❌ {login_123pan.last_error}")
return None
def get_share_info(share_key, password=''):
@@ -189,7 +233,7 @@ def start(link, password='', username='', user_password=''):
if not token:
return {
"code": 201,
"message": "登录失败"
"message": getattr(login_123pan, "last_error", None) or "登录失败"
}
else:
print("⚠️ 未提供登录信息,某些文件可能无法下载")
@@ -0,0 +1,44 @@
package cn.qaiu.parser;
import org.junit.Test;
import java.io.IOException;
import java.net.URL;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* GHSA-997r-7xx2-p9x6 regression: Cloudreve generic parser must reject
* hosts that resolve to loopback / private / link-local / metadata ranges
* before any outbound request.
*/
public class AssertPublicHostTest {
@Test
public void rejectsLoopbackAndPrivateHosts() throws Exception {
String[] blocked = {
"http://127.0.0.1.nip.io/s/poc",
"http://localhost/s/poc",
"http://10.0.0.1/s/poc",
"http://192.168.1.1/s/poc",
"http://172.16.0.1/s/poc",
"http://169.254.169.254/s/poc",
"http://[::1]/s/poc"
};
for (String raw : blocked) {
try {
PanBase.assertPublicHost(new URL(raw));
fail("expected block for " + raw);
} catch (IOException expected) {
assertTrue(expected.getMessage().contains("不允许访问")
|| expected.getMessage().contains("无法解析"));
}
}
}
@Test
public void allowsPublicHost() throws Exception {
PanBase.assertPublicHost(new URL("https://example.com/s/demo"));
}
}
@@ -0,0 +1,79 @@
package cn.qaiu.parser;
import cn.qaiu.entity.ShareLinkInfo;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class FolderPagingTest {
@Test
public void blankPageKeepsLegacyBehaviour() {
assertNull(FolderPaging.parsePage(null));
assertNull(FolderPaging.parsePage(" "));
assertEquals(1, FolderPaging.pageOrFirst(info()));
assertNull(FolderPaging.requestedPage(info()));
}
@Test
public void invalidPagesAreRejected() {
assertEquals(Integer.valueOf(3), FolderPaging.parsePage(" 3 "));
assertThrows(IllegalArgumentException.class, () -> FolderPaging.parsePage("0"));
assertThrows(IllegalArgumentException.class, () -> FolderPaging.parsePage("-1"));
assertThrows(IllegalArgumentException.class, () -> FolderPaging.parsePage("abc"));
assertThrows(IllegalArgumentException.class, () -> FolderPaging.parsePage(String.valueOf(FolderPaging.MAX_PAGE + 1)));
}
@Test
public void onlyLzFjIzArePaged() {
assertTrue(FolderPaging.supports("lz"));
assertTrue(FolderPaging.supports("FJ"));
assertTrue(FolderPaging.supports("iz"));
assertFalse(FolderPaging.supports("qk"));
assertFalse(FolderPaging.supports(null));
}
@Test
public void emptyPageAlwaysEnds() {
assertFalse(FolderPaging.hasMore(2, 0, 60, 9));
assertFalse(FolderPaging.hasMore(1, 0, 50, null));
}
@Test
public void totalPageWinsOverFullPageHeuristic() {
assertFalse(FolderPaging.hasMore(2, 60, 60, 2));
assertTrue(FolderPaging.hasMore(1, 5, 60, 2));
assertTrue(FolderPaging.hasMore(1, 50, 50, null));
assertFalse(FolderPaging.hasMore(1, 49, 50, null));
assertTrue(FolderPaging.hasMore(1, 50, 50, 0));
}
@Test
public void offsetListPageReadsTotals() {
ShareLinkInfo info = info();
info.getOtherParam().put(FolderPaging.PAGE, 2);
JsonObject resp = new JsonObject().put("total", "121").put("totalPage", 3).put("offset", 2).put("limit", 60);
JsonObject page = FolderPaging.offsetListPage(info, resp, 60, 60);
assertEquals(Integer.valueOf(121), page.getInteger("total"));
assertEquals(Integer.valueOf(3), page.getInteger("totalPage"));
assertTrue(page.getBoolean("hasMore"));
assertEquals(Integer.valueOf(3), page.getInteger("nextPage"));
assertEquals(page, FolderPaging.pageInfo(info));
}
@Test
public void noMoreClearsNextPageAndCursor() {
JsonObject page = FolderPaging.pageInfo(info(), 4, 50, false, null, null, "cursor");
assertNull(page.getValue("nextPage"));
assertNull(page.getValue("nextCursor"));
}
private static ShareLinkInfo info() {
return ShareLinkInfo.newBuilder().type("lz").shareKey("b1").build();
}
}
@@ -1,6 +1,7 @@
package cn.qaiu.parser;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.util.YeShareHostUtil;
import org.junit.Test;
import java.util.Arrays;
@@ -157,6 +158,43 @@ 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 shareUrl = yePattern.matcher("https://1815268665.share.123pan.cn/123pan/iaKtVv-r4aCd");
assertTrue("YE should match uid.share.123pan.cn URL", shareUrl.find());
assertEquals("iaKtVv-r4aCd", shareUrl.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"));
Matcher hashUrl = yePattern.matcher("https://www.123pan.com/s/lN7UVv-pbYJ#/list/share");
assertTrue("YE should match URL with hash fragment", hashUrl.matches());
assertEquals("lN7UVv-pbYJ", hashUrl.group("KEY"));
String fakeQuery = "ref" + "=" + "example";
Matcher yunUrl = yePattern.matcher("https://yun.123pan.com/s/lN7UVv-pbYJ?" + fakeQuery);
assertTrue("YE should match yun.123pan.com", yunUrl.matches());
assertEquals("lN7UVv-pbYJ", yunUrl.group("KEY"));
assertEquals("lN7UVv-pbYJ", YeShareHostUtil.normalizeShareKey("lN7UVv-pbYJ#/list/share"));
assertEquals("lN7UVv-pbYJ", YeShareHostUtil.normalizeShareKey(
"https://yun.123pan.com/s/lN7UVv-pbYJ?" + fakeQuery + "#/list"));
}
@Test
public void testLePatternFix() {
Pattern lePattern = PanDomainTemplate.LE.getPattern();
@@ -302,6 +340,63 @@ public class PanDomainTemplateTest {
fsPattern.matcher("https://xxx.feishu.cn/docs/abc123").matches());
}
@Test
public void testYsPatternMatching() {
Pattern ysPattern = PanDomainTemplate.YS.getPattern();
// 主域名
Matcher m1 = ysPattern.matcher("https://qaiu.ysepan.com/");
assertTrue("YS should match ysepan.com", m1.matches());
assertEquals("qaiu", m1.group("KEY"));
Matcher m2 = ysPattern.matcher("http://sohehe4.ys168.com");
assertTrue("YS should match ys168.com", m2.matches());
assertEquals("sohehe4", m2.group("KEY"));
// 备用域名
Matcher m3 = ysPattern.matcher("https://demo.cccpan.com/");
assertTrue("YS should match cccpan.com", m3.matches());
assertEquals("demo", m3.group("KEY"));
Matcher m4 = ysPattern.matcher("https://space.ysupan.com");
assertTrue("YS should match ysupan.com", m4.matches());
assertEquals("space", m4.group("KEY"));
Matcher m5 = ysPattern.matcher("https://user.uupan.net/");
assertTrue("YS should match uupan.net", m5.matches());
assertEquals("user", m5.group("KEY"));
Matcher m6 = ysPattern.matcher("https://ok.ysok.net");
assertTrue("YS should match ysok.net", m6.matches());
assertEquals("ok", m6.group("KEY"));
// 非空间子域 / 非白名单域名
assertFalse("YS should NOT match www.ysepan.com",
ysPattern.matcher("https://www.ysepan.com/").matches());
assertFalse("YS should NOT match api host c6.ysepan.com",
ysPattern.matcher("https://c6.ysepan.com/api/ml/mldq").matches());
assertFalse("YS should NOT match CDN ys-c.ysepan.com",
ysPattern.matcher("https://ys-c.ysepan.com/wap/qaiu/x").matches());
assertFalse("YS should NOT match unrelated domain",
ysPattern.matcher("https://qaiu.evil.com/").matches());
assertFalse("YS should NOT match ysepan.com without space subdomain",
ysPattern.matcher("https://ysepan.com/").matches());
}
@Test
public void testYsFromShareUrl() {
ParserCreate parserCreate = ParserCreate.fromShareUrl("https://qaiu.ysepan.com/");
ShareLinkInfo info = parserCreate.getShareLinkInfo();
assertNotNull(info);
assertEquals("ys", info.getType());
assertEquals("永硕E盘", info.getPanName());
assertEquals("qaiu", info.getShareKey());
ParserCreate backup = ParserCreate.fromShareUrl("https://demo.cccpan.com/");
assertEquals("ys", backup.getShareLinkInfo().getType());
assertEquals("demo", backup.getShareLinkInfo().getShareKey());
}
@Test
public void testFsFromShareUrl() {
// 测试文件链接解析
@@ -0,0 +1,115 @@
package cn.qaiu.parser;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PasswordLoginRiskTest {
@Test
public void securityRiskMessageGuidesAuthorization() {
JsonObject body = new JsonObject()
.put("code", 401)
.put("message", "当前账号存在安全风险,请使用短信验证码或者微信进行登录。");
assertTrue(PasswordLoginRisk.indicatesCaptchaOrRisk(body));
String message = PasswordLoginRisk.describeLoginFailure(body);
assertTrue(message.startsWith(PasswordLoginRisk.AUTHORIZATION_HINT));
assertTrue(message.contains("验证码/风控"));
assertTrue(message.contains("auths.ye.authorization"));
assertTrue(message.contains("authType=authorization"));
assertTrue(message.contains("authType=accesstoken"));
assertTrue(message.contains("code=401"));
assertTrue(message.contains("当前账号存在安全风险"));
assertFalse(message.startsWith("登录失败:"));
}
@Test
public void overseasRiskAndCaptchaPhrasesMatch() {
assertRisk("当前账号存在境外登录风险,请使用短信验证码或者微信进行登录。");
assertRisk("请完成安全验证");
assertRisk("请进行滑块验证");
assertRisk("操作频繁,请稍后再试");
assertRisk("captcha required");
}
@Test
public void wrongPasswordStaysDistinct() {
JsonObject body = new JsonObject()
.put("code", 500)
.put("message", "用户名或密码错误");
assertFalse(PasswordLoginRisk.indicatesCaptchaOrRisk(body));
assertEquals("登录失败: 用户名或密码错误", PasswordLoginRisk.describeLoginFailure(body));
JsonObject account = new JsonObject().put("code", 1).put("msg", "账号或密码错误");
assertFalse(PasswordLoginRisk.indicatesCaptchaOrRisk(account));
assertEquals("登录失败: 账号或密码错误", PasswordLoginRisk.describeLoginFailure(account));
}
@Test
public void riskFieldWithoutKeywordStillHints() {
JsonObject body = new JsonObject()
.put("code", 200)
.put("message", "ok")
.put("data", new JsonObject().put("needCaptcha", true));
assertFalse(PasswordLoginRisk.isLoginSuccess(body));
assertTrue(PasswordLoginRisk.indicatesCaptchaOrRisk(body));
assertTrue(PasswordLoginRisk.describeLoginFailure(body).contains("Authorization"));
}
@Test
public void falseCaptchaFlagDoesNotHint() {
JsonObject body = new JsonObject()
.put("code", 500)
.put("message", "用户名或密码错误")
.put("data", new JsonObject().put("needCaptcha", false));
assertFalse(PasswordLoginRisk.indicatesCaptchaOrRisk(body));
assertEquals("登录失败: 用户名或密码错误", PasswordLoginRisk.describeLoginFailure(body));
}
@Test
public void successTokenIsNotTreatedAsFailure() {
JsonObject body = new JsonObject()
.put("code", 200)
.put("message", "ok")
.put("data", new JsonObject().put("token", "jwt-token"));
assertTrue(PasswordLoginRisk.isLoginSuccess(body));
}
@Test
public void blankTokenWithoutRiskKeepsMissingTokenMessage() {
JsonObject body = new JsonObject()
.put("code", 200)
.put("message", "ok")
.put("data", new JsonObject().put("token", ""));
assertFalse(PasswordLoginRisk.isLoginSuccess(body));
assertEquals("未获取到token", PasswordLoginRisk.describeLoginFailure(body));
}
@Test
public void nonJsonCaptchaBodyUsesHint() {
String body = "<html>请完成滑块验证</html>";
String message = PasswordLoginRisk.nonJsonLoginFailure(body);
assertTrue(message.startsWith(PasswordLoginRisk.AUTHORIZATION_HINT));
}
@Test
public void nonJsonWrongPasswordStaysFormatError() {
assertEquals("登录响应格式异常: 用户名或密码错误",
PasswordLoginRisk.nonJsonLoginFailure("用户名或密码错误"));
}
private static void assertRisk(String message) {
JsonObject body = new JsonObject().put("code", 5202).put("message", message);
assertTrue(message, PasswordLoginRisk.indicatesCaptchaOrRisk(body));
assertTrue(PasswordLoginRisk.describeLoginFailure(body).startsWith(PasswordLoginRisk.AUTHORIZATION_HINT));
}
}
@@ -0,0 +1,62 @@
package cn.qaiu.parser.customjs;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.custom.CustomParserConfig;
import io.vertx.core.Vertx;
import org.junit.Test;
import javax.script.ScriptEngine;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class ParserScriptEngineTest {
@Test
public void disablesClassLookupAndHostLoadersBeforeRunningScripts() throws Exception {
SecurityClassFilter filter = new SecurityClassFilter();
assertFalse(filter.exposeToScripts("java.lang.String"));
assertFalse(filter.exposeToScripts("java.util.Formatter"));
ScriptEngine engine = ParserScriptEngine.create();
for (String name : new String[]{"Java", "JavaImporter", "Packages", "java", "javax",
"org", "com", "edu", "javafx", "load", "loadWithNewGlobal", "engine", "context", "exit", "quit"}) {
assertEquals(name, "undefined", engine.eval("typeof " + name));
assertEquals(name, Boolean.FALSE, engine.eval("Object.getOwnPropertyDescriptor(this, '" + name + "').writable"));
assertEquals(name, Boolean.FALSE, engine.eval("Object.getOwnPropertyDescriptor(this, '" + name + "').configurable"));
}
}
@Test
public void ordinaryScriptsCanStillCallAnInjectedParserApi() throws Exception {
ScriptEngine engine = ParserScriptEngine.create();
engine.put("logger", new JsPlaygroundLogger());
assertEquals("ok", engine.eval("logger.info('parser test'); JSON.parse('{\"result\":\"ok\"}').result"));
}
@Test
public void bothExecutorsPreserveParserApisAndDisableHostGlobals() throws Exception {
String script = """
function parse(info, http, logger) {
logger.info("parser test");
return [info.getShareKey(), typeof fetch, typeof java, typeof loadWithNewGlobal].join("|");
}
""";
String expected = "sample|function|undefined|undefined";
ShareLinkInfo info = ShareLinkInfo.newBuilder().shareKey("sample").build();
CustomParserConfig config = CustomParserConfig.builder()
.type("sandbox_test").displayName("Sandbox test").isJsParser(true).jsCode(script).build();
Vertx vertx = Vertx.vertx();
try {
WebClientVertxInit.init(vertx);
try (JsPlaygroundExecutor playground = new JsPlaygroundExecutor(info, script);
JsParserExecutor registered = new JsParserExecutor(info, config)) {
assertEquals(expected, playground.executeParseAsync().toCompletionStage().toCompletableFuture()
.get(10, TimeUnit.SECONDS));
assertEquals(expected, registered.parse().toCompletionStage().toCompletableFuture()
.get(10, TimeUnit.SECONDS));
}
} finally {
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
}
}
}
@@ -0,0 +1,96 @@
package cn.qaiu.parser.impl;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import java.util.Base64;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class AltchaV2SolverTest {
private static final String NONCE = "00112233445566778899aabbccddeeff";
private static final String SALT = "0102030405060708090a0b0c0d0e0f10";
@Test
public void pbkdf2MatchesAltchaVector() {
byte[] password = password(NONCE, 7);
byte[] derived = AltchaV2Solver.pbkdf2(password, AltchaV2Solver.decodeHex(SALT, "salt"), 100, 32);
assertEquals("dce8b41d12bd8245a12f9fbca56d1d5db2924c1bfe02b924be69f6d89dc1721b",
AltchaV2Solver.toHex(derived));
}
@Test
public void productionCostMatchesCounterZero() {
byte[] derived = AltchaV2Solver.pbkdf2(password(NONCE, 0),
AltchaV2Solver.decodeHex(SALT, "salt"), 1200, 32);
assertEquals("c24bb34595d0df8688c53e6be3b63e4a0fb0f2d9f732b5c4daebc46fba958bf7",
AltchaV2Solver.toHex(derived));
}
@Test
public void solverFindsPrefixedCounterAndBuildsPayload() {
byte[] derived = AltchaV2Solver.pbkdf2(password(NONCE, 3),
AltchaV2Solver.decodeHex(SALT, "salt"), 50, 32);
String prefix = AltchaV2Solver.toHex(derived).substring(0, 8);
JsonObject challenge = challenge(50, prefix, "sig-test");
AltchaV2Solver.Solution solution = AltchaV2Solver.solve(challenge, 20, 5_000);
assertEquals(3, solution.counter);
assertTrue(solution.derivedKeyHex.startsWith(prefix));
JsonObject payload = new JsonObject(new String(Base64.getDecoder().decode(AltchaV2Solver.payload(challenge, solution))));
assertEquals("sig-test", payload.getJsonObject("challenge").getString("signature"));
assertEquals("PBKDF2/SHA-256", payload.getJsonObject("challenge").getJsonObject("parameters").getString("algorithm"));
assertEquals(3, payload.getJsonObject("solution").getInteger("counter").intValue());
assertEquals(solution.derivedKeyHex, payload.getJsonObject("solution").getString("derivedKey"));
}
@Test
public void impossiblePrefixStopsAtTheCounterCap() {
byte[] beyondCap = AltchaV2Solver.pbkdf2(password(NONCE, 40),
AltchaV2Solver.decodeHex(SALT, "salt"), 20, 32);
JsonObject challenge = challenge(20, AltchaV2Solver.toHex(beyondCap).substring(0, 8), "sig");
try {
AltchaV2Solver.solve(challenge, 8, 5_000);
fail("expected the search to stop");
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains("超时"));
}
}
@Test
public void rejectsCostAboveTheSafetyCap() {
JsonObject challenge = challenge(AltchaV2Solver.MAX_COST + 1, "00", "sig");
try {
AltchaV2Solver.solve(challenge, 1, 1_000);
fail("expected cost to be rejected");
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("cost"));
}
}
private static JsonObject challenge(int cost, String keyPrefix, String signature) {
return new JsonObject()
.put("parameters", new JsonObject()
.put("algorithm", "PBKDF2/SHA-256")
.put("cost", cost)
.put("keyLength", 32)
.put("nonce", NONCE)
.put("salt", SALT)
.put("keyPrefix", keyPrefix))
.put("signature", signature);
}
private static byte[] password(String nonceHex, int counter) {
byte[] nonce = AltchaV2Solver.decodeHex(nonceHex, "nonce");
byte[] password = new byte[nonce.length + 4];
System.arraycopy(nonce, 0, password, 0, nonce.length);
password[nonce.length] = (byte) (counter >>> 24);
password[nonce.length + 1] = (byte) (counter >>> 16);
password[nonce.length + 2] = (byte) (counter >>> 8);
password[nonce.length + 3] = (byte) counter;
return password;
}
}
@@ -0,0 +1,274 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.ParserCreate;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* 城通真实联调。默认不跑:
* mvn -pl parser -DskipTests=false -Dctfile.live=true -Dtest=CtToolLiveTest test
*/
public class CtToolLiveTest {
private static final String FREE_FILE = "https://474b.com/file/4015376-131945810";
private static final String PASSWORD_FILE =
"https://url94.ctfile.com/f/64115194-17569800420720-06c697?p=7609";
private static final String PASSWORD_FILE_WITHOUT_PASSWORD =
"https://url94.ctfile.com/f/64115194-17569800420720-06c697";
private static final String PASSWORD_DIR =
"https://url94.ctfile.com/d/64115194-164803691-48508c?p=7609";
private static final String PASSWORD_FILE_WRONG =
"https://url94.ctfile.com/f/64115194-17569800420720-06c697?p=0000";
private static Vertx vertx;
@AfterClass
public static void tearDown() throws Exception {
CtfileSession.clearCachedPasses();
if (vertx != null) {
CtTool.shutdownWorkerExecutor();
vertx.close().toCompletionStage().toCompletableFuture().get(15, TimeUnit.SECONDS);
}
}
@Test
public void freeFileDownloadsRealPdfBytes() throws Exception {
liveOnly();
CtTool tool = tool(FREE_FILE);
String url = tool.parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
FileInfo info = (FileInfo) tool.getShareLinkInfo().getOtherParam().get("fileInfo");
assertNotNull(info);
assertTrue(info.getFileName().endsWith(".pdf"));
assertTrue(info.getSize() > 1000);
assertTrue(url.startsWith("https://"));
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
HttpResponse<byte[]> head = client.send(HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(30))
.header("Range", "bytes=0-15")
.GET().build(), HttpResponse.BodyHandlers.ofByteArray());
assertTrue("head status " + head.statusCode(), head.statusCode() == 206 || head.statusCode() == 200);
String magic = new String(head.body(), 0, Math.min(5, head.body().length), StandardCharsets.ISO_8859_1);
assertEquals("%PDF-", magic);
String range = head.headers().firstValue("content-range").orElse("");
String length = head.headers().firstValue("content-length").orElse("");
assertTrue(range.endsWith("/" + info.getSize()) || length.equals(String.valueOf(info.getSize()))
|| range.contains("/" + info.getSize()));
long size = info.getSize();
HttpResponse<byte[]> tail = client.send(HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(30))
.header("Range", "bytes=" + Math.max(0, size - 20) + "-" + (size - 1))
.GET().build(), HttpResponse.BodyHandlers.ofByteArray());
String ending = new String(tail.body(), StandardCharsets.ISO_8859_1);
assertTrue(ending.contains("%%EOF"));
}
@Test
public void sameSessionListsParentDirectory() throws Exception {
liveOnly();
ShareLinkInfo info = ParserCreate.fromShareUrl(FREE_FILE).getShareLinkInfo();
try (CtfileSession session = CtfileSession.open(info)) {
JsonObject resource = session.loadResource("file", info.getShareKey(),
CtfileSession.ShareTarget.from(info), "", "");
JsonObject file = CtfileSession.dataOf(resource).getJsonObject("file");
String fileDir = file.getString("file_dir", "");
int marker = fileDir.indexOf("/d/");
assertTrue(fileDir, marker >= 0);
String dirId = fileDir.substring(marker + 3);
int query = dirId.indexOf('?');
if (query >= 0) {
dirId = dirId.substring(0, query);
}
JsonObject listing = session.listing("dir", dirId, new CtfileSession.ShareTarget("0", "", "0"),
"", resource, 0, 20);
JsonArray rows = CtfileSession.rowsOf(listing);
assertTrue(rows.size() > 0);
ShareLinkInfo directory = ShareLinkInfo.newBuilder()
.type("ctd")
.panName("城通网盘-目录")
.shareKey(dirId)
.shareUrl("https://474b.com/d/" + dirId)
.build();
directory.getOtherParam().put("domainName", "https://nfd.example");
int named = 0;
for (int i = 0; i < rows.size(); i++) {
FileInfo item = CtTool.toFileInfo(rows.getJsonObject(i), directory);
if (item != null && item.getFileName() != null && !item.getFileName().isBlank()) {
named++;
assertNotNull(item.getParserUrl());
}
}
assertTrue(named > 0);
}
}
@Test
public void passwordFileDownloadsAnonymously() throws Exception {
liveOnly();
CtTool tool = tool(PASSWORD_FILE);
String url = tool.parse().toCompletionStage().toCompletableFuture().get(120, TimeUnit.SECONDS);
FileInfo info = (FileInfo) tool.getShareLinkInfo().getOtherParam().get("fileInfo");
assertEquals("欢迎使用微盘.pdf", info.getFileName());
assertEquals(Long.valueOf(4005749L), info.getSize());
byte[] body = download(url);
assertEquals(4005749, body.length);
assertTrue(new String(body, 0, 5, StandardCharsets.ISO_8859_1).startsWith("%PDF-"));
assertTrue(new String(body, body.length - 16, 16, StandardCharsets.ISO_8859_1).contains("%%EOF"));
assertEquals("cce8357689762fd1acd1f73fcd7e83d62b4e9bcee6fccf0c9b8f46d26ee74902", sha256(body));
}
@Test
public void passwordDirectoryListsAndDownloadsZipAnonymously() throws Exception {
liveOnly();
CtTool directory = tool(PASSWORD_DIR);
List<FileInfo> files = directory.parseFileList().toCompletionStage().toCompletableFuture()
.get(120, TimeUnit.SECONDS);
assertEquals(3, files.size());
FileInfo zip = null;
for (FileInfo file : files) {
assertNotNull(file.getParserUrl());
assertTrue(file.getParserUrl().contains("pwd=7609") || decodedParam(file).getString("pwd").equals("7609"));
if ("osm_model_20260602_153158.zip".equals(file.getFileName())) {
zip = file;
}
}
assertNotNull(zip);
assertEquals(Long.valueOf(158842L), zip.getSize());
ShareLinkInfo child = ShareLinkInfo.newBuilder()
.type("ct")
.panName("城通网盘")
.shareKey("pending")
.shareUrl("https://ctfile.com/file/pending")
.build();
child.getOtherParam().put("paramJson", decodedParam(zip));
child.getOtherParam().put("domainName", "https://nfd.example");
CtTool downloader = new CtTool(child);
String url = downloader.parseById().toCompletionStage().toCompletableFuture().get(120, TimeUnit.SECONDS);
byte[] body = download(url);
assertEquals(158842, body.length);
assertEquals('P', (char) body[0]);
assertEquals('K', (char) body[1]);
int entries = 0;
try (ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(body))) {
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
byte[] ignored = zipIn.readAllBytes();
assertTrue(entry.getName() != null);
assertTrue(ignored.length >= 0);
zipIn.closeEntry();
entries++;
}
}
assertTrue(entries > 0);
}
@Test
public void missingPasswordAndMissingShareStayDistinct() throws Exception {
liveOnly();
String withoutPassword = failure(tool(PASSWORD_FILE_WITHOUT_PASSWORD).parse());
assertTrue(withoutPassword, withoutPassword.contains("需要访问密码"));
assertFalse(withoutPassword, withoutPassword.contains("未配置城通账号"));
String wrongPassword = failure(tool(PASSWORD_FILE_WRONG).parse());
assertTrue(wrongPassword, wrongPassword.contains("访问密码不正确"));
assertFalse(wrongPassword, wrongPassword.contains("未配置城通账号"));
String missingFile = failure(tool("https://474b.com/file/4015376-1").parse());
assertTrue(missingFile, missingFile.contains("不存在或已过期"));
String missingOwner = failure(tool("https://474b.com/file/0-0").parse());
assertTrue(missingOwner, missingOwner.contains("不存在或已过期"));
}
private static JsonObject decodedParam(FileInfo file) {
String url = file.getParserUrl();
return new JsonObject(decodeUrlBase64(url.substring(url.lastIndexOf('/') + 1)));
}
private static String decodeUrlBase64(String value) {
String padded = value;
int mod = padded.length() % 4;
if (mod != 0) {
padded += "=".repeat(4 - mod);
}
return new String(java.util.Base64.getUrlDecoder().decode(padded), StandardCharsets.UTF_8);
}
private static byte[] download(String url) throws Exception {
HttpResponse<byte[]> response = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(20))
.followRedirects(HttpClient.Redirect.NORMAL)
.build()
.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(120)).GET().build(),
HttpResponse.BodyHandlers.ofByteArray());
assertEquals(200, response.statusCode());
return response.body();
}
private static String sha256(byte[] body) throws Exception {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(body);
StringBuilder hex = new StringBuilder();
for (byte value : digest) {
hex.append(String.format("%02x", value));
}
return hex.toString();
}
private static void liveOnly() {
Assume.assumeTrue("set -Dctfile.live=true to call ctfile", Boolean.getBoolean("ctfile.live"));
if (vertx == null) {
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
}
}
private static CtTool tool(String url) {
return (CtTool) ParserCreate.fromShareUrl(url).createTool();
}
private static String failure(io.vertx.core.Future<?> future) throws Exception {
try {
future.toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
return "";
} catch (Exception e) {
Throwable current = e;
StringBuilder message = new StringBuilder();
while (current != null) {
if (current.getMessage() != null) {
message.append(current.getMessage()).append('\n');
}
current = current.getCause();
}
if (message.length() == 0) {
throw e;
}
return message.toString();
}
}
}
@@ -0,0 +1,157 @@
package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.impl.CtfileSession.Decision;
import cn.qaiu.parser.impl.CtfileSession.Kind;
import cn.qaiu.parser.impl.CtfileSession.ShareTarget;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class CtfileResponseTest {
@Test
public void classifiesNotFoundInvalidPasswordAndCaptcha() {
Decision missing = CtfileSession.classify(json(404, null, "File was not found."), 404, "");
assertEquals(Kind.NOT_FOUND, missing.kind);
assertTrue(missing.message.contains("不存在或已过期"));
assertFalse(missing.message.contains("密码"));
Decision unsigned = CtfileSession.classify(json(403, null, "Unsigned file link is not accepted."), 403, "");
assertEquals(Kind.INVALID, unsigned.kind);
Decision needPassword = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"captcha_type\":\"turnstile\",\"capabilities\":{\"passcodeRequired\":true}},"
+ "\"msg\":\"Share passcode is required.\"}"), 423, "");
assertEquals(Kind.NEED_PASSWORD, needPassword.kind);
assertTrue(needPassword.message.contains("需要访问密码"));
Decision wrong = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"passcode_incorrect\",\"captcha_type\":\"turnstile\","
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"incorrect\"}"), 423, "7609");
assertEquals(Kind.BAD_PASSWORD, wrong.kind);
Decision turnstile = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"turnstile\","
+ "\"capabilities\":{\"passcodeRequired\":true,\"ownerId\":64115194}},"
+ "\"msg\":\"Share passcode needs a new human check.\"}"), 423, "7609");
assertEquals(Kind.TURNSTILE, turnstile.kind);
assertEquals("64115194", turnstile.ownerId);
assertTrue(turnstile.message.contains("Turnstile"));
assertFalse(turnstile.message.contains("密码"));
Decision altcha = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"altcha\","
+ "\"capabilities\":{\"passcodeRequired\":false,\"ownerId\":4015376}},"
+ "\"msg\":\"Share access needs a human check.\"}"), 423, "");
assertEquals(Kind.ALTCHA, altcha.kind);
assertEquals("4015376", altcha.ownerId);
Decision ok = CtfileSession.classify(new JsonObject(
"{\"code\":200,\"data\":{\"access_pass\":\"v1.aaa.bbb\",\"capabilities\":{\"ownerId\":4015376}}}"), 200, "");
assertEquals(Kind.OK, ok.kind);
assertEquals("v1.aaa.bbb", ok.accessPass);
Decision labeledTurnstile = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"turnstile\","
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"Share passcode needs a new human check.\"}"),
423, "pw");
assertTrue(CtfileSession.shouldSolveAltcha(labeledTurnstile));
assertFalse(CtfileSession.shouldSolveAltcha(needPassword));
Decision wrongAfterAltcha = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"passcode_incorrect\",\"captcha_type\":\"turnstile\","
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"Share passcode is incorrect.\"}"),
423, "0000");
assertEquals(Kind.BAD_PASSWORD, wrongAfterAltcha.kind);
assertFalse(CtfileSession.shouldSolveAltcha(wrongAfterAltcha));
ShareLinkInfo passwordShare = ShareLinkInfo.newBuilder()
.type("ct")
.shareKey("11-22-ab")
.sharePassword("pw")
.shareUrl("https://example.test/f/11-22-ab?p=pw")
.build();
assertFalse(CtTool.requiresV4(passwordShare));
passwordShare.getOtherParam().put("ctV4FileId", "f22");
assertTrue(CtTool.requiresV4(passwordShare));
}
@Test
public void resourceQueryKeepsTokensAndEncodesThem() {
Map<String, String> query = CtfileSession.resourceQuery("file", "4015376-131945810",
new ShareTarget("0", "", "0"), "7609", "a+b/c=", "turn stile", "v1.aaa.bbb");
String form = CtfileSession.form(query);
assertTrue(form.contains("kind=file"));
assertTrue(form.contains("passcode=7609"));
assertTrue(form.contains("altcha_token=a%2Bb%2Fc%3D"));
assertTrue(form.contains("turnstile_token=turn+stile") || form.contains("turnstile_token=turn%20stile"));
assertTrue(form.contains("access_pass=v1.aaa.bbb"));
}
@Test
public void listingRowBecomesFileAndFolderLinks() {
ShareLinkInfo info = ShareLinkInfo.newBuilder()
.type("ctd")
.panName("城通网盘-目录")
.shareKey("64115194-164803691-48508c")
.sharePassword("7609")
.shareUrl("https://url94.ctfile.com/d/64115194-164803691-48508c?p=7609")
.build();
info.getOtherParam().put("domainName", "https://nfd.example");
FileInfo folder = CtTool.toFileInfo(new JsonObject()
.put("kind", "folder")
.put("name", "2022")
.put("folderId", 54597713)
.put("folderKey", "bf0603")
.put("date", "2023-02-22"), info);
assertEquals("folder", folder.getFileType());
assertTrue(folder.getParserUrl().contains("dirId="));
assertTrue(folder.getParserUrl().contains("54597713"));
assertTrue(folder.getParserUrl().contains("pwd=7609"));
FileInfo file = CtTool.toFileInfo(new JsonObject()
.put("kind", "file")
.put("name", "notes.pdf")
.put("href", "#/f/t-token")
.put("fileId", 415670738)
.put("extension", "pdf")
.put("size", "1 MB")
.put("size_bytes", 1048576)
.put("date", "2019-12-31"), info);
assertEquals("t-token", fileId(file));
assertEquals(Long.valueOf(1048576L), file.getSize());
assertEquals("pdf", file.getFileType());
assertTrue(file.getParserUrl().startsWith("https://nfd.example/v2/redirectUrl/ctd/"));
}
private static JsonObject json(int code, JsonObject data, String message) {
JsonObject body = new JsonObject().put("code", code).put("msg", message);
if (data != null) {
body.put("data", data);
}
return body;
}
private static String fileId(FileInfo file) {
String url = file.getParserUrl();
String encoded = url.substring(url.lastIndexOf('/') + 1);
return new JsonObject(decodeUrlBase64(encoded)).getString("id");
}
private static String decodeUrlBase64(String value) {
String padded = value;
int mod = padded.length() % 4;
if (mod != 0) {
padded += "=".repeat(4 - mod);
}
byte[] bytes = java.util.Base64.getUrlDecoder().decode(padded);
return new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
}
}
@@ -0,0 +1,133 @@
package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.impl.CtfileV4Client.V4CallException;
import io.vertx.core.MultiMap;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class CtfileV4Test {
private static final String FILE_LINK = "xtc11-f22-ab-pw";
private static final String DIR_LINK = "xtc11-d33-cd-pw";
@Test
public void webShareBecomesXtlink() {
assertEquals(FILE_LINK, CtfileXtlink.fromShare("11-22-ab", "pw", false));
assertEquals(DIR_LINK, CtfileXtlink.fromShare("11-33-cd", "pw", true));
assertEquals("xturl44-f55", CtfileXtlink.fromShare("44-55", "", false));
assertEquals("xturl11-d33-cd", CtfileXtlink.fromShare("11-33-cd", null, true));
assertEquals("xtc1-d2-ab-pw", CtfileXtlink.fromShare("xtc1-d2-ab-pw", "other", true));
assertNull(CtfileXtlink.fromShare("t-signed", "pw", true));
assertEquals("f22", CtfileXtlink.prefixedId("22", false));
assertEquals("22", CtfileXtlink.bareId("f22"));
}
@Test
public void requestBodiesMatchTheClientProtocol() {
JsonObject list = CtfileV4Client.listBody(DIR_LINK, "33", 1, 2);
assertEquals(DIR_LINK, list.getString("xtlink"));
assertEquals(33L, list.getLong("folder_id").longValue());
assertEquals(1, list.getInteger("start").intValue());
assertEquals(2, list.getInteger("pagesize").intValue());
JsonObject auth = CtfileV4Client.authBody(FILE_LINK, "f22");
assertEquals("f22", auth.getString("ids"));
JsonObject fetch = CtfileV4Client.fetchBody(FILE_LINK, "22", "sig");
assertEquals("22", fetch.getString("file_id"));
assertEquals("sig", fetch.getString("download_sign"));
assertEquals(0, fetch.getInteger("carrier").intValue());
assertFalse(CtfileV4Client.refreshBody("rt", false).containsKey("rotate_token"));
assertTrue(CtfileV4Client.refreshBody("rt", true).getBoolean("rotate_token"));
}
@Test
public void errorCodesStaySpecific() {
assertTrue(CtfileV4Client.describeFailure(401, "无效或过期的refresh token", "api.auth.invalid_refresh_token")
.contains("refresh_token 无效或已过期"));
assertTrue(CtfileV4Client.describeFailure(401, "无效的令牌或账户已锁定", "").contains("登录令牌无效或账号已锁定"));
assertEquals("城通账号已锁定", CtfileV4Client.describeFailure(401, "账户已锁定", ""));
assertEquals("访问密码不正确", CtfileV4Client.describeFailure(403, "访问密码不正确", "api.passcode"));
assertTrue(CtfileV4Client.describeFailure(404, "分享不存在", "").contains("不存在或已过期"));
assertTrue(CtfileV4Client.describeFailure(401, "请扫码完成登录保护", "qr_required").contains("扫码"));
V4CallException invalid = new V4CallException(401, "无效的令牌或账户已锁定", "");
assertTrue(invalid.authenticationFailure());
assertFalse(new V4CallException(403, "访问密码不正确", "passcode").authenticationFailure());
}
@Test
public void listRowBecomesDownloadParamWithXtlink() {
ShareLinkInfo info = ShareLinkInfo.newBuilder()
.type("ctd")
.panName("城通网盘-目录")
.shareKey("11-33-cd")
.sharePassword("pw")
.shareUrl("https://example.test/d/11-33-cd?p=pw")
.build();
info.getOtherParam().put("domainName", "https://nfd.example");
FileInfo file = CtfileV4Client.toFileInfo(new JsonObject()
.put("key", "f22")
.put("name", "notes.pdf")
.put("icon", "pdf")
.put("size", 12)
.put("date", "2024-01-02"), info, DIR_LINK);
assertEquals("notes.pdf", file.getFileName());
assertEquals(Long.valueOf(12L), file.getSize());
assertTrue(file.getParserUrl().contains("/v2/redirectUrl/ctd/"));
JsonObject param = new JsonObject(decode(file.getParserUrl().substring(file.getParserUrl().lastIndexOf('/') + 1)));
assertEquals("f22", param.getString("id"));
assertEquals(DIR_LINK, param.getString("xtlink"));
assertEquals("pw", param.getString("pwd"));
ShareLinkInfo download = ShareLinkInfo.newBuilder().type("ctd").sharePassword("").build();
assertTrue(CtTool.applyFileParam(download, param));
assertEquals("f22", download.getOtherParam().get("ctV4FileId"));
assertEquals("11-33-cd", download.getShareKey());
FileInfo folder = CtfileV4Client.toFileInfo(new JsonObject()
.put("fid", "d33")
.put("name", "2022")
.put("is_folder", true), info, DIR_LINK);
assertEquals("folder", folder.getFileType());
assertTrue(folder.getParserUrl().contains("dirId=33"));
assertTrue(folder.getParserUrl().contains("pwd=pw"));
}
@Test
public void credentialsComeFromAuthsAndDoNotTreatSharePasswordAsLogin() {
ShareLinkInfo info = ShareLinkInfo.newBuilder()
.type("ct")
.shareKey("11-22-ab")
.sharePassword("pw")
.build();
assertFalse(CtfileV4Client.hasCredentials(info));
MultiMap auths = MultiMap.caseInsensitiveMultiMap();
auths.set("refresh_token", "refresh-value");
auths.set("authorization", "Bearer access-value");
auths.set("_configId", "home");
info.getOtherParam().put("auths", auths);
CtfileV4Client.Credentials credentials = CtfileV4Client.credentials(info);
assertEquals("refresh-value", credentials.refreshToken);
assertEquals("access-value", credentials.accessToken);
assertTrue(credentials.usable());
assertTrue(CtfileV4Client.missingAccountMessage().contains("auths.ct.refresh_token"));
}
private static String decode(String value) {
String padded = value;
int mod = padded.length() % 4;
if (mod != 0) {
padded += "=".repeat(4 - mod);
}
return new String(java.util.Base64.getUrlDecoder().decode(padded), java.nio.charset.StandardCharsets.UTF_8);
}
}
@@ -0,0 +1,59 @@
package cn.qaiu.parser.impl;
import cn.qaiu.util.AESUtils;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import static org.junit.Assert.*;
public class FjDownloadParamsTest {
@Test
public void anonymousIdentityIsEmptyRatherThanNull() throws Exception {
JsonObject params = FjDownloadParams.create("123", null, "uuid", "share", 1000L);
assertEquals("123|", decrypt(params.getString("fidEncode")));
assertEquals("1000", decrypt(params.getString("ts")));
assertEquals("123|1000", decrypt(params.getString("auth")));
}
@Test
public void authenticatedIdentityAndTimestampAreRegenerated() throws Exception {
JsonObject params = FjDownloadParams.create("123", "456", "uuid", "share", 2000L);
assertEquals("123|456", decrypt(params.getString("fidEncode")));
assertEquals("123|2000", decrypt(params.getString("auth")));
}
@Test
public void legacyLinksRecoverOnlyFileId() throws Exception {
JsonObject old = JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|null"), "ts", "expired");
assertEquals("123", FjDownloadParams.fileId(old));
assertEquals("789", FjDownloadParams.fileId(JsonObject.of("fileId", "789")));
}
@Test(expected = IllegalArgumentException.class)
public void invalidLegacyLinkFailsExplicitly() throws Exception {
FjDownloadParams.fileId(JsonObject.of("fidEncode", AESUtils.encrypt2Hex("invalid")));
}
@Test
public void upstreamErrorPreservesBusinessCodeAndMessage() {
String message = FjDownloadParams.missingLocation(200, "{\"code\":401,\"msg\":\"请登录后下载\"}");
assertTrue(message.contains("HTTP 200"));
assertTrue(message.contains("code=401"));
assertTrue(message.contains("请登录后下载"));
assertTrue(FjDownloadParams.missingLocation(502, "").contains("响应体为空"));
assertTrue(FjDownloadParams.missingLocation(502, "x".repeat(1000)).length() < 600);
}
@Test
public void ownerIdentityComesFromDirectoryDataOrLegacySignature() throws Exception {
assertEquals("11069975", FjDownloadParams.ownerId(JsonObject.of("userId", 11069975L)));
assertEquals("11069975", FjDownloadParams.ownerId(
JsonObject.of("fidEncode", AESUtils.encrypt2Hex("61731757356|11069975"))));
assertNull(FjDownloadParams.ownerId(JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|null"))));
assertNull(FjDownloadParams.ownerId(JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|"))));
}
private String decrypt(String value) throws Exception {
return AESUtils.decryptByHexAES(value, AESUtils.CIPHER_AES0);
}
}
@@ -0,0 +1,170 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.util.AESUtils;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import io.vertx.uritemplate.UriTemplate;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.*;
public class FjToolDownloadTest {
private Vertx vertx;
private WebClient local;
private HttpServer server;
private final AtomicInteger logins = new AtomicInteger();
private final AtomicInteger downloads = new AtomicInteger();
private String identity;
private String businessError;
private String contentEncoding;
@Before
public void setup() throws Exception {
FjTool.resetToken();
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
local = WebClient.create(vertx, new WebClientOptions().setFollowRedirects(false));
server = vertx.createHttpServer().requestHandler(req -> {
if (req.path().equals("/ws/login")) {
logins.incrementAndGet();
req.response().setStatusCode(500).end("Share downloads must not require login");
} else if (req.path().equals("/ws/file/redirect")) {
downloads.incrementAndGet();
try {
identity = AESUtils.decryptByHexAES(req.getParam("downloadId"), AESUtils.CIPHER_AES0);
long timestamp = Long.parseLong(AESUtils.decryptByHexAES(req.getParam("timestamp"), AESUtils.CIPHER_AES0));
assertTrue(Math.abs(System.currentTimeMillis() - timestamp) < 10000);
assertEquals(AESUtils.encrypt2Hex("123|" + timestamp), req.getParam("auth"));
assertEquals("share", req.getParam("shareId"));
if (businessError != null) {
if (contentEncoding != null) {
req.response().putHeader("Content-Encoding", contentEncoding);
}
req.response().end(businessError);
} else {
req.response().setStatusCode(302).putHeader("Location", "https://download.example/file").end();
}
} catch (Throwable e) {
req.response().setStatusCode(500).end(e.toString());
}
} else {
req.response().setStatusCode(404).end();
}
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
}
@After
public void cleanup() throws Exception {
local.close();
server.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
FjTool.resetToken();
}
@Test
public void directoryLinkUsesOwnerEvenWithConfiguredCredentials() throws Exception {
ShareLinkInfo info = info();
info.getOtherParam().put("auths", MultiMap.caseInsensitiveMultiMap()
.set("username", "test-user").set("password", "test-password"));
assertEquals("https://download.example/file", tool(info).parseById()
.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS));
assertEquals(0, logins.get());
assertEquals(1, downloads.get());
assertEquals("123|11069975", identity);
}
@Test
public void shareRequestUsesOwnerNotGlobalUserIdentity() throws Exception {
FjTool.userId = "other-user";
assertEquals("https://download.example/file", tool(info()).parseById()
.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS));
assertEquals("123|11069975", identity);
assertEquals(0, logins.get());
FjTool.userId = null;
}
@Test
public void upstreamBusinessErrorCompletesFutureWithReason() throws Exception {
businessError = "{\"code\":403,\"msg\":\"需要会员\"}";
try {
tool(info()).parseById().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
fail("Expected upstream error");
} catch (ExecutionException e) {
assertTrue(e.getCause().getMessage().contains("需要会员"));
assertTrue(e.getCause().getMessage().contains("code=403"));
}
}
@Test
public void unsupportedErrorEncodingFailsWithoutLeavingFuturePending() throws Exception {
contentEncoding = "zstd";
businessError = "upstream error";
assertErrorBodyFailure("zstd");
}
@Test
public void oversizedErrorBodyFailsWithoutLeavingFuturePending() throws Exception {
businessError = "x".repeat(8 * 1024 * 1024 + 1);
assertErrorBodyFailure("响应体过大");
}
private void assertErrorBodyFailure(String expectedReason) throws Exception {
try {
tool(info()).parseById().toCompletionStage().toCompletableFuture().get(3, TimeUnit.SECONDS);
fail("Expected response decoding error");
} catch (ExecutionException e) {
assertTrue(e.getCause().getMessage(), e.getCause().getMessage().contains(expectedReason));
}
}
@Test
public void missingOwnerFailsBeforeDownload() throws Exception {
ShareLinkInfo info = info();
info.getOtherParam().put("paramJson", JsonObject.of("fileId", "123", "shareId", "share"));
try {
tool(info).parseById().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
fail("Expected missing owner error");
} catch (ExecutionException e) {
assertTrue(e.getCause().getMessage().contains("缺少分享者 userId"));
}
assertEquals(0, downloads.get());
}
private ShareLinkInfo info() {
ShareLinkInfo info = ShareLinkInfo.newBuilder().type("fj").shareKey("share")
.shareUrl("https://share.feijipan.com/s/share").build();
info.getOtherParam().put("paramJson", JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|11069975"),
"uuid", "test-uuid", "ts", "expired", "auth", "expired", "shareId", "share"));
return info;
}
private FjTool tool(ShareLinkInfo info) {
WebClient routed = (WebClient) Proxy.newProxyInstance(WebClient.class.getClassLoader(),
new Class<?>[]{WebClient.class}, (proxy, method, args) -> {
if (args != null && args.length > 0 && args[0] instanceof UriTemplate template) {
args[0] = Proxy.newProxyInstance(UriTemplate.class.getClassLoader(),
new Class<?>[]{UriTemplate.class}, (p, m, a) -> {
Object expanded = m.invoke(template, a);
return expanded instanceof String url
? url.replace("https://api.feijipan.com", "http://127.0.0.1:" + server.actualPort())
: expanded;
});
}
return method.invoke(local, args);
});
return new FjTool(info) {{ client = routed; clientNoRedirects = routed; }};
}
}
@@ -0,0 +1,144 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.FolderPaging;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.WebClient;
import io.vertx.uritemplate.UriTemplate;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/** 小飞机 share/list:offset 是从 1 开始的页码,limit 为每页条数。 */
public class FjToolFolderPagingTest {
private Vertx vertx;
private WebClient local;
private HttpServer server;
private final List<String> queries = new CopyOnWriteArrayList<>();
private volatile String override;
@Before
public void setup() throws Exception {
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
local = WebClient.create(vertx);
server = vertx.createHttpServer().requestHandler(req -> {
if (req.path().endsWith("/share/list")) {
queries.add(req.query());
if (override != null) {
req.response().end(override);
return;
}
int offset = Integer.parseInt(req.getParam("offset"));
int limit = Integer.parseInt(req.getParam("limit"));
int total = 125;
int totalPage = (total + limit - 1) / limit;
JsonArray list = new JsonArray();
for (int i = (offset - 1) * limit; i < Math.min(total, offset * limit); i++) {
list.add(new JsonObject().put("fileType", 1).put("fileId", String.valueOf(1000 + i)).put("fileName", "f" + i + ".txt")
.put("fileSize", 1).put("fileIcon", "txt").put("userId", 9).put("fileDownloads", 0)
.put("updTime", "2024-01-01 00:00:00"));
}
req.response().end(new JsonObject().put("code", 200).put("list", list).put("total", total)
.put("offset", offset).put("limit", limit).put("totalPage", totalPage).encode());
} else {
req.response().setStatusCode(404).end();
}
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
}
@After
public void cleanup() throws Exception {
local.close();
server.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
}
@Test
public void defaultRequestIsFirstPageWithLegacyLimit() throws Exception {
ShareLinkInfo info = info(null);
List<FileInfo> list = list(info);
assertEquals(60, list.size());
assertTrue(queries.get(0).contains("offset=1"));
assertTrue(queries.get(0).contains("limit=60"));
assertTrue(FolderPaging.pageInfo(info).getBoolean("hasMore"));
assertEquals(Integer.valueOf(125), FolderPaging.pageInfo(info).getInteger("total"));
}
@Test
public void pagesAreDistinctAndLastPageEnds() throws Exception {
java.util.Set<String> ids = new java.util.HashSet<>();
for (int page = 1; page <= 3; page++) {
ShareLinkInfo info = info(page);
for (FileInfo f : list(info)) {
assertTrue("重复 " + f.getFileId(), ids.add(f.getFileId()));
}
assertEquals(page < 3, FolderPaging.pageInfo(info).getBoolean("hasMore"));
assertTrue(queries.get(queries.size() - 1).contains("offset=" + page));
}
assertEquals(125, ids.size());
ShareLinkInfo beyond = info(4);
assertTrue(list(beyond).isEmpty());
assertFalse(FolderPaging.pageInfo(beyond).getBoolean("hasMore"));
}
@Test
public void nonJsonListFailsInsteadOfHanging() throws Exception {
override = "<html>busy</html>";
try {
list(info(null));
fail();
} catch (ExecutionException e) {
assertTrue(e.getCause().getMessage().contains("目录解析失败"));
}
}
private List<FileInfo> list(ShareLinkInfo info) throws Exception {
return tool(info).parseFileList().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
}
private ShareLinkInfo info(Integer page) {
ShareLinkInfo info = ShareLinkInfo.newBuilder().type("fj").shareKey("share")
.shareUrl("https://share.feijipan.com/s/share").build();
info.getOtherParam().put("dirId", "777");
info.getOtherParam().put("uuid", "test-uuid");
if (page != null) {
info.getOtherParam().put(FolderPaging.PAGE, page);
}
return info;
}
private FjTool tool(ShareLinkInfo info) {
WebClient routed = (WebClient) Proxy.newProxyInstance(WebClient.class.getClassLoader(),
new Class<?>[]{WebClient.class}, (proxy, method, args) -> {
if (args != null && args.length > 0 && args[0] instanceof UriTemplate template) {
args[0] = Proxy.newProxyInstance(UriTemplate.class.getClassLoader(),
new Class<?>[]{UriTemplate.class}, (p, m, a) -> {
Object expanded = m.invoke(template, a);
return expanded instanceof String url
? url.replace("https://api.feijipan.com", "http://127.0.0.1:" + server.actualPort())
: expanded;
});
}
return method.invoke(local, args);
});
return new FjTool(info) {{ client = routed; clientNoRedirects = routed; }};
}
}
@@ -0,0 +1,36 @@
package cn.qaiu.parser.impl;
import io.vertx.core.MultiMap;
import org.junit.Test;
import static org.junit.Assert.*;
public class IzXffHeaderTest {
@Test
public void offByDefault() {
assertNull(IzXffHeader.resolve(null));
assertNull(IzXffHeader.resolve(""));
assertNull(IzXffHeader.resolve("OFF"));
}
@Test
public void literalAndRandom() {
assertEquals("113.96.181.18", IzXffHeader.resolve("113.96.181.18"));
String ip = IzXffHeader.resolve("random");
assertTrue(ip, ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"));
}
@Test
public void applyRemovesWhenOff() {
MultiMap h = MultiMap.caseInsensitiveMultiMap().set("X-Forwarded-For", "1.1.1.1");
System.clearProperty(IzXffHeader.PROP);
if (System.getenv(IzXffHeader.ENV) == null) {
IzXffHeader.apply(h);
assertFalse(h.contains("X-Forwarded-For"));
}
System.setProperty(IzXffHeader.PROP, "8.8.8.8");
IzXffHeader.apply(h);
assertEquals("8.8.8.8", h.get("X-Forwarded-For"));
System.clearProperty(IzXffHeader.PROP);
}
}
@@ -0,0 +1,76 @@
package cn.qaiu.parser.impl;
import cn.qaiu.util.CommonUtils;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class LzFolderCursorTest {
private static final String PATH = "/filemoreajax.php?file=66477";
private static Map<String, String> form() {
Map<String, String> form = new LinkedHashMap<>();
form.put("lx", "2");
form.put("fid", "66477");
form.put("uid", "234978");
form.put("pg", "1");
form.put("t", "1795564485");
form.put("k", "abc");
form.put("pwd", "secret");
return form;
}
@Test
public void roundTripDropsPasswordAndUsesRequestedPage() {
String raw = LzFolderCursor.encode("b66477", PATH, form(), 2, "wp1");
assertFalse(CommonUtils.urlBase64Decode(raw).contains("secret"));
LzFolderCursor cursor = LzFolderCursor.decode(raw, "b66477", 2);
assertNotNull(cursor);
assertEquals(PATH, cursor.path);
assertEquals("wp1", cursor.webpage);
Map<String, String> next = cursor.formFor("newpwd", 2);
assertEquals("2", next.get("pg"));
assertEquals("newpwd", next.get("pwd"));
assertEquals("1795564485", next.get("t"));
}
@Test
public void mismatchedShareOrPageIsIgnored() {
String raw = LzFolderCursor.encode("b66477", PATH, form(), 2, null);
assertNull(LzFolderCursor.decode(raw, "b00000", 2));
assertNull(LzFolderCursor.decode(raw, "b66477", 3));
assertNull(LzFolderCursor.decode("not-base64!", "b66477", 2));
assertNull(LzFolderCursor.decode(null, "b66477", 2));
}
@Test
public void tamperedPathOrFieldsAreIgnored() {
assertNull(LzFolderCursor.decode(LzFolderCursor.encode("b1", "http://evil/x", form(), 2, null), "b1", 2));
assertNull(LzFolderCursor.decode(LzFolderCursor.encode("b1", "/filemoreajax.php?file=1", form(), 2, null), "b1", 2));
Map<String, String> bad = form();
bad.put("x\ny", "1");
assertNull(LzFolderCursor.decode(LzFolderCursor.encode("b1", PATH, bad, 2, null), "b1", 2));
Map<String, String> noToken = form();
noToken.remove("t");
assertNull(LzFolderCursor.decode(LzFolderCursor.encode("b1", PATH, noToken, 2, null), "b1", 2));
JsonObject json = new JsonObject(CommonUtils.urlBase64Decode(LzFolderCursor.encode("b1", PATH, form(), 2, null)));
json.put("v", 99);
assertNull(LzFolderCursor.decode(CommonUtils.urlBase64Encode(json.encode()), "b1", 2));
}
@Test
public void unsafeWebpageIsDropped() {
String raw = LzFolderCursor.encode("b1", PATH, form(), 2, "a/../../x?y");
LzFolderCursor cursor = LzFolderCursor.decode(raw, "b1", 2);
assertNotNull(cursor);
assertNull(cursor.webpage);
}
}
@@ -0,0 +1,95 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.parser.ParserCreate;
import io.vertx.core.Vertx;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.Test;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* 蓝奏目录真实联调。默认不跑:
* mvn -pl parser -DskipTests=false -Dlz.live=true -Dtest=LzFolderLiveTest test
*/
public class LzFolderLiveTest {
private static Vertx vertx;
@AfterClass
public static void close() {
if (vertx != null) {
vertx.close();
}
}
@Test
public void oldFolderListsOnBothDomainsAndOneFileDownloads() throws Exception {
liveOnly();
List<FileInfo> oui = list("https://pan.lanzoui.com/b66477");
List<FileInfo> oug = list("https://pan.lanzoug.com/b66477");
assertFalse(oui.isEmpty());
assertFalse(oug.isEmpty());
assertEquals(oui.get(0).getFileName(), oug.get(0).getFileName());
FileInfo small = smallest(oui);
String url = ParserCreate.fromShareUrl("https://pan.lanzoui.com/" + small.getFileId())
.createTool().parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
HttpResponse<byte[]> response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(20))
.build()
.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(60)).GET().build(),
HttpResponse.BodyHandlers.ofByteArray());
assertEquals(200, response.statusCode());
assertTrue(response.body().length > 0);
if (small.getSize() != null && small.getSize() > 0 && small.getSize() < 8_000_000) {
assertEquals(small.getSize().longValue(), response.body().length);
}
}
@Test
public void passwordFolderStillLists() throws Exception {
liveOnly();
List<FileInfo> files = ParserCreate.fromShareUrl("https://moteam.lanzoum.com/b00yaejvte")
.setShareLinkInfoPwd("1234")
.createTool().parseFileList()
.toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
assertFalse(files.isEmpty());
assertTrue(files.stream().anyMatch(file -> file.getFileName() != null && !file.getFileName().isBlank()));
}
private static List<FileInfo> list(String url) throws Exception {
return ParserCreate.fromShareUrl(url).createTool().parseFileList()
.toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
}
private static FileInfo smallest(List<FileInfo> files) {
FileInfo best = files.get(0);
for (FileInfo file : files) {
if (file.getSize() != null && (best.getSize() == null || file.getSize() < best.getSize())) {
best = file;
}
}
return best;
}
private static void liveOnly() {
Assume.assumeTrue("set -Dlz.live=true to call lanzou", Boolean.getBoolean("lz.live"));
if (vertx == null) {
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
}
}
}
@@ -0,0 +1,175 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.parser.FolderPaging;
import cn.qaiu.parser.ParserCreate;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.Test;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* 蓝奏目录分页真实联调(b66477 约 93 页,每页 50 条)。默认不跑:
* mvn -pl parser -DskipTests=false -Dlz.live=true -Dtest=LzFolderPagingLiveTest test
* 加 -Dlz.live.full=true 会顺序翻完整个目录(约 2 分钟)。
*/
public class LzFolderPagingLiveTest {
private static final String OUI = "https://pan.lanzoui.com/b66477";
private static final String OUG = "https://pan.lanzoug.com/b66477";
private static Vertx vertx;
@AfterClass
public static void close() {
if (vertx != null) {
vertx.close();
}
}
record Page(List<FileInfo> list, JsonObject info) {
String cursor() {
return info.getString("nextCursor");
}
}
@Test
public void pacedPagesOneToThreeAreFullAndDistinct() throws Exception {
liveOnly();
Set<String> ids = new HashSet<>();
Page page = page(OUI, null, 1, null);
for (int n = 1; n <= 3; n++) {
if (n > 1) {
Thread.sleep(5000);
page = page(OUI, null, n, page.cursor());
}
// 上游每页 50 条原始项,其中 id=-1 的占位项(如 ***.apk)已被过滤
assertTrue("第 " + n + " 页 " + page.list().size(), page.list().size() >= 45 && page.list().size() <= 50);
assertEquals(Integer.valueOf(50), page.info().getInteger("pageSize"));
assertTrue(page.info().getBoolean("hasMore"));
assertNotNull(page.cursor());
page.list().forEach(f -> assertTrue("重复 " + f.getFileId(), ids.add(f.getFileId())));
}
}
/** 上游对紧跟的下一页常回 zt=4「请刷新,重试0」:必须重试成功或明确报错,不能当末页。 */
@Test
public void immediateNextPageIsNeverReportedAsEnd() throws Exception {
liveOnly();
Page first = page(OUG, null, 1, null);
try {
Page second = page(OUG, null, 2, first.cursor());
assertFalse(second.list().isEmpty());
assertTrue(second.info().getBoolean("hasMore"));
} catch (ExecutionException e) {
String msg = e.getCause().getMessage();
assertTrue(msg, msg.contains("稍后重试") || msg.contains("重新加载"));
}
Page again = page(OUG, null, 2, null);
assertEquals(50, again.list().size());
assertTrue(again.info().getBoolean("hasMore"));
}
@Test
public void passwordFolderIsSinglePageAndPageTwoIsEmpty() throws Exception {
liveOnly();
Page first = page("https://moteam.lanzoum.com/b00yaejvte", "1234", 1, null);
assertFalse(first.list().isEmpty());
assertFalse(first.info().getBoolean("hasMore"));
assertNull(first.cursor());
Thread.sleep(2000);
Page second = page("https://moteam.lanzoum.com/b00yaejvte", "1234", 2, null);
assertTrue(second.list().isEmpty());
assertFalse(second.info().getBoolean("hasMore"));
}
@Test
public void fileFromSecondPageDownloads() throws Exception {
liveOnly();
Page first = page(OUI, null, 1, null);
Thread.sleep(2000);
Page second = page(OUI, null, 2, first.cursor());
FileInfo small = second.list().get(0);
for (FileInfo f : second.list()) {
if (f.getSize() != null && small.getSize() != null && f.getSize() < small.getSize()) {
small = f;
}
}
String url = ParserCreate.fromShareUrl("https://pan.lanzoui.com/" + small.getFileId())
.createTool().parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
HttpResponse<byte[]> response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(20))
.build()
.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(120)).GET().build(),
HttpResponse.BodyHandlers.ofByteArray());
assertEquals(200, response.statusCode());
assertTrue(response.body().length > 0);
}
@Test
public void wholeFolderWithCursorHasNoDuplicatesAndEnds() throws Exception {
liveOnly();
Assume.assumeTrue(Boolean.getBoolean("lz.live.full"));
Set<String> ids = new HashSet<>();
String cursor = null;
int pages = 0;
int lastSize = -1;
for (int n = 1; n <= FolderPaging.MAX_PAGE; n++) {
Page page = page(OUI, null, n, cursor);
pages = n;
lastSize = page.list().size();
page.list().forEach(f -> assertTrue("重复 " + f.getFileId(), ids.add(f.getFileId())));
if (!page.info().getBoolean("hasMore")) {
break;
}
cursor = page.cursor();
assertNotNull(cursor);
Thread.sleep(800);
}
assertTrue("应有多页", pages > 2);
assertTrue("末页应不足 50 条", lastSize < 50);
assertTrue(ids.size() > (pages - 1) * 49);
}
private static Page page(String url, String pwd, int page, String cursor) throws Exception {
ParserCreate create = ParserCreate.fromShareUrl(url);
if (pwd != null) {
create.setShareLinkInfoPwd(pwd);
}
create.getShareLinkInfo().getOtherParam().put(FolderPaging.PAGE, page);
if (cursor != null) {
create.getShareLinkInfo().getOtherParam().put(FolderPaging.CURSOR, cursor);
}
List<FileInfo> list = create.createTool().parseFileList()
.toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
return new Page(list, FolderPaging.pageInfo(create.getShareLinkInfo()));
}
private static void liveOnly() {
Assume.assumeTrue(Boolean.getBoolean("lz.live"));
if (vertx == null) {
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
}
}
}
@@ -0,0 +1,293 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.FolderPaging;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* 蓝奏目录分页离线回归:本地模拟分享页与 filemoreajax.php。
* 上游真实行为(b66477 实测):每页 50 条,不足 50 即末页;zt=2「没有了」;
* 同一组 t/k 请求过快返回 {@code {"zt":4,"info":"请刷新,重试0","text":0}},隔约 2 秒同页可正常取到。
*/
public class LzToolFolderPagingTest {
private static final String SHARE_KEY = "b66477";
private static final String TOKEN_T = "1700000000";
private static final String TOKEN_K = "test-k-token";
private static final String RATE_LIMITED = "{\"zt\":4,\"info\":\"请刷新,重试0\",\"text\":0}";
private Vertx vertx;
private HttpServer server;
private final AtomicInteger pageGets = new AtomicInteger();
private final List<MultiMap> ajaxForms = new CopyOnWriteArrayList<>();
private final Map<String, AtomicInteger> ajaxCountByPg = new ConcurrentHashMap<>();
/** (pg, 该页第几次请求 从 1 开始) -> 响应体;返回 null 用默认三页数据 */
private volatile BiFunction<Integer, Integer, String> ajax = (pg, n) -> null;
@Before
public void setup() throws Exception {
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
server = vertx.createHttpServer().requestHandler(req -> {
if ("GET".equals(req.method().name()) && req.path().equals("/" + SHARE_KEY)) {
pageGets.incrementAndGet();
req.response().putHeader("Content-Type", "text/html; charset=utf-8").end(folderHtml());
} else if (req.path().equals("/filemoreajax.php")) {
req.setExpectMultipart(true);
req.endHandler(v -> {
MultiMap form = MultiMap.caseInsensitiveMultiMap().addAll(req.formAttributes());
ajaxForms.add(form);
int pg = Integer.parseInt(form.get("pg"));
int n = ajaxCountByPg.computeIfAbsent(String.valueOf(pg), k -> new AtomicInteger()).incrementAndGet();
String body = ajax.apply(pg, n);
req.response().putHeader("Content-Type", "text/json; charset=utf-8")
.end(body != null ? body : defaultPage(pg));
});
} else {
req.response().setStatusCode(404).end();
}
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
}
@After
public void cleanup() throws Exception {
server.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
}
@Test
public void defaultRequestStillReturnsFirstPageWithoutPlaceholder() throws Exception {
ShareLinkInfo info = info(null, null);
List<FileInfo> list = list(info);
assertEquals(49, list.size());
assertTrue(list.stream().noneMatch(f -> "-1".equals(f.getFileId())));
assertEquals("p1-0", list.get(0).getFileId());
assertTrue(list.get(0).getParserUrl().startsWith("http://nfd.test/v2/redirectUrl/lz/"));
JsonObject pageInfo = FolderPaging.pageInfo(info);
assertTrue(pageInfo.getBoolean("hasMore"));
assertEquals(2, (int) pageInfo.getInteger("nextPage"));
assertNotNull(pageInfo.getString("nextCursor"));
assertEquals(1, pageGets.get());
assertEquals("1", ajaxForms.get(0).get("pg"));
assertEquals("secret", ajaxForms.get(0).get("pwd"));
}
@Test
public void rateLimitedNextPageIsRetriedNotTreatedAsLastPage() throws Exception {
ajax = (pg, n) -> pg == 2 && n == 1 ? RATE_LIMITED : null;
ShareLinkInfo info = info(2, null);
List<FileInfo> list = list(info);
assertEquals(50, list.size());
assertEquals("p2-0", list.get(0).getFileId());
JsonObject pageInfo = FolderPaging.pageInfo(info);
assertTrue("zt=4 不能被当作末页", pageInfo.getBoolean("hasMore"));
assertEquals(2, ajaxCountByPg.get("2").get());
}
@Test
public void persistentRateLimitFailsWithRetryableErrorInsteadOfEmptyEnd() throws Exception {
ajax = (pg, n) -> pg == 2 ? RATE_LIMITED : null;
ShareLinkInfo info = info(2, null);
try {
list(info);
fail("zt=4 一直不恢复时必须报错,不能返回空列表或 hasMore=false");
} catch (ExecutionException e) {
String msg = e.getCause().getMessage();
assertTrue(msg, msg.contains("请刷新,重试0"));
assertTrue(msg, msg.contains("不完整"));
assertTrue(msg, msg.contains("稍后重试"));
}
assertNull(FolderPaging.pageInfo(info));
assertEquals(1 + LzTool.LZ_REFRESH_RETRIES, ajaxCountByPg.get("2").get());
}
@Test
public void cursorContinuesWithSameTokenWithoutReloadingPage() throws Exception {
ShareLinkInfo first = info(1, null);
list(first);
String cursor = FolderPaging.pageInfo(first).getString("nextCursor");
ShareLinkInfo second = info(2, cursor);
List<FileInfo> page2 = list(second);
assertEquals(50, page2.size());
assertEquals(1, pageGets.get());
MultiMap last = ajaxForms.get(ajaxForms.size() - 1);
assertEquals("2", last.get("pg"));
assertEquals(TOKEN_T, last.get("t"));
assertEquals(TOKEN_K, last.get("k"));
assertEquals("secret", last.get("pwd"));
ShareLinkInfo third = info(3, FolderPaging.pageInfo(second).getString("nextCursor"));
List<FileInfo> page3 = list(third);
assertEquals(9, page3.size());
JsonObject end = FolderPaging.pageInfo(third);
assertFalse(end.getBoolean("hasMore"));
assertNull(end.getString("nextCursor"));
assertNull(end.getValue("nextPage"));
Set<String> ids = new HashSet<>();
for (List<FileInfo> page : List.of(list(info(1, null)), page2, page3)) {
page.forEach(f -> assertTrue("跨页重复 " + f.getFileId(), ids.add(f.getFileId())));
}
assertEquals(49 + 50 + 9, ids.size());
}
@Test
public void rateLimitedCursorRequestRetriesSamePage() throws Exception {
ShareLinkInfo first = info(1, null);
list(first);
ajax = (pg, n) -> pg == 2 && n == 1 ? RATE_LIMITED : null;
ShareLinkInfo second = info(2, FolderPaging.pageInfo(first).getString("nextCursor"));
assertEquals(50, list(second).size());
assertTrue(FolderPaging.pageInfo(second).getBoolean("hasMore"));
assertEquals(1, pageGets.get());
}
@Test
public void pastLastPageIsEmptyAndEnds() throws Exception {
ajax = (pg, n) -> pg == 3 ? page(pg, 50) : pg == 4 ? "{\"zt\":2,\"info\":\"没有了\",\"text\":\"no file\"}" : null;
ShareLinkInfo third = info(3, null);
list(third);
ShareLinkInfo fourth = info(4, FolderPaging.pageInfo(third).getString("nextCursor"));
List<FileInfo> list = list(fourth);
assertTrue(list.isEmpty());
assertFalse(FolderPaging.pageInfo(fourth).getBoolean("hasMore"));
}
@Test
public void walkStopsAtShortPageWhenTargetIsBeyondEnd() throws Exception {
ShareLinkInfo info = info(5, null);
assertTrue(list(info).isEmpty());
assertFalse(FolderPaging.pageInfo(info).getBoolean("hasMore"));
assertEquals(null, ajaxCountByPg.get("4"));
}
@Test
public void deepPageWithoutCursorFailsFastWithHint() throws Exception {
ShareLinkInfo info = info(LzTool.LZ_MAX_WALK_PAGES + 1, null);
try {
list(info);
fail();
} catch (ExecutionException e) {
assertTrue(e.getCause().getMessage().contains("nextCursor"));
}
assertEquals(0, pageGets.get());
assertTrue(ajaxForms.isEmpty());
}
@Test
public void foreignCursorIsIgnored() throws Exception {
String foreign = LzFolderCursor.encode("bOTHER", "/filemoreajax.php?file=66477",
Map.of("fid", "66477", "t", "x", "k", "y"), 2, null);
ShareLinkInfo info = info(2, foreign);
assertEquals(50, list(info).size());
assertEquals(1, pageGets.get());
assertTrue(ajaxForms.stream().noneMatch(f -> "x".equals(f.get("t"))));
}
@Test
public void emptyFolderKeepsLegacyFailure() throws Exception {
ajax = (pg, n) -> "{\"zt\":2,\"info\":\"没有文件\",\"text\":\"no file\"}";
try {
list(info(null, null));
fail();
} catch (ExecutionException e) {
assertTrue(e.getCause().getMessage().contains("没有文件"));
}
}
private List<FileInfo> list(ShareLinkInfo info) throws Exception {
return new LzTool(info).parseFileList().toCompletionStage().toCompletableFuture().get(30, TimeUnit.SECONDS);
}
private ShareLinkInfo info(Integer page, String cursor) {
String url = "http://127.0.0.1:" + server.actualPort() + "/" + SHARE_KEY;
ShareLinkInfo info = ShareLinkInfo.newBuilder().type("lz").panName("蓝奏云").shareKey(SHARE_KEY)
.shareUrl(url).standardUrl(url).sharePassword("secret").build();
info.getOtherParam().put("domainName", "http://nfd.test");
if (page != null) {
info.getOtherParam().put(FolderPaging.PAGE, page);
}
if (cursor != null) {
info.getOtherParam().put(FolderPaging.CURSOR, cursor);
}
return info;
}
private static String folderHtml() {
return """
<html><body><div id="infos"></div>
<script type="text/javascript">
var pwd;
var pgs;
var ibb6kj = '%s';
var _h9imc = '%s';
pgs =1;
function file(){
$.ajax({
type : 'post',
url : '/filemoreajax.php?file=66477',
data : {
'lx':2,
'fid':66477,
'uid':'234978',
'pg':pgs,
'rep':'0',
't':ibb6kj,
'k':_h9imc,
'up':1,
'ls':1,
'pwd':pwd },
dataType : 'json'
});
}
</script></body></html>
""".formatted(TOKEN_T, TOKEN_K);
}
/** 默认三页:50(含一个 -1 占位)、50、9。 */
private static String defaultPage(int pg) {
return switch (pg) {
case 1, 2 -> page(pg, 50);
case 3 -> page(pg, 9);
default -> "{\"zt\":2,\"info\":\"没有了\",\"text\":\"no file\"}";
};
}
private static String page(int pg, int count) {
JsonArray text = new JsonArray();
for (int i = 0; i < count; i++) {
String id = pg == 1 && i == 10 ? "-1" : "p" + pg + "-" + i;
text.add(new JsonObject().put("icon", "apk").put("t", 0).put("id", id)
.put("name_all", id + ".apk").put("size", "1.0 M").put("time", "2023-03-08"));
}
return new JsonObject().put("zt", 1).put("info", "sucess").put("text", text).encode();
}
}
@@ -0,0 +1,230 @@
package cn.qaiu.parser.impl;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* 个性域名 a.lanzouw.com 不能被改写到 wwww.lanzoux.com(四个 w)。
* 部分出口连不上四 w,页面请求会超时;ajax 只把四 w 当作最后兜底。
*/
public class LzToolShareUrlTest {
@Test
public void personalDomainPageStaysOffWwww() {
String resolved = LzTool.resolveSharePageUrl(
"https://a.lanzouw.com/xxx",
"https://w1.lanzn.com/xxx",
"xxx");
assertEquals("https://a.lanzouw.com/xxx", resolved);
assertFalse(resolved.contains("wwww.lanzoux.com"));
}
@Test
public void folderPageKeepsOriginalHost() {
String resolved = LzTool.resolveSharePageUrl(
"https://a.lanzouw.com/b710887",
"https://w1.lanzn.com/b710887",
"b710887");
assertEquals("https://a.lanzouw.com/b710887", resolved);
}
@Test
public void nodeShareIsNotRewrittenToWwww() {
String resolved = LzTool.resolveSharePageUrl(
"https://wwn.lanzouy.com/ihLkw1gezutg",
"https://w1.lanzn.com/ihLkw1gezutg",
"ihLkw1gezutg");
assertEquals("https://wwn.lanzouy.com/ihLkw1gezutg", resolved);
}
@Test
public void webpageQueryStaysOnOriginalHost() {
String resolved = LzTool.resolveSharePageUrl(
"https://a.lanzouw.com/iabc?webpage=wp1&pwd=secret",
"https://w1.lanzn.com/iabc",
"iabc");
assertEquals("https://a.lanzouw.com/iabc?webpage=wp1", resolved);
}
@Test
public void placeholderUsesStandardHostNotWwww() {
assertEquals("https://w1.lanzn.com/", LzTool.SHARE_URL_PREFIX);
assertFalse(LzTool.SHARE_URL_PREFIX.contains("wwww"));
String resolved = LzTool.resolveSharePageUrl(
"https://w1.lanzn.com/-",
"https://w1.lanzn.com/-",
"iFileId");
assertEquals("https://w1.lanzn.com/iFileId", resolved);
assertFalse(resolved.contains("wwww.lanzoux.com"));
}
@Test
public void missingShareUrlKeepsRealStandardHost() {
String resolved = LzTool.resolveSharePageUrl(
null,
"https://www.lanzoux.com/iabc",
"iabc");
assertEquals("https://www.lanzoux.com/iabc", resolved);
}
@Test
public void ajaxFallbackOrderPutsWwwwLast() {
List<String> fallback = LzTool.AJAX_FALLBACK_ORIGINS;
assertEquals("https://w1.lanzn.com", fallback.get(0));
assertEquals("https://www.lanzoux.com", fallback.get(1));
assertEquals("https://wwww.lanzoux.com", fallback.get(fallback.size() - 1));
List<String> origins = LzTool.ajaxOrigins("https://a.lanzouw.com/xxx");
assertEquals("https://a.lanzouw.com", origins.get(0));
assertEquals("https://w1.lanzn.com", origins.get(1));
assertEquals("https://www.lanzoux.com", origins.get(2));
assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1));
assertTrue(origins.indexOf("https://wwww.lanzoux.com")
> origins.indexOf("https://w1.lanzn.com"));
}
@Test
public void ajaxOriginsDoNotDuplicateKnownHost() {
List<String> origins = LzTool.ajaxOrigins("https://www.lanzoux.com/iabc");
assertEquals(3, origins.size());
assertEquals("https://www.lanzoux.com", origins.get(0));
assertEquals("https://w1.lanzn.com", origins.get(1));
assertEquals("https://wwww.lanzoux.com", origins.get(2));
}
@Test
public void timeoutAjaxFallsBackButBusinessErrorDoesNot() {
assertTrue(LzTool.ajaxResponseShouldFallback("{\"zt\":0,\"inf\":\"已超时\"}"));
assertTrue(LzTool.ajaxResponseShouldFallback("{\"info\":\"请求超时\"}"));
assertTrue(LzTool.ajaxResponseShouldFallback(""));
assertTrue(LzTool.ajaxResponseShouldFallback("<html>blocked</html>"));
assertFalse(LzTool.ajaxResponseShouldFallback("{\"zt\":0,\"inf\":\"密码错误\"}"));
assertFalse(LzTool.ajaxResponseShouldFallback(
"{\"zt\":1,\"inf\":\"name.zip\",\"dom\":\"https://x\",\"url\":\"abc\"}"));
}
@Test
public void filePagePrefersExistingHostOverWwww() {
assertEquals("https://a.lanzouw.com/",
LzTool.sharePageHostBase("https://a.lanzouw.com/b123", "https://w1.lanzn.com/b123"));
assertEquals("https://w1.lanzn.com/",
LzTool.sharePageHostBase("https://w1.lanzn.com/-", "https://w1.lanzn.com/-"));
assertFalse(LzTool.sharePageHostBase("https://a.lanzouw.com/b123", null).contains("wwww"));
}
@Test
public void absoluteAjaxUrlIsKeptAndTriedFirst() {
String html = """
url : 'https://apifile.lanzouw.com/ajaxfile.php?file=320665771',
data : { 'action':'downprocess','sign':isngis,'kd':kdns,'p':pwd, },
""";
String target = LzTool.fileAjaxTarget(html);
assertEquals("https://apifile.lanzouw.com/ajaxfile.php?file=320665771", target);
List<String> origins = LzTool.fileAjaxOrigins(
"https://wwaqg.lanzouu.com/iqouM49vy9ib", target);
assertEquals("https://apifile.lanzouw.com", origins.get(0));
assertTrue(origins.contains("https://wwaqg.lanzouu.com"));
assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1));
assertTrue(origins.indexOf("https://apifile.lanzouw.com")
< origins.indexOf("https://wwaqg.lanzouu.com"));
assertTrue(origins.indexOf("https://wwww.lanzoux.com")
> origins.indexOf("https://w1.lanzn.com"));
assertEquals(1, origins.stream().filter("https://apifile.lanzouw.com"::equals).count());
}
@Test
public void protocolRelativeAjaxBecomesHttps() {
String html = "url : '//apifile.lanzouw.com/ajaxfile.php?file=9',";
assertEquals("https://apifile.lanzouw.com/ajaxfile.php?file=9", LzTool.fileAjaxTarget(html));
}
@Test
public void absoluteAjaxWinsOverRelativePathInSamePage() {
String html = """
//data : { url : '/ajaxfile.php?file=1' }
url : "https://apifile.lanzouw.com/ajaxm.php?file=42",
""";
assertEquals("https://apifile.lanzouw.com/ajaxm.php?file=42", LzTool.fileAjaxTarget(html));
}
@Test
public void relativeFileAjaxFallsThroughToApifileBeforeWwww() {
String html = "url : '/ajaxfile.php?file=150233466',";
assertEquals("/ajaxfile.php?file=150233466", LzTool.fileAjaxTarget(html));
List<String> origins = LzTool.fileAjaxOrigins("https://a.lanzouw.com/xxx", LzTool.fileAjaxTarget(html));
assertEquals("https://a.lanzouw.com", origins.get(0));
assertEquals("https://apifile.lanzouw.com", origins.get(1));
assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1));
assertTrue(origins.indexOf("https://apifile.lanzouw.com")
< origins.indexOf("https://wwww.lanzoux.com"));
assertFalse(LzTool.ajaxOrigins("https://a.lanzouw.com/xxx").contains("https://apifile.lanzouw.com"));
}
@Test
public void oldFolderPageSuppliesFilemoreParameters() {
String html = """
<script type="text/javascript">
var ibb6kj = '111';
var demoKey = 'abc';
function file(){
$.ajax({
url : '/filemoreajax.php?file=66477',
data : {
'lx':2,
'fid':66477,
'uid':'11',
'pg':pgs,
't':ibb6kj,
'k':demoKey,
'up':1,
'pwd':pwd
}
});
}
</script>
""";
Map<String, String> form = LzTool.folderAjaxForm(html, "1234");
assertEquals("66477", form.get("fid"));
assertEquals("111", form.get("t"));
assertEquals("abc", form.get("k"));
assertEquals("1", form.get("pg"));
assertEquals("1234", form.get("pwd"));
assertEquals("/filemoreajax.php?file=66477", LzTool.folderAjaxPath(html, "1234"));
assertFalse(LzTool.isAccessRiskPage(html));
}
@Test
public void blankOffPageIsRiskControlNotExpiry() {
String html = """
<div class="off"><div class="off0"><div class="off1"></div></div></div>
<div style="display:none ">folder66477ufolder66477ip203.0.113.8</div>
""";
assertTrue(LzTool.isAccessRiskPage(html));
assertNull(LzTool.folderAjaxForm(html, null));
String cancelled = """
<div class="off"><div class="off1"></div></div>
文件取消分享了
""";
assertFalse(LzTool.isAccessRiskPage(cancelled));
}
@Test
public void missingAjaxTargetStillPutsApifileBeforeWwww() {
List<String> origins = LzTool.fileAjaxOrigins("https://www.lanzoux.com/ihLkw1gezutg", null);
assertEquals("https://www.lanzoux.com", origins.get(0));
assertEquals("https://apifile.lanzouw.com", origins.get(1));
assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1));
assertFalse(origins.get(0).contains("wwww"));
}
}
@@ -0,0 +1,58 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import io.vertx.core.Vertx;
import org.junit.Assume;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* 对 Issue #282 的分享做一次真实访客解析。
* 默认不跑:父 POM surefire skipTests=true,且本测试还要求 -Dquark.live=true。
* mvn -pl parser -DskipTests=false -Dquark.live=true -Dtest=QkToolGuestFolderLiveTest test
*/
public class QkToolGuestFolderLiveTest {
@Test
public void issue282FolderShareResolvesAnonymously() throws Exception {
Assume.assumeTrue("set -Dquark.live=true to call Quark", Boolean.getBoolean("quark.live"));
Vertx vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
QkTool tool = null;
try {
ShareLinkInfo info = ShareLinkInfo.newBuilder()
.type("qk")
.panName("夸克网盘")
.shareKey("d34c18e9d62a")
.shareUrl("https://pan.quark.cn/s/d34c18e9d62a")
.build();
tool = new QkTool(info);
String url = tool.parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
assertNotNull(url);
assertTrue(url.startsWith("http"));
FileInfo fileInfo = (FileInfo) info.getOtherParam().get("fileInfo");
assertNotNull(fileInfo);
assertNotNull(fileInfo.getFileName());
assertTrue(fileInfo.getSize() > 0);
if (fileInfo.getSize() > QuarkFamilyDownloadPolicy.NORMAL_PARSE_MAX_BYTES) {
assertTrue("large file should be a public dl-c url, got " + url, url.contains("dl-c-"));
assertTrue(url.contains("filename="));
assertFalse(url.contains("dl-guest"));
} else {
assertTrue("guest download host, got " + url, url.contains("dl-guest"));
}
} finally {
if (tool != null) {
tool.close();
}
vertx.close().toCompletionStage().toCompletableFuture().get(15, TimeUnit.SECONDS);
}
}
}
@@ -0,0 +1,112 @@
package cn.qaiu.parser.impl;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* 夸克目录项分类与访客选文件。不访问网络。
* 父 POM 的 surefire 默认 skipTests=true,本地验证用:
* mvn -pl parser -DskipTests=false -Dtest=QkToolShareListTest test
*/
public class QkToolShareListTest {
@Test
public void folderIsNotADownloadableFile() {
JsonObject folder = new JsonObject()
.put("file", false)
.put("dir", true)
.put("file_type", 0)
.put("file_name", "BiliTools最新版");
assertTrue(QkTool.isQuarkFolder(folder));
assertFalse(QkTool.isQuarkFile(folder));
}
@Test
public void archiveAndInstallerCountAsFiles() {
JsonObject rar = new JsonObject()
.put("file", true)
.put("dir", false)
.put("file_type", 1)
.put("obj_category", "archive")
.put("size", 8228);
JsonObject exe = new JsonObject()
.put("file", true)
.put("dir", false)
.put("file_type", 1)
.put("obj_category", "default")
.put("size", 11919276);
assertTrue(QkTool.isQuarkFile(rar));
assertTrue(QkTool.isQuarkFile(exe));
assertFalse(QkTool.isQuarkFolder(rar));
}
@Test
public void directoryFlagWinsOverCategory() {
JsonObject odd = new JsonObject()
.put("file", false)
.put("dir", true)
.put("file_type", 0)
.put("obj_category", "default");
assertTrue(QkTool.isQuarkFolder(odd));
assertFalse(QkTool.isQuarkFile(odd));
}
@Test
public void guestOrderKeepsFirstFileThenSortsTheRestBySize() {
JsonObject large = file("large", 90_000_000L);
JsonObject mid = file("mid", 20_000_000L);
JsonObject small = file("small", 8_000L);
List<JsonObject> ordered = QkTool.orderGuestCandidates(List.of(large, mid, small));
assertEquals("large", ordered.get(0).getString("file_name"));
assertEquals("small", ordered.get(1).getString("file_name"));
assertEquals("mid", ordered.get(2).getString("file_name"));
}
@Test
public void sizeLimitIsTransferFallbackAndLoginIsNot() {
assertTrue(QkTool.needsTransferFallback(new RuntimeException(
"分享直链获取失败(code=23018): download file size limit")));
assertFalse(QkTool.needsTransferFallback(new RuntimeException("未登录或 Cookie 已失效")));
assertTrue(QkTool.isGuestAuthError(new RuntimeException("code=31001 未登录")));
assertFalse(QkTool.isGuestAuthError(new RuntimeException("code=23018 size limit")));
}
@Test
public void violationCodeIsExplainedWithoutFolderWording() {
JsonObject json = new JsonObject().put("code", 41010).put("message", "文件涉及违规内容");
String msg = QkTool.quarkApiFailure("https://drive-pc.quark.cn/token", json);
assertTrue(msg.contains("违规"));
assertTrue(msg.contains("41010"));
assertFalse(msg.contains("都是文件夹"));
}
@Test
public void zeroBytePlaceholderIsDroppedWhenARealFileExists() {
JsonObject placeholder = file("等待更新", 0L);
JsonObject real = file("notes.rar", 8228L);
List<JsonObject> kept = QkTool.preferSizedFiles(List.of(placeholder, real));
assertEquals(1, kept.size());
assertEquals("notes.rar", kept.get(0).getString("file_name"));
assertTrue(QkTool.hasPositiveSize(List.of(real)));
assertFalse(QkTool.hasPositiveSize(List.of(placeholder)));
assertEquals(1, QkTool.preferSizedFiles(List.of(placeholder)).size());
}
@Test
public void oversizeHintPointsAtCookie() {
assertTrue(QkTool.GUEST_OVERSIZE_MSG.contains("auths.qk.cookie"));
assertTrue(QkTool.GUEST_OVERSIZE_MSG.contains("23018"));
assertFalse(QkTool.GUEST_OVERSIZE_MSG.contains("都是文件夹"));
assertTrue(QkTool.GUEST_LOGIN_MSG.contains("auths.qk.cookie"));
}
private static JsonObject file(String name, long size) {
return new JsonObject().put("file_name", name).put("size", size).put("file", true);
}
}
@@ -0,0 +1,414 @@
package cn.qaiu.parser.impl;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.impl.QuarkFamilyDownloadPolicy.Membership;
import cn.qaiu.parser.impl.QuarkFamilyDownloadPolicy.ProbeHit;
import cn.qaiu.util.QuarkAccountScope;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.WebClient;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* 夸克 / UC 大文件策略。会员、体积、文件名和响应分类不访问网盘。
* 本地 HTTP 只验证探测不会收完整文件,以及 HTML / JSON 不会被当成下载。
*/
public class QuarkFamilyDownloadPolicyTest {
private static final long NOW = 1_700_000_000_000L;
private static final String SECRET = "__pus=super-secret-cookie; __puus=another-secret";
private static Vertx vertx;
private static HttpServer server;
private static WebClient client;
private static int port;
@BeforeClass
public static void startServer() throws Exception {
vertx = Vertx.vertx();
client = WebClient.create(vertx);
CountDownLatch latch = new CountDownLatch(1);
server = vertx.createHttpServer().requestHandler(req -> {
String path = req.path();
if ("/member-valid".equals(path)) {
req.response().putHeader("Content-Type", "application/json")
.end(new JsonObject().put("code", 0).put("data", new JsonObject()
.put("member_type", "SUPER_VIP").put("exp_at", 4_102_416_000_000L)).encode());
} else if ("/member-auth".equals(path)) {
req.response().putHeader("Content-Type", "application/json")
.end(new JsonObject().put("code", 31001).put("message", "未登录").encode());
} else if ("/member-html".equals(path)) {
req.response().putHeader("Content-Type", "text/html").end("<html>login</html>");
} else if ("/preview-html".equals(path)) {
req.response().putHeader("Content-Type", "text/html; charset=utf-8")
.end("<!DOCTYPE html><html><body>preview page</body></html>");
} else if ("/preview-missing".equals(path)) {
req.response().putHeader("Content-Type", "application/json")
.end(new JsonObject().put("code", 0).put("data", new JsonObject()).encode());
} else if ("/preview-page".equals(path)) {
req.response().putHeader("Content-Type", "application/json")
.end(new JsonObject().put("code", 0).put("data", new JsonObject()
.put("download_url", "https://vt.quark.cn/preview?foo=1")).encode());
} else if ("/zip".equals(path)) {
byte[] body = new byte[256 * 1024];
body[0] = 'P';
body[1] = 'K';
req.response().putHeader("Content-Type", "application/zip")
.putHeader("Content-Length", Integer.toString(body.length))
.end(Buffer.buffer(body));
} else if ("/html-file".equals(path)) {
req.response().putHeader("Content-Type", "text/html")
.end("<html><body>not a file</body></html>");
} else if ("/json-file".equals(path)) {
req.response().putHeader("Content-Type", "application/json")
.end("{\"code\":412,\"message\":\"html-not-file\"}");
} else if ("/empty".equals(path)) {
req.response().putHeader("Content-Type", "text/plain").putHeader("Content-Length", "0").end();
} else if ("/redirect".equals(path)) {
req.response().setStatusCode(302).putHeader("Location", "https://pan.quark.cn/login").end();
} else {
req.response().setStatusCode(404).end();
}
});
server.listen(0).onComplete(ar -> {
if (ar.succeeded()) {
port = ar.result().actualPort();
}
latch.countDown();
});
assertTrue(latch.await(10, TimeUnit.SECONDS));
assertTrue(port > 0);
}
@AfterClass
public static void stopServer() {
if (client != null) {
client.close();
}
if (server != null) {
server.close();
}
if (vertx != null) {
vertx.close();
}
}
@Test
public void thresholdKeepsEqualSizeOnNormalPath() {
long limit = QuarkFamilyDownloadPolicy.NORMAL_PARSE_MAX_BYTES;
assertEquals(10L * 1024 * 1024, limit);
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(0));
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(limit - 1));
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(limit));
assertTrue(QuarkFamilyDownloadPolicy.knownLarge(limit + 1));
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(Long.MAX_VALUE));
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(-1));
assertEquals(limit, QuarkFamilyDownloadPolicy.sizeOf(new JsonObject().put("size", limit)));
assertEquals(Long.MAX_VALUE, QuarkFamilyDownloadPolicy.sizeOf(new JsonObject()));
}
@Test
public void membershipRequiresTierAndFutureExpiry() {
assertTrue(judge("SUPER_VIP", NOW + 1).validPaid);
assertTrue(judge("VIP", NOW + 60_000).validPaid);
assertTrue(judge("EXP_SVIP", NOW + 60_000).validPaid);
assertTrue(judge("EXP_VIP", NOW + 60_000).validPaid);
assertTrue(judge("Z_VIP", NOW + 60_000).validPaid);
assertTrue(judge("vip", NOW + 1).validPaid);
Membership expired = judge("SUPER_VIP", NOW);
assertFalse(expired.validPaid);
assertTrue(expired.reason.contains("过期"));
Membership past = judge("VIP", NOW - 1);
assertFalse(past.validPaid);
Membership normal = judge("NORMAL", NOW + 60_000);
assertFalse(normal.validPaid);
assertTrue(normal.reason.contains("不是"));
Membership unknown = judge("MINI", NOW + 60_000);
assertFalse(unknown.validPaid);
Membership noType = QuarkFamilyDownloadPolicy.judgeMembership(new JsonObject().put("exp_at", NOW + 1), NOW);
assertFalse(noType.validPaid);
assertTrue(noType.reason.contains("member_type"));
Membership noExp = QuarkFamilyDownloadPolicy.judgeMembership(new JsonObject().put("member_type", "SVIP"), NOW);
assertFalse(noExp.validPaid);
Membership missingExp = QuarkFamilyDownloadPolicy.judgeMembership(
new JsonObject().put("member_type", "SUPER_VIP"), NOW);
assertFalse(missingExp.validPaid);
assertTrue(missingExp.reason.contains("exp_at"));
long seconds = (NOW + 5_000) / 1000;
assertTrue(QuarkFamilyDownloadPolicy.judgeMembership(new JsonObject()
.put("member_type", "VIP").put("exp_at", seconds), NOW).validPaid);
assertNull(QuarkFamilyDownloadPolicy.judgeMembership(null, NOW).memberType);
}
@Test
public void memberHttpAuthHtmlAndMissingCookieAreNotPaid() throws Exception {
Membership valid = await(QuarkFamilyDownloadPolicy.fetchMembership(client, cookieHeaders(),
url("/member-valid"), false));
assertTrue(valid.validPaid);
assertEquals("SUPER_VIP", valid.memberType);
Membership auth = await(QuarkFamilyDownloadPolicy.fetchMembership(client, cookieHeaders(),
url("/member-auth"), true));
assertFalse(auth.validPaid);
assertTrue(auth.reason.contains("31001"));
Membership html = await(QuarkFamilyDownloadPolicy.fetchMembership(client, cookieHeaders(),
url("/member-html"), true));
assertFalse(html.validPaid);
assertTrue(html.reason.contains("HTML"));
Membership missing = await(QuarkFamilyDownloadPolicy.fetchMembership(client, MultiMap.caseInsensitiveMultiMap(),
url("/member-valid"), false));
assertFalse(missing.validPaid);
assertTrue(missing.reason.contains("未配置"));
assertFalse(missing.reason.contains("super-secret"));
}
@Test
public void previewHtmlMissingAndWebpageAreNotDownloads() throws Exception {
String html = awaitFailure(client.getAbs(url("/preview-html")).send()
.compose(res -> QuarkFamilyDownloadPolicy.interpretPreview(res, "qk", false)));
assertTrue(html.contains("HTML"));
String missing = awaitFailure(client.getAbs(url("/preview-missing")).send()
.compose(res -> QuarkFamilyDownloadPolicy.interpretPreview(res, "uc", false)));
assertTrue(missing.contains("download_url"));
String page = await(client.getAbs(url("/preview-page")).send()
.compose(res -> QuarkFamilyDownloadPolicy.interpretPreview(res, "qk", false)));
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl(page, "qk"));
assertTrue(page.contains("vt.quark.cn"));
}
@Test
public void publicCdnHostsAreSeparateForQuarkAndUc() {
String quark = "https://dl-c-zb-u.drive.quark.cn/a/b?auth_key=1&sp=100&token=t&abt=9";
String uc = "https://dl-c-zb.drive.uc.cn/a/b?auth_key=1&sp=100&token=t";
assertTrue(QuarkFamilyDownloadPolicy.isPublicFileUrl(quark, "qk"));
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl(quark, "uc"));
assertTrue(QuarkFamilyDownloadPolicy.isPublicFileUrl(uc, "uc"));
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl(uc, "qk"));
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://dl-c-sz.u-drive.quark.cn/a", "qk"));
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://dl-pc.sz.drive.quark.cn/a", "qk"));
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://dl-guest-1.drive.quark.cn/a", "qk"));
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://vt.quark.cn/preview", "qk"));
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://drive.uc.cn/s/abc", "uc"));
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("http://dl-c-zb.drive.uc.cn/a", "uc"));
}
@Test
public void filenameUsesUtf8AndDropsTrackingParams() throws Exception {
String raw = "https://dl-c-zb.drive.quark.cn/a/b?auth_key=9&abt=1&sp=100&token=abc&filename=old";
String bare = QuarkFamilyDownloadPolicy.bareFileUrl(raw);
assertFalse(bare.contains("abt="));
assertFalse(bare.contains("filename="));
String named = QuarkFamilyDownloadPolicy.withFilename(bare, "报告 (1).zip");
assertTrue(named.contains("filename="));
assertFalse(named.contains("报告"));
String value = named.substring(named.indexOf("filename=") + "filename=".length());
assertEquals("报告 (1).zip", URLDecoder.decode(value, StandardCharsets.UTF_8));
assertFalse(value.contains(" "));
assertFalse(value.contains("+"));
String fromAccount = QuarkFamilyDownloadPolicy.presentPublicDownload(raw, "qk", "报告 (1).zip");
assertTrue(fromAccount.contains("filename="));
assertFalse(fromAccount.contains("abt="));
assertEquals("https://dl-pc.sz.drive.quark.cn/a?auth_key=1",
QuarkFamilyDownloadPolicy.presentPublicDownload(
"https://dl-pc.sz.drive.quark.cn/a?auth_key=1", "qk", "a.zip"));
}
@Test
public void videoPickerKeepsProgressiveFileAndDropsPlaylist() {
JsonObject data = new JsonObject().put("video_list", new JsonArray()
.add(new JsonObject().put("video_info", new JsonObject()
.put("width", 1920)
.put("url", "https://dl-c-zb.drive.quark.cn/high.m3u8?auth_key=1&token=t")))
.add(new JsonObject().put("video_info", new JsonObject()
.put("width", 1280)
.put("url", "https://dl-pc.sz.drive.quark.cn/login.mp4?auth_key=1")))
.add(new JsonObject().put("video_info", new JsonObject()
.put("width", 640)
.put("url", "https://dl-c-sz.drive.quark.cn/low.mp4?auth_key=2&token=t&abt=1"))));
assertEquals("https://dl-c-sz.drive.quark.cn/low.mp4?auth_key=2&token=t&abt=1",
QuarkFamilyDownloadPolicy.pickProgressiveFileUrl(data, "qk"));
assertEquals("", QuarkFamilyDownloadPolicy.pickProgressiveFileUrl(new JsonObject()
.put("download_url", "https://pan.quark.cn/s/abc"), "qk"));
}
@Test
public void probeRejectsHtmlJsonAndEmptyAndCapsZipPrefix() throws Exception {
ProbeHit zip = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/zip"), "qk", 1));
assertTrue(zip.ok);
assertTrue(zip.prefixLength > 0);
assertTrue(zip.prefixLength <= 64);
ProbeHit html = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/html-file"), "qk", 1));
assertFalse(html.ok);
assertTrue(html.reason.contains("HTML"));
ProbeHit json = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/json-file"), "uc", 1));
assertFalse(json.ok);
assertTrue(json.reason.contains("JSON"));
ProbeHit empty = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/empty"), "qk", 1));
assertFalse(empty.ok);
ProbeHit redirect = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/redirect"), "qk", 1));
assertFalse(redirect.ok);
assertTrue(redirect.reason.contains("不是公开文件"));
ProbeHit rangedHtml = QuarkFamilyDownloadPolicy.judgeProbe(206, "text/html", "bytes 0-0/9", "1",
Buffer.buffer("<html>"));
assertFalse(rangedHtml.ok);
ProbeHit rangedZip = QuarkFamilyDownloadPolicy.judgeProbe(206, "application/zip", "bytes 0-15/99", null,
Buffer.buffer("PK"));
assertTrue(rangedZip.ok);
ProbeHit denied = QuarkFamilyDownloadPolicy.judgeProbe(412, "text/html", null, null, Buffer.buffer("<html>"));
assertFalse(denied.ok);
assertTrue(denied.reason.contains("412"));
}
@Test
public void errorsStayActionableAndHideSecrets() {
RuntimeException leaked = new RuntimeException("失败 cookie=" + SECRET + " <html>login</html>");
String uc = QuarkFamilyDownloadPolicy.largeFileError("uc", leaked,
new IllegalStateException("H5 预览没有 download_url"));
String qk = QuarkFamilyDownloadPolicy.largeFileError("qk", null,
new IllegalStateException("<!DOCTYPE html>"));
assertTrue(uc.contains("不能免登录"));
assertTrue(uc.contains("auths.uc.cookie"));
assertTrue(uc.contains("10MiB"));
assertFalse(uc.contains("super-secret"));
assertFalse(uc.contains("<html"));
assertTrue(qk.contains("auths.qk.cookie"));
assertTrue(qk.contains("HTML"));
assertFalse(qk.contains("免登录下载"));
}
@Test
public void publicDirectDropsAccountHeaders() {
Map<String, String> headers = new LinkedHashMap<>();
headers.put("cookie", SECRET);
headers.put("Referer", "https://pan.quark.cn/");
assertFalse(QuarkFamilyDownloadPolicy.prepareDownloader(headers, true, true));
assertTrue(headers.isEmpty());
Map<String, String> account = new LinkedHashMap<>();
account.put("cookie", "account-cookie");
assertTrue(QuarkFamilyDownloadPolicy.prepareDownloader(account, true, false));
assertEquals("account-cookie", account.get("cookie"));
}
@Test
public void accountCacheScopeDoesNotReuseAnotherCookie() {
Map<String, Object> guest = new HashMap<>();
assertNull(QuarkAccountScope.suffix(guest));
Map<String, Object> first = authParam(SECRET);
Map<String, Object> second = authParam("__pus=other-account; __uid=2");
Map<String, Object> same = authParam(SECRET);
String a = QuarkAccountScope.suffix(first);
String b = QuarkAccountScope.suffix(second);
assertEquals(a, QuarkAccountScope.suffix(same));
assertNotEquals(a, b);
assertFalse(a.contains("super-secret"));
assertFalse(b.contains("__pus"));
ShareLinkInfo guestInfo = share("qk", guest);
ShareLinkInfo accountInfo = share("qk", first);
ShareLinkInfo otherInfo = share("UC", second);
assertEquals("qk:key", guestInfo.getCacheKey());
assertTrue(accountInfo.getCacheKey().startsWith("qk:key#"));
assertNotEquals(accountInfo.getCacheKey(), otherInfo.getCacheKey().replace("UC:", "qk:"));
assertFalse(accountInfo.getCacheKey().contains("super-secret"));
assertFalse(otherInfo.getCacheKey().contains("other-account"));
}
private static Membership judge(String type, long expAt) {
return QuarkFamilyDownloadPolicy.judgeMembership(new JsonObject()
.put("member_type", type).put("exp_at", expAt), NOW);
}
private static MultiMap cookieHeaders() {
return MultiMap.caseInsensitiveMultiMap().set("cookie", SECRET);
}
private static String url(String path) {
return "http://127.0.0.1:" + port + path;
}
private static Map<String, Object> authParam(String cookie) {
MultiMap auths = MultiMap.caseInsensitiveMultiMap().set("cookie", cookie);
Map<String, Object> other = new HashMap<>();
other.put("auths", auths);
return other;
}
private static ShareLinkInfo share(String type, Map<String, Object> other) {
ShareLinkInfo info = ShareLinkInfo.newBuilder().type(type).shareKey("key").build();
info.setOtherParam(other);
return info;
}
private static <T> T await(io.vertx.core.Future<T> future) throws Exception {
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<T> value = new AtomicReference<>();
AtomicReference<Throwable> error = new AtomicReference<>();
future.onComplete(ar -> {
if (ar.succeeded()) {
value.set(ar.result());
} else {
error.set(ar.cause());
}
latch.countDown();
});
assertTrue(latch.await(10, TimeUnit.SECONDS));
if (error.get() != null) {
throw new AssertionError(error.get().getMessage(), error.get());
}
return value.get();
}
private static String awaitFailure(io.vertx.core.Future<?> future) throws Exception {
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<Throwable> error = new AtomicReference<>();
future.onComplete(ar -> {
if (ar.failed()) {
error.set(ar.cause());
}
latch.countDown();
});
assertTrue(latch.await(10, TimeUnit.SECONDS));
assertTrue(error.get() != null);
return error.get().getMessage() == null ? "" : error.get().getMessage();
}
}
@@ -0,0 +1,40 @@
package cn.qaiu.parser.impl;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* 123 登录提示。不访问网络。
* mvn -pl parser -DskipTests=false -Dtest=Ye2LoginHintTest test
*/
public class Ye2LoginHintTest {
@Test
public void loginCodesAndMessagesAreRecognized() {
assertTrue(Ye2Tool.isYeLoginRequired(5112, "您需要注册登录或付费后下载"));
assertTrue(Ye2Tool.isYeLoginRequired(401, "请登录后下载"));
assertTrue(Ye2Tool.isYeLoginRequired(0, "需要登录才能下载"));
assertFalse(Ye2Tool.isYeLoginRequired(0, "ok"));
assertFalse(Ye2Tool.isYeLoginRequired(null, null));
}
@Test
public void missingAuthTellsUserToConfigureLocalAuthorization() {
String msg = Ye2Tool.loginRequiredDownloadMessage(false, null);
assertTrue(msg.contains("auths.ye.authorization"));
assertTrue(msg.contains("5112"));
assertTrue(msg.contains("公共云解析"));
assertTrue(msg.contains("ye:分享key@提取码"));
assertFalse(msg.contains("验证码求解"));
}
@Test
public void configuredAuthStillPointsAtLocalTokenWhenUpstreamRejects() {
String msg = Ye2Tool.loginRequiredDownloadMessage(true, "请登录后下载");
assertTrue(msg.contains("auths.ye.authorization"));
assertTrue(msg.contains("上游信息: 请登录后下载"));
assertFalse(msg.contains("{"));
}
}
@@ -0,0 +1,121 @@
package cn.qaiu.parser.impl;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* 永硕入口页解析与重定向的离线测试,不访问网络。
*/
public class YsToolPasswordPageTest {
private static final String NEW_GATE = ""
+ "<div id=\"entryConfig\" style=\"display:none\" data-dlmc=\"qaiu\"\n"
+ " data-verification-token=\"new-token_value.1\"></div>\n"
+ "<form id=\"loginForm\"></form>\n";
private static final String OLD_GATE = ""
+ "<script>var cfg = { RequestVerificationToken': 'legacy-token' };</script>\n"
+ "<div id=\"loginPopup\"></div>\n"
+ "<form action=\"/?handler=VerifyPassword\"></form>\n";
private static final String OPEN_SPACE = ""
+ "<script>window.htxx = {\"dlmc\":\"fufu1\",\"qqdz\":\"https://c6.ysepan.com/api/\","
+ "\"yh\":{\"isgly\":false},\"ym\":\"ysepan.com\"};</script>";
@Test
public void testNewPasswordPageTokenAndDlmc() {
assertTrue(YsTool.isPasswordPage(NEW_GATE));
assertEquals("new-token_value.1", YsTool.extractAntiforgery(NEW_GATE));
assertEquals("qaiu", YsTool.extractDlmc(NEW_GATE));
assertNull(YsTool.extractHtxx(NEW_GATE));
}
@Test
public void testLegacyPasswordPageStillParsed() {
assertTrue(YsTool.isPasswordPage(OLD_GATE));
assertEquals("legacy-token", YsTool.extractAntiforgery(OLD_GATE));
assertNull(YsTool.extractDlmc(OLD_GATE));
}
@Test
public void testNewTokenWinsWhenBothFormatsExist() {
String mixed = NEW_GATE + OLD_GATE;
assertEquals("new-token_value.1", YsTool.extractAntiforgery(mixed));
}
@Test
public void testSingleQuotedAttributes() {
String html = "<div id='entryConfig' data-dlmc='sohehe4' "
+ "data-verification-token='quoted-token'></div>";
assertTrue(YsTool.isPasswordPage(html));
assertEquals("quoted-token", YsTool.extractAntiforgery(html));
assertEquals("sohehe4", YsTool.extractDlmc(html));
}
@Test
public void testOpenSpaceIsNotPasswordPageAndKeepsNestedHtxx() {
assertFalse(YsTool.isPasswordPage(OPEN_SPACE));
JsonObject htxx = YsTool.extractHtxx(OPEN_SPACE);
assertEquals("fufu1", htxx.getString("dlmc"));
assertEquals("https://c6.ysepan.com/api/", htxx.getString("qqdz"));
assertFalse(htxx.getJsonObject("yh").getBoolean("isgly"));
}
@Test
public void testYs168RedirectTargetsYsepanPasswordEndpoint() {
String next = YsTool.resolveRedirect("https://qaiu.ys168.com/", "https://qaiu.ysepan.com");
assertEquals("https://qaiu.ysepan.com", next);
assertEquals("https://qaiu.ysepan.com", YsTool.originOf(next));
assertEquals("https://qaiu.ysepan.com/?handler=VerifyPassword",
YsTool.verifyPasswordEndpoint(YsTool.originOf(next)));
assertFalse(YsTool.verifyPasswordEndpoint(YsTool.originOf(next)).contains("ys168.com"));
}
@Test
public void testProtocolRelativeAndRelativeRedirects() {
String protocolRelative = YsTool.resolveRedirect(
"https://qaiu.ys168.com/", "//qaiu.ysepan.com/");
assertEquals("https://qaiu.ysepan.com/", protocolRelative);
assertEquals("https://qaiu.ysepan.com", YsTool.originOf(protocolRelative));
String relative = YsTool.resolveRedirect(
"https://qaiu.ysupan.com/", "/login.aspx?d=qaiu");
assertEquals("https://qaiu.ysupan.com/login.aspx?d=qaiu", relative);
assertEquals("https://qaiu.ysupan.com", YsTool.originOf(relative));
}
@Test
public void testNonDefaultPortKeptInOrigin() {
assertEquals("https://y.ys168.com:8100", YsTool.originOf("https://y.ys168.com:8100/"));
assertEquals("https://qaiu.ysepan.com", YsTool.originOf("https://qaiu.ysepan.com:443/"));
}
@Test
public void testWrongPasswordUsesUpstreamMessageWithoutSecrets() {
String body = "{\"success\":false,\"code\":\"invalid_password\",\"message\":\"密码错误\"}";
assertEquals("密码错误", YsTool.passwordFailureMessage(400, body));
String leaked = "{\"success\":false,\"code\":\"invalid_password\",\"message\":\"eyJhbGciOiJIUzI1NiJ9.secret\"}";
assertEquals("密码错误", YsTool.passwordFailureMessage(400, leaked));
String other = "{\"success\":false,\"message\":\"空间已关闭\"}";
assertEquals("空间已关闭", YsTool.passwordFailureMessage(400, other));
assertEquals("密码验证失败 HTTP 500", YsTool.passwordFailureMessage(500, "<html>CfDJ8secret</html>"));
assertEquals("密码验证失败 HTTP 400", YsTool.passwordFailureMessage(400, ""));
}
@Test
public void testBlankRedirectIsRejected() {
assertNull(YsTool.resolveRedirect("https://qaiu.ys168.com/", " "));
assertNull(YsTool.resolveRedirect("https://qaiu.ys168.com/", null));
assertNull(YsTool.originOf("not a url"));
assertFalse(YsTool.isPasswordPage(null));
assertNull(YsTool.extractAntiforgery(null));
}
}
@@ -0,0 +1,431 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.parser.PanDomainTemplate;
import cn.qaiu.parser.ParserCreate;
import cn.qaiu.util.CommonUtils;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.WebClient;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.*;
/**
* 永硕E盘解析测试(含示例空间联调 + 真实下载校验)
*/
public class YsToolTest {
private static Vertx vertx;
private static WebClient webClient;
@BeforeClass
public static void setUpClass() {
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
webClient = WebClient.create(vertx);
}
@AfterClass
public static void tearDownClass() {
if (webClient != null) {
webClient.close();
}
if (vertx != null) {
vertx.close();
}
}
@Test
public void testPatternMatching() {
Pattern pattern = PanDomainTemplate.YS.getPattern();
Matcher m1 = pattern.matcher("https://qaiu.ysepan.com/");
assertTrue(m1.matches());
assertEquals("qaiu", m1.group("KEY"));
Matcher m2 = pattern.matcher("http://sohehe4.ysepan.com");
assertTrue(m2.matches());
assertEquals("sohehe4", m2.group("KEY"));
Matcher m3 = pattern.matcher("https://demo.ys168.com/");
assertTrue(m3.matches());
assertEquals("demo", m3.group("KEY"));
assertTrue(pattern.matcher("https://a.cccpan.com/").matches());
assertTrue(pattern.matcher("https://a.ysupan.com").matches());
assertTrue(pattern.matcher("https://a.uupan.net/").matches());
assertTrue(pattern.matcher("https://a.ysok.net").matches());
assertFalse(pattern.matcher("https://www.ysepan.com/").matches());
assertFalse(pattern.matcher("https://c6.ysepan.com/api/ml/mldq").matches());
assertFalse(pattern.matcher("https://ys-c.ysepan.com/wap/qaiu/x/y/z").matches());
assertFalse(pattern.matcher("https://zy.ysepan.com/assets/index.js").matches());
assertFalse(pattern.matcher("https://qaiu.evil.com/").matches());
}
@Test
public void testIdentifyShareUrl() {
ParserCreate create = ParserCreate.fromShareUrl("https://qaiu.ysepan.com/");
assertEquals("ys", create.getShareLinkInfo().getType());
assertEquals("永硕E盘", create.getShareLinkInfo().getPanName());
assertEquals("qaiu", create.getShareLinkInfo().getShareKey());
}
@Test
public void testBuildDownloadUrl() {
String url = YsTool.buildDownloadUrl(
"yssl",
"A95UIe495EkSKE",
"Bc8hF8Nsbl2I4Ec6vAm5EGe9HU36iC",
"L",
"lu20.jpg");
// 与官方一致:xzpz 前不加 "_"
assertEquals(
"https://ys-l.ysepan.com/wap/yssl/A95UIe495EkSKE/Bc8hF8Nsbl2I4Ec6vAm5EGe9HU36iC/lu20.jpg",
url);
assertFalse("force-download 前缀会导致 404", url.contains("/_"));
}
@Test
public void testYsslOpenSpaceRealDownload() throws Exception {
// 旧样例 lu20.jpg 已从示例空间删除(直链 404)。改为现场列出示例空间里的小文件再下载。
FileInfo file = firstSmallFile("https://yssl.ysepan.com/", null, 2_000_000);
assertNotNull("示例空间应至少有一个可下载的小文件", file);
Buffer body = downloadParsedFile(file, "https://yssl.ysepan.com/");
assertEquals(file.getSize().longValue(), body.length());
System.out.println("yssl real download ok, file=" + file.getFileName() + ", size=" + body.length());
}
@Test
public void testQaiuSpaceFileListAndRealDownload() throws Exception {
ParserCreate create = ParserCreate.fromShareUrl("https://qaiu.ysepan.com/");
create.getShareLinkInfo().setSharePassword("qaiuys168");
create.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
List<FileInfo> dirs = create.createTool().parseFileList()
.toCompletionStage().toCompletableFuture()
.get(60, TimeUnit.SECONDS);
assertNotNull(dirs);
assertFalse("目录列表不应为空", dirs.isEmpty());
assertEquals("folder", dirs.get(0).getFileType());
String dirId = dirs.get(0).getFileId();
assertNotNull(dirId);
ParserCreate filesCreate = ParserCreate.fromShareUrl("https://qaiu.ysepan.com/");
filesCreate.getShareLinkInfo().setSharePassword("qaiuys168");
filesCreate.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
filesCreate.getShareLinkInfo().getOtherParam().put("dirId", dirId);
List<FileInfo> files = filesCreate.createTool().parseFileList()
.toCompletionStage().toCompletableFuture()
.get(60, TimeUnit.SECONDS);
assertNotNull(files);
FileInfo zip = files.stream()
.filter(f -> "file".equals(f.getFileType()))
.filter(f -> f.getFileName() != null && f.getFileName().contains("Pycharm"))
.findFirst()
.orElse(null);
assertNotNull("应能列出 Pycharm 压缩包", zip);
assertTrue(zip.getSize() > 0);
assertNotNull(zip.getParserUrl());
String param = zip.getParserUrl().substring(zip.getParserUrl().lastIndexOf('/') + 1);
JsonObject paramJson = new JsonObject(CommonUtils.urlBase64Decode(param));
assertFalse("downloadUrl 不应含 force 前缀",
paramJson.getString("downloadUrl", "").contains("/_"));
ParserCreate byId = ParserCreate.fromType("ys").shareKey("qaiu");
byId.getShareLinkInfo().setSharePassword("qaiuys168");
byId.getShareLinkInfo().getOtherParam().put("paramJson", paramJson);
String downloadUrl = byId.createTool().parseById()
.toCompletionStage().toCompletableFuture()
.get(60, TimeUnit.SECONDS);
assertNotNull(downloadUrl);
assertFalse("解析直链不应含 _xzpz 前缀", downloadUrl.matches(".*/_[^/]+/.*"));
assertTrue(downloadUrl.contains("ysepan.com"));
Buffer body = download(downloadUrl, "https://qaiu.ysepan.com/");
assertEquals("真实下载大小应与列表一致", zip.getSize().longValue(), body.length());
// ZIP magic: PK
assertEquals('P', (char) body.getByte(0));
assertEquals('K', (char) body.getByte(1));
System.out.println("qaiu real download ok, url=" + downloadUrl + ", size=" + body.length());
}
@Test
public void testFufu1ZmlHierarchyAndUrlItems() throws Exception {
// https://fufu1.ysepan.com/ 无密码;游戏3 下应按 zml 展示子目录,再进子目录才是夸克/百度链接
ParserCreate create = ParserCreate.fromShareUrl("https://fufu1.ysepan.com/");
create.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
List<FileInfo> roots = create.createTool().parseFileList()
.toCompletionStage().toCompletableFuture()
.get(60, TimeUnit.SECONDS);
assertNotNull(roots);
FileInfo game3 = roots.stream()
.filter(f -> "folder".equals(f.getFileType()))
.filter(f -> "游戏3".equals(f.getFileName()))
.findFirst()
.orElse(null);
assertNotNull("应有目录 游戏3", game3);
ParserCreate level2 = ParserCreate.fromShareUrl("https://fufu1.ysepan.com/");
level2.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
level2.getShareLinkInfo().getOtherParam().put("dirId", game3.getFileId());
List<FileInfo> subdirs = level2.createTool().parseFileList()
.toCompletionStage().toCompletableFuture()
.get(60, TimeUnit.SECONDS);
assertNotNull(subdirs);
assertTrue("游戏3 下应是子目录列表", subdirs.size() > 10);
assertTrue("游戏3 下列表应全是 folder(zml 子目录)",
subdirs.stream().allMatch(f -> "folder".equals(f.getFileType())));
FileInfo sample = subdirs.stream()
.filter(f -> f.getFileName() != null && f.getFileName().contains("我是未来"))
.findFirst()
.orElse(subdirs.get(0));
// 从 parserUrl 提取 zml,或直接用 fileName
ParserCreate level3 = ParserCreate.fromShareUrl("https://fufu1.ysepan.com/");
level3.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
level3.getShareLinkInfo().getOtherParam().put("dirId", game3.getFileId());
level3.getShareLinkInfo().getOtherParam().put("zml", sample.getFileName());
List<FileInfo> links = level3.createTool().parseFileList()
.toCompletionStage().toCompletableFuture()
.get(60, TimeUnit.SECONDS);
assertNotNull(links);
assertFalse(links.isEmpty());
assertTrue("子目录内应有 url 类型",
links.stream().anyMatch(f -> "url".equals(f.getFileType())));
assertTrue("应包含夸克/百度链接名",
links.stream().anyMatch(f -> "夸克".equals(f.getFileName()) || "百度".equals(f.getFileName())));
assertFalse("空占位 URL 不应出现",
links.stream().anyMatch(f -> f.getFileName() == null || f.getFileName().isBlank()));
assertTrue("URL 条目应带 previewUrl",
links.stream().filter(f -> "url".equals(f.getFileType()))
.allMatch(f -> f.getPreviewUrl() != null && f.getPreviewUrl().startsWith("http")));
System.out.println("fufu1 hierarchy ok: 游戏3 -> " + sample.getFileName()
+ " -> " + links.stream().map(FileInfo::getFileName).toList());
}
@Test
public void testSohehe4SpaceDirectories() throws Exception {
ParserCreate create = ParserCreate.fromShareUrl("https://sohehe4.ysepan.com/");
create.getShareLinkInfo().setSharePassword("1234");
create.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
List<FileInfo> dirs = create.createTool().parseFileList()
.toCompletionStage().toCompletableFuture()
.get(60, TimeUnit.SECONDS);
assertNotNull(dirs);
assertTrue("sohehe4 应有多个目录", dirs.size() >= 3);
assertTrue(dirs.stream().allMatch(d -> "folder".equals(d.getFileType())));
FileInfo file = null;
for (FileInfo dir : dirs) {
if (!"folder".equals(dir.getFileType())) {
continue;
}
file = firstSmallFileInDir("https://sohehe4.ysepan.com/", "1234", dir.getFileId(), 5_000_000);
if (file != null) {
break;
}
}
assertNotNull("sohehe4 应能找到可下载的小文件", file);
Buffer body = downloadParsedFile(file, "https://sohehe4.ysepan.com/");
assertEquals(file.getSize().longValue(), body.length());
System.out.println("sohehe4 real download ok, file=" + file.getFileName()
+ ", size=" + body.length());
}
@Test
public void testQaiuRequiresPassword() throws Exception {
ParserCreate create = ParserCreate.fromShareUrl("https://qaiu.ysepan.com/");
create.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
try {
create.createTool().parseFileList()
.toCompletionStage().toCompletableFuture()
.get(60, TimeUnit.SECONDS);
fail("未提供密码时应拒绝进入");
} catch (java.util.concurrent.ExecutionException e) {
assertTrue(e.getCause().getMessage(), e.getCause().getMessage().contains("空间需要访问密码"));
}
}
@Test
public void testFufu1Ys168RedirectOpenSpace() throws Exception {
List<FileInfo> roots = fileList("https://fufu1.ys168.com/", null);
assertNotNull(roots);
assertTrue(roots.stream().anyMatch(f -> "游戏3".equals(f.getFileName())));
}
@Test
public void testQaiuYs168PasswordRedirectAndRealDownload() throws Exception {
List<FileInfo> dirs = fileList("https://qaiu.ys168.com/", "qaiuys168");
assertNotNull(dirs);
assertFalse(dirs.isEmpty());
FileInfo app = dirs.stream()
.filter(d -> d.getFileName() != null && d.getFileName().contains("app"))
.findFirst()
.orElse(dirs.get(0));
List<FileInfo> files = fileList("https://qaiu.ys168.com/", "qaiuys168", app.getFileId());
FileInfo zip = files.stream()
.filter(f -> "file".equals(f.getFileType()))
.filter(f -> f.getFileName() != null && f.getFileName().contains("Pycharm"))
.findFirst()
.orElse(null);
assertNotNull("ys168 重定向后应能列出 Pycharm 压缩包", zip);
String param = zip.getParserUrl().substring(zip.getParserUrl().lastIndexOf('/') + 1);
JsonObject paramJson = new JsonObject(CommonUtils.urlBase64Decode(param));
String downloadUrl = paramJson.getString("downloadUrl");
assertNotNull(downloadUrl);
assertTrue(downloadUrl.contains("ysepan.com"));
assertFalse(downloadUrl.contains("ys168.com"));
assertFalse(downloadUrl.contains("/_"));
Buffer body = download(downloadUrl, "https://qaiu.ysepan.com/");
assertEquals(zip.getSize().longValue(), body.length());
assertEquals('P', (char) body.getByte(0));
assertEquals('K', (char) body.getByte(1));
System.out.println("qaiu ys168 redirect download ok, size=" + body.length());
}
@Test
public void testBackupDomainsOpenAndPasswordSpaces() throws Exception {
for (String host : new String[]{"cccpan.com", "uupan.net", "ysok.net"}) {
List<FileInfo> openDirs = fileList("https://fufu1." + host + "/", null);
assertNotNull(host, openDirs);
assertFalse(host + " 无密码空间目录为空", openDirs.isEmpty());
assertTrue(host, openDirs.stream().anyMatch(d -> "游戏3".equals(d.getFileName())));
List<FileInfo> lockedDirs = fileList("https://qaiu." + host + "/", "qaiuys168");
assertNotNull(host, lockedDirs);
assertFalse(host + " 密码空间目录为空", lockedDirs.isEmpty());
assertTrue(host + " " + lockedDirs.stream().map(FileInfo::getFileName).toList(),
lockedDirs.stream().anyMatch(d -> d.getFileName() != null && d.getFileName().contains("app")));
}
}
private static List<FileInfo> fileList(String url, String pwd) throws Exception {
return fileList(url, pwd, null, null);
}
private static List<FileInfo> fileList(String url, String pwd, String dirId) throws Exception {
return fileList(url, pwd, dirId, null);
}
private static List<FileInfo> fileList(String url, String pwd, String dirId, String zml) throws Exception {
ParserCreate create = ParserCreate.fromShareUrl(url);
if (pwd != null) {
create.getShareLinkInfo().setSharePassword(pwd);
}
create.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
if (dirId != null) {
create.getShareLinkInfo().getOtherParam().put("dirId", dirId);
}
if (zml != null) {
create.getShareLinkInfo().getOtherParam().put("zml", zml);
}
return create.createTool().parseFileList()
.toCompletionStage().toCompletableFuture()
.get(60, TimeUnit.SECONDS);
}
/** 在目录及其 zml 子目录中找一个体积合适的真实文件。 */
private static FileInfo firstSmallFile(String url, String pwd, long maxSize) throws Exception {
List<FileInfo> dirs = fileList(url, pwd);
assertNotNull(dirs);
assertFalse(url + " 目录为空", dirs.isEmpty());
for (FileInfo dir : dirs) {
if (!"folder".equals(dir.getFileType())) {
continue;
}
FileInfo file = firstSmallFileInDir(url, pwd, dir.getFileId(), maxSize);
if (file != null) {
return file;
}
}
return null;
}
private static FileInfo firstSmallFileInDir(String url, String pwd, String dirId, long maxSize) throws Exception {
List<FileInfo> entries = fileList(url, pwd, dirId);
FileInfo direct = smallFile(entries, maxSize);
if (direct != null) {
return direct;
}
for (FileInfo entry : entries) {
if (!"folder".equals(entry.getFileType()) || entry.getFileId() == null
|| !entry.getFileId().contains(":")) {
continue;
}
FileInfo nested = smallFile(fileList(url, pwd, dirId, entry.getFileName()), maxSize);
if (nested != null) {
return nested;
}
}
return null;
}
private static FileInfo smallFile(List<FileInfo> entries, long maxSize) {
if (entries == null) {
return null;
}
return entries.stream()
.filter(f -> "file".equals(f.getFileType()))
.filter(f -> f.getSize() != null && f.getSize() > 0 && f.getSize() < maxSize)
.findFirst()
.orElse(null);
}
private static Buffer downloadParsedFile(FileInfo file, String referer) throws Exception {
assertNotNull(file.getParserUrl());
String param = file.getParserUrl().substring(file.getParserUrl().lastIndexOf('/') + 1);
JsonObject paramJson = new JsonObject(CommonUtils.urlBase64Decode(param));
String downloadUrl = paramJson.getString("downloadUrl");
assertNotNull(downloadUrl);
assertFalse(downloadUrl.contains("/_"));
return download(downloadUrl, referer);
}
private static Buffer download(String url, String referer) throws Exception {
return webClient.getAbs(url)
.putHeader("User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36")
.putHeader("Referer", referer)
.send()
.toCompletionStage().toCompletableFuture()
.thenApply(res -> {
assertEquals("下载 HTTP 状态码应为 200: " + url, 200, res.statusCode());
Buffer body = res.body();
assertNotNull(body);
assertTrue("下载内容为空: " + url, body.length() > 0);
String ct = res.getHeader("Content-Type");
assertFalse("不应返回 HTML 错误页: " + url,
ct != null && ct.toLowerCase().contains("text/html"));
return body;
})
.get(60, TimeUnit.SECONDS);
}
}
@@ -0,0 +1,127 @@
package cn.qaiu.util;
import org.junit.Test;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Random;
import java.util.function.Function;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class Base64DecoderTest {
@Test
public void matchesJdkForStandardAndUrlSafeEncodings() {
Random random = new Random(114938);
for (int length = 0; length <= 512; length++) {
assertRoundTrip(random, length);
}
}
@Test
public void decodesCompleteGroupsAndEveryTailAcrossLargeInputs() {
Random random = new Random(20261120);
for (int boundary : new int[]{1024, 8192, 65536}) {
for (int offset = -2; offset <= 2; offset++) {
assertRoundTrip(random, boundary + offset);
}
}
}
@Test
public void matchesJdkForInvalidCharactersAtGroupAndTailBoundaries() {
for (int length : new int[]{4, 6, 7, 8}) {
String valid = "A".repeat(length);
for (int i = 0; i < length; i++) {
for (String invalid : new String[]{"!", "=", "\u0141", "\ud83d\ude00"}) {
String value = valid.substring(0, i) + invalid + valid.substring(i + 1);
assertCompatible(value, Base64.getDecoder(), Base64Decoder::decode);
assertCompatible(value, Base64.getUrlDecoder(), Base64Decoder::decodeUrl);
}
}
}
}
@Test
public void matchesJdkForPaddingAlphabetAndInvalidCharacters() {
for (String value : new String[]{"", "A", "AA", "AB==", "ABC=", "ABCD", "AA=", "AAA==",
"AA==AA", "AA==\n", " AA", "A A", "AA\u00e9", "AA\u2603", "+/8=", "-_8=", "+_8=", "===="}) {
assertCompatible(value, Base64.getDecoder(), Base64Decoder::decode);
assertCompatible(value, Base64.getUrlDecoder(), Base64Decoder::decodeUrl);
}
}
@Test
public void preservesLegacyDownloadLinkFormats() {
String value = "网盘下载😀";
String standard = Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));
String escaped = URLEncoder.encode(standard, StandardCharsets.UTF_8);
assertEquals(value, CommonUtils.urlBase64Decode(CommonUtils.urlBase64Encode(value)));
assertEquals(value, CommonUtils.urlBase64Decode(standard));
assertEquals(value, CommonUtils.urlBase64Decode(escaped));
assertEquals(value, CommonUtils.urlBase64Decode(URLEncoder.encode(escaped, StandardCharsets.UTF_8)));
assertEquals("f", CommonUtils.urlBase64Decode("Zg="));
}
@Test
public void matchesJdkAcrossSimdBlocksAndThreshold() {
if (Boolean.getBoolean("nfd.test.requireVector")) {
assertEquals(true, Base64Encoder.useVectors(4096));
}
Random random = new Random(114938);
for (int boundary : new int[]{768, 1024, 4096}) {
for (int offset = -65; offset <= 65; offset++) {
byte[] plain = new byte[boundary + offset];
random.nextBytes(plain);
String standard = Base64.getEncoder().encodeToString(plain);
String url = Base64.getUrlEncoder().withoutPadding().encodeToString(plain);
assertEquals(standard, Base64Encoder.encode(plain));
assertEquals(url, Base64Encoder.encodeUrlWithoutPadding(plain));
assertArrayEquals(Base64.getEncoder().encode(plain), Base64Encoder.encodeBytes(plain));
assertArrayEquals(plain, Base64Decoder.decode(standard));
assertArrayEquals(plain, Base64Decoder.decodeUrl(url));
}
}
}
@Test
public void validatesBothAlphabetsInsideVectorBlocks() {
char[] input = "A".repeat(2048).toCharArray();
for (int ch = 0; ch < 256; ch++) {
int position = 128 + ch % 64;
input[position] = (char) ch;
String encoded = new String(input);
assertCompatible(encoded, Base64.getDecoder(), Base64Decoder::decode);
assertCompatible(encoded, Base64.getUrlDecoder(), Base64Decoder::decodeUrl);
input[position] = 'A';
}
}
private static void assertRoundTrip(Random random, int length) {
byte[] value = new byte[length];
random.nextBytes(value);
assertArrayEquals(value, Base64Decoder.decode(Base64.getEncoder().encodeToString(value)));
assertArrayEquals(value, Base64Decoder.decode(Base64.getEncoder().withoutPadding().encodeToString(value)));
assertArrayEquals(value, Base64Decoder.decodeUrl(Base64.getUrlEncoder().encodeToString(value)));
assertArrayEquals(value, Base64Decoder.decodeUrl(Base64.getUrlEncoder().withoutPadding().encodeToString(value)));
}
private static void assertCompatible(String value, Base64.Decoder jdk, Function<String, byte[]> replacement) {
byte[] expected;
try {
expected = jdk.decode(value);
} catch (IllegalArgumentException expectedFailure) {
try {
replacement.apply(value);
} catch (IllegalArgumentException actualFailure) {
return;
}
fail("Accepted invalid Base64 input: " + value);
return;
}
assertArrayEquals(expected, replacement.apply(value));
}
}
@@ -0,0 +1,90 @@
package cn.qaiu.util;
import org.junit.Test;
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
import java.util.Map;
import static org.junit.Assert.*;
/**
* 新版蓝奏页面会调用更多 document / jQuery API,沙箱必须能跑完并抓住 $.ajax。
*/
public class JsExecUtilsLzTest {
@Test
public void testNewIframeAjaxWithDomApis() throws Exception {
String js = """
var lanosso = '';
var down_1 = '';
var wsk_sign = 'c20230908';
var wp_sign = 'SIGN_ABC';
var ajaxdata = 'MrBR';
var kdns = 1;
if (typeof(killdns)=='undefined'){
var kdns = 0;
}
document.cookie = 'x=1';
document.location.reload();
document.querySelector('#tourl');
document.createElement('div');
$.ajax({
type : 'post',
url : '/ajaxfile.php?file=150233466',
data : { 'action':'downprocess','websignkey':ajaxdata,'signs':ajaxdata,'sign':wp_sign,'websign':'','kd':kdns,'ves':1 },
dataType : 'json',
success:function(msg){
$("#tourl").html("ok");
$("#outime").css("display","block");
}
});
""";
ScriptObjectMirror sign = JsExecUtils.executeDynamicJs(js, null);
assertNotNull(sign);
assertEquals("/ajaxfile.php?file=150233466", String.valueOf(sign.get("url")));
@SuppressWarnings("unchecked")
Map<String, Object> data = (Map<String, Object>) sign.get("data");
assertEquals("downprocess", String.valueOf(data.get("action")));
assertEquals("SIGN_ABC", String.valueOf(data.get("sign")));
assertEquals("MrBR", String.valueOf(data.get("websignkey")));
assertEquals("1", String.valueOf(data.get("kd")));
}
@Test
public void testPwdViaJqueryValAndDocument() throws Exception {
String js = """
function down_p(){
var pwd = $('#pwd').val();
var pwd2 = document.getElementById('pwd').value;
var pwd3 = document.querySelector('#pwd').value;
$(".passwdinput").focus();
$.ajax({
type : 'post',
url : '/ajaxm.php',
data : { 'action':'downprocess','sign':'S1','p':pwd,'p2':pwd2,'p3':pwd3 }
});
}
""";
ScriptObjectMirror sign = JsExecUtils.executeDynamicJs(js, "down_p", "e4k4");
assertNotNull(sign);
@SuppressWarnings("unchecked")
Map<String, Object> data = (Map<String, Object>) sign.get("data");
assertEquals("e4k4", String.valueOf(data.get("p")));
assertEquals("e4k4", String.valueOf(data.get("p2")));
assertEquals("e4k4", String.valueOf(data.get("p3")));
}
@Test
public void testReadyAndSuccessCallbackDoNotDropAjax() throws Exception {
String js = """
$(function(){
document.getElementById('rpt').style.display = 'none';
$.ajax({ url: '/ajaxm.php?file=1', data: { a: 1 } });
$("#tourl").html("x");
});
""";
ScriptObjectMirror sign = JsExecUtils.executeDynamicJs(js, null);
assertNotNull(sign);
assertTrue(String.valueOf(sign.get("url")).contains("ajaxm.php"));
}
}
+5 -4
View File
@@ -17,7 +17,7 @@
</modules>
<properties>
<revision>0.3.4</revision>
<revision>0.4.12</revision>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
@@ -33,9 +33,10 @@
<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>
<jackson.version>2.18.9</jackson.version>
<!-- Logback 最新稳定版 -->
<logback.version>1.5.32</logback.version>
<logback.version>1.5.34</logback.version>
<skipTests>true</skipTests>
<junit.version>4.13.2</junit.version>
</properties>
@@ -97,7 +98,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<skipTests>true</skipTests>
<skipTests>${skipTests}</skipTests>
</configuration>
</plugin>
<plugin>
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
亿方云 (FangCloud) 分享链接有效性验证脚本
用法: 直接 `python3 verify_fangcloud_share.py` 运行, 分享链接已写死在 SHARE_URL
里 (不走命令行传参), 要换链接就直接改这个常量。
根因(已用真实分享链接验证确认)
--------------------------------
GET https://v2.fangcloud.cn/apps/share_links/info/{uname}
返回的是 200 + JSON, 结构形如:
{
"process": {
"is_closed": false,
"is_expired": false,
"item": {"type": "file", "id": 45006535173, "name": "..."},
...
}
}
FcTool.java 原来的实现判断有效性时读的是响应体**顶层**的 "is_valid" 字段
(`json.getBoolean("is_valid")`), 但这个字段根本不存在于该接口的实际响应里
(有效性信息实际上是 process.is_closed / process.is_expired, 且没有任何
名叫 "is_valid" 的字段) —— 所以旧的判断逻辑其实从未真正读取过这个接口的
有效性判断, 而是走的另一套 HTML 抓取 typed_id 的流程, 分享失效时会得到一个
"未匹配到文件id(typed_id)" 这种令人困惑的技术报错, 而不是清晰的"分享已失效"。
修复方案(已同步到 FcTool.java): 解析前先请求一次
https://v2.fangcloud.cn/apps/share_links/info/{uname}, 用
process.is_closed / process.is_expired 判断分享是否有效, 无效则直接返回
"分享已失效或不存在", 有效再继续走原来的 HTML + files/download 流程。
本脚本用于本地复现/回归验证这条判断逻辑, 并顺带跑一遍完整的取直链流程。
"""
import re
import sys
import requests
# 直接写死分享链接, 不通过命令行参数传入
SHARE_URL = "https://v2.fangcloud.cn/h5/share/ded6dc6b9c3672b40b769804bf"
# 如果分享有密码, 在这里填上, 没有就留空字符串
SHARE_PASSWORD = ""
HEADERS = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
),
"Accept": "application/json, text/html;q=0.9, */*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}
# 修复后的正则, 额外兼容 /h5/share/ 移动端落地页路径 (对齐 PanDomainTemplate.FC)
FC_REGEX = re.compile(r"https://v2\.fangcloud\.(com|cn)/(?:h5/)?(s|share|sharing)/(?P<KEY>.+)")
SHARE_INFO_URL = "https://v2.fangcloud.cn/apps/share_links/info/{key}"
SHARE_URL_PREFIX = "https://v2.fangcloud.com/sharing/{key}"
DOWN_REQUEST_URL = "https://v2.fangcloud.cn/apps/files/download"
TYPED_ID_RE = re.compile(r'id="typed_id"\s+value="file_(\d+)"')
def extract_share_key(url: str) -> str:
m = FC_REGEX.search(url)
if not m:
raise ValueError(f"无法从链接中提取 shareKey (正则不匹配): {url}")
return m.group("KEY")
def check_is_valid(share_key: str, session: requests.Session) -> bool:
print("=" * 70)
print("Step 1. 请求 share_links/info 判断分享有效性 (对齐 FcTool.java 修复后的逻辑)")
print("=" * 70)
url = SHARE_INFO_URL.format(key=share_key)
r = session.get(url, timeout=15)
print(f"GET {url}")
print(f"状态码: {r.status_code}")
try:
data = r.json()
except Exception:
print("响应不是合法JSON => 判定分享已失效或不存在\n")
return False
process = data.get("process")
if not process:
print("响应中没有 process 字段 => 判定分享已失效或不存在\n")
return False
is_closed = bool(process.get("is_closed"))
is_expired = bool(process.get("is_expired"))
item = process.get("item")
print(f"is_closed = {is_closed}, is_expired = {is_expired}, item = {item}")
if is_closed or is_expired:
print("=> 分享已失效或不存在\n")
return False
print("=> 分享有效\n")
return True
def get_download_url(share_key: str, pwd: str, session: requests.Session) -> str:
print("=" * 70)
print("Step 2. 走原有 HTML + files/download 流程取直链")
print("=" * 70)
r = session.get(SHARE_URL_PREFIX.format(key=share_key), timeout=15)
print(f"GET {SHARE_URL_PREFIX.format(key=share_key)} -> {r.status_code}, 最终URL: {r.url}")
html = r.text
if pwd:
# 加密分享: 提交密码换取跳转后的落地页 (此处仅示意, 具体见 FcTool.java)
m = re.search(r'name="requesttoken"\s+value="([a-zA-Z0-9_+=]+)"', html)
if not m:
raise RuntimeError("未匹配到加密分享的密码输入页面的 requesttoken")
token = m.group(1)
r2 = session.post(
"https://v2.fangcloud.cn/sharing/" + share_key,
data={"requesttoken": token, "password": pwd},
timeout=15,
)
html = r2.text
m = TYPED_ID_RE.search(html)
if not m:
raise RuntimeError("未匹配到文件id(typed_id), 分享可能是文件夹或页面结构有变化")
fid = m.group(1)
print(f"提取到 file_id = {fid}")
r3 = session.get(
DOWN_REQUEST_URL,
params={"file_id": fid, "scenario": "share", "unique_name": share_key},
timeout=15,
allow_redirects=False,
)
print(f"GET {DOWN_REQUEST_URL} -> {r3.status_code}")
if r3.status_code in (301, 302) and r3.headers.get("Location"):
return r3.headers["Location"]
data = r3.json()
if not data.get("success"):
raise RuntimeError(f"取直链失败: {data}")
return data["download_url"]
def main() -> None:
share_key = extract_share_key(SHARE_URL)
print(f"分享链接: {SHARE_URL}")
print(f"提取到的 shareKey: {share_key}\n")
session = requests.Session()
session.headers.update(HEADERS)
if not check_is_valid(share_key, session):
print("结论: 分享无效, 不再继续取直链。")
sys.exit(1)
try:
url = get_download_url(share_key, SHARE_PASSWORD, session)
print(f"\n>>> 直链: {url}")
except Exception as e:
print(f"\n取直链失败: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
+4 -3
View File
@@ -1,19 +1,20 @@
{
"name": "nfd-web",
"version": "0.2.1",
"version": "0.4.12",
"private": true,
"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",
"lint": "vue-cli-service lint"
"lint": "vue-cli-service lint",
"test": "node --test src/utils/batchTreeCollect.spec.js src/utils/folderPaging.spec.js"
},
"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.18.0",
"clipboard": "^2.0.11",
"core-js": "^3.8.3",
"crypto-js": "^4.2.0",
+139 -18
View File
@@ -292,6 +292,29 @@
gap: 10px;
}
}
.load-more {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
padding: 12px 0 4px;
font-size: 13px;
color: #7f8c8d;
}
.load-more button {
padding: 6px 14px;
border: 1px solid #3498db;
background: #fff;
color: #3498db;
border-radius: 4px;
cursor: pointer;
}
.load-more button:disabled {
opacity: .6;
cursor: default;
}
</style>
</head>
<body>
@@ -409,6 +432,98 @@
};
const pathStack = [currentDir];
// 目录分页:/v2/getFileList 链接换成 /v2/getFileListPage 并带 page / pageCursor
let more = null;
let loadSeq = 0;
let seenKeys = new Set();
let folderCount = 0;
let fileCount = 0;
const moreEl = document.createElement('div');
moreEl.className = 'load-more';
moreEl.style.display = 'none';
function toPageUrl(listUrl, page, cursor) {
const m = String(listUrl || '').match(/^(.*?\/v2\/getFileList)(\?.*)?$/);
if (!m) return null;
let url = `${m[1]}Page${m[2] || ''}`;
url += (url.includes('?') ? '&' : '?') + `page=${encodeURIComponent(page)}`;
if (cursor) url += `&pageCursor=${encodeURIComponent(cursor)}`;
return url;
}
function readPage(data) {
if (Array.isArray(data)) return { list: data, hasMore: false };
const d = data || {};
const hasMore = !!d.hasMore && Number.isInteger(d.nextPage);
return { list: Array.isArray(d.list) ? d.list : [], hasMore, nextPage: d.nextPage, nextCursor: d.nextCursor || null };
}
async function fetchJson(url) {
const response = await fetch(url);
let data = null;
try {
data = await response.json();
} catch (e) {
throw new Error(`HTTP error! status: ${response.status}`);
}
if (data && data.code === 200 && data.success) return data;
throw new Error((data && data.msg) || `获取文件列表失败 (HTTP ${response.status})`);
}
function fileKey(file) {
return `${file.parserUrl || ''}::${file.fileName || ''}::${file.fileId || ''}`;
}
function renderMore() {
if (!more) {
moreEl.style.display = 'none';
moreEl.innerHTML = '';
return;
}
moreEl.style.display = '';
const total = folderCount + fileCount;
const label = more.loading ? '加载中…' : (more.error ? '加载失败,点击重试' : '加载更多');
const hint = more.error ? `已加载 ${total} 项:${more.error}` : `已加载 ${total} 项,滚动到底部自动加载`;
moreEl.innerHTML = '';
const btn = document.createElement('button');
btn.textContent = label;
btn.disabled = !!more.loading;
btn.addEventListener('click', loadMore);
const span = document.createElement('span');
span.textContent = hint;
moreEl.appendChild(btn);
moreEl.appendChild(span);
}
// 加载失败只提示重试,已加载的条目保留;失败后暂停滚动自动加载
async function loadMore() {
const state = more;
if (!state || state.loading) return;
const seq = loadSeq;
state.loading = true;
state.error = '';
renderMore();
try {
const data = await fetchJson(toPageUrl(state.listUrl, state.nextPage, state.nextCursor));
if (seq !== loadSeq || more !== state) return;
const page = readPage(data.data);
renderFileList(page.list, true);
more = page.hasMore ? { listUrl: state.listUrl, nextPage: page.nextPage, nextCursor: page.nextCursor } : null;
} catch (error) {
if (seq !== loadSeq || more !== state) return;
state.error = error.message || '加载下一页失败';
} finally {
state.loading = false;
renderMore();
}
}
if (typeof IntersectionObserver !== 'undefined') {
new IntersectionObserver(entries => {
if (more && !more.loading && !more.error && entries.some(e => e.isIntersecting)) loadMore();
}).observe(moreEl);
}
// DOM 元素
const breadcrumbEl = document.getElementById('breadcrumb');
const fileGridEl = document.getElementById('file-grid');
@@ -418,6 +533,7 @@
// 初始化
document.addEventListener('DOMContentLoaded', () => {
fileGridEl.insertAdjacentElement('afterend', moreEl);
renderBreadcrumb();
fetchFileList(currentDir.url);
@@ -458,6 +574,9 @@
// 获取文件列表
async function fetchFileList(url) {
const seq = ++loadSeq;
more = null;
renderMore();
try {
// 显示加载状态
fileGridEl.innerHTML = `
@@ -466,18 +585,15 @@
</div>
`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.code === 200 && data.success) {
renderFileList(data.data);
} else {
throw new Error(data.msg || '获取文件列表失败');
}
const pageUrl = toPageUrl(url, 1);
const data = await fetchJson(pageUrl || url);
if (seq !== loadSeq) return;
const page = readPage(data.data);
renderFileList(page.list);
more = pageUrl && page.hasMore ? { listUrl: url, nextPage: page.nextPage, nextCursor: page.nextCursor } : null;
renderMore();
} catch (error) {
if (seq !== loadSeq) return;
console.error('获取文件列表失败:', error);
fileGridEl.innerHTML = `
<div class="empty-state">
@@ -490,10 +606,15 @@
}
// 渲染文件列表
function renderFileList(files) {
fileGridEl.innerHTML = '';
function renderFileList(files, append = false) {
if (!append) {
fileGridEl.innerHTML = '';
seenKeys = new Set();
folderCount = 0;
fileCount = 0;
}
if (!files || files.length === 0) {
if (!append && (!files || files.length === 0)) {
fileGridEl.innerHTML = `
<div class="empty-state">
<i class="fas fa-folder-open"></i>
@@ -506,10 +627,10 @@
return;
}
let folderCount = 0;
let fileCount = 0;
files.forEach(file => {
(files || []).forEach(file => {
const key = fileKey(file);
if (seenKeys.has(key)) return;
seenKeys.add(key);
const item = document.createElement('div');
const metaText = fileMetaText(file);
File diff suppressed because it is too large. Load diff
+2 -7
View File
@@ -105,6 +105,7 @@
<script>
import { testConnection, addDownload, getConfig, hasCookieHeader, hasCustomUaHeader } from '@/utils/downloaderService'
import { openNoReferrer } from '@/utils/openNoReferrer'
export default {
name: 'DownloadDialog',
@@ -193,13 +194,7 @@ export default {
/** 直接打开下载链接(可能因缺请求头而失败) */
doDirectDownload() {
if (this.info && this.info.downloadUrl) {
const a = document.createElement('a')
a.href = this.info.downloadUrl
a.target = '_blank'
a.rel = 'noopener noreferrer'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
openNoReferrer(this.info.downloadUrl)
this.dialogVisible = false
}
},
@@ -0,0 +1,65 @@
<template>
<el-radio-group
:model-value="modelValue"
size="small"
class="view-mode-switch"
@update:model-value="$emit('update:modelValue', $event)"
>
<el-radio-button label="pane" title="窗格视图">
<i class="fas fa-th" aria-hidden="true"></i>
<span class="view-mode-text">{{ paneLabel }}</span>
</el-radio-button>
<el-radio-button label="tree" title="文件树视图">
<i class="fas fa-sitemap" aria-hidden="true"></i>
<span class="view-mode-text">{{ treeLabel }}</span>
</el-radio-button>
</el-radio-group>
</template>
<script>
export default {
name: 'ViewModeSwitch',
props: {
modelValue: {
type: String,
default: 'pane'
},
paneLabel: {
type: String,
default: '窗格'
},
treeLabel: {
type: String,
default: '文件树'
}
},
emits: ['update:modelValue']
}
</script>
<style scoped>
.view-mode-switch :deep(.el-radio-button__inner) {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
min-height: 36px;
min-width: 76px;
padding: 8px 12px;
}
.view-mode-switch i {
font-size: 14px;
line-height: 1;
}
.view-mode-text {
line-height: 1;
}
@media (max-width: 480px) {
.view-mode-switch :deep(.el-radio-button__inner) {
min-width: 68px;
min-height: 40px;
padding: 10px 12px;
}
}
</style>
+13 -2
View File
@@ -246,8 +246,8 @@
storage: 'hash'
},
'123pan': {
reg: /((?:https?:\/\/)?www\.(123pan|123865|123684)\.com\/s\/[\w-]{6,})/,
host: /www\.123pan\.com/,
reg: /((?:https?:\/\/)?(?:[a-zA-Z\d-]+\.(?:m?share)\.123pan\.cn\/123pan\/[\w-]+|(?:www\.)?(?:123panpay|123pan|123\d{3})\.(?:com|cn)\/s\/[\w-]{6,}(?:\.html)?)(?:\?[^#\s]*)?)/i,
host: /(?:[a-zA-Z\d-]+\.(?:m?share)\.123pan\.cn|(?:www\.)?(?:123panpay|123pan|123\d{3})\.(?:com|cn))/i,
input: ['.ca-fot input', ".appinput .appinput"],
button: ['.ca-fot button', ".appinput button"],
name: '123云盘',
@@ -356,6 +356,13 @@
host: /(fast|drive)\.uc\.cn/,
name: 'UC网盘'
},
// 永硕E盘:主 ysepan.com/ys168.com,备 cccpan.com/ysupan.com/uupan.net/ysok.net
ysepan: {
reg: /https?:\/\/(?!(?:www|zy|ht|api|c\d+|ys-[a-zA-Z0-9]+)\.)[a-zA-Z\d-]+\.(?:ysepan\.com|ys168\.com|cccpan\.com|ysupan\.com|uupan\.net|ysok\.net)\/?/,
host: /[a-zA-Z\d-]+\.(?:ysepan\.com|ys168\.com|cccpan\.com|ysupan\.com|uupan\.net|ysok\.net)/,
name: '永硕E盘',
storage: 'hash'
},
other: {
reg: /https:\/\/([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\.)+[a-zA-Z]{2,}\/s\/.+/,
@@ -370,6 +377,7 @@
parseLink(text = '') {
let obj = {name: '', link: '', storage: '', storagePwdName: ''};
if (text) {
text = String(text).trim();
try {
text = decodeURIComponent(text);
} catch {
@@ -383,6 +391,9 @@
let matches = text.match(val.reg);
obj.name = val.name;
obj.link = matches[0];
if (obj.link && !/^https?:\/\//i.test(obj.link)) {
obj.link = 'https://' + obj.link.replace(/^\/\//, '');
}
obj.storage = val.storage;
obj.storagePwdName = val.storagePwdName || null;
if (val.replaceHost) {
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more