Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(downloads): CloudDrive2 地址留空时「检查」自动探测本机端口

longmeidao97ed9badb445
diff --git a/docs/CLOUDDRIVE.md b/docs/CLOUDDRIVE.md
index c19560c1c..c78d69bb2 100644
--- a/docs/CLOUDDRIVE.md
+++ b/docs/CLOUDDRIVE.md
@@ -117,7 +117,7 @@ Peach 不实时监视网盘目录,因为每列一次目录都是一次网络
配置在配置页「媒体」分组的「云下载」和「PikPak 账号」两张卡里:
-- **115**:经 CloudDrive2 的 gRPC 接口提交。在 CloudDrive2「设置 → API 令牌」里生成一个令牌,至少勾「提交离线任务」「查看离线任务与配额」,要在 Peach 里取消任务再勾「取消离线任务」。把 CloudDrive2 地址和令牌填进去(独立版默认 `http://127.0.0.1:19798`;Windows 桌面版的端口可能不同,2026-10-01 在一台机器上实测是 `29798`,「检查」报连不上时先核对端口),点「检查」:它报出缺哪项权限、目标目录能不能离线下载、本月还剩几条配额,只读,不提交任务。
+- **115**:经 CloudDrive2 的 gRPC 接口提交。在 CloudDrive2「设置 → API 令牌」里生成一个令牌,至少勾「提交离线任务」「查看离线任务与配额」,要在 Peach 里取消任务再勾「取消离线任务」。填好令牌后点「检查」:它报出缺哪项权限、目标目录能不能离线下载、本月还剩几条配额,只读,不提交任务。CloudDrive2 跑在这台电脑上时地址可以留空,「检查」会依次试 `http://127.0.0.1:19798`(独立版默认)和 `http://127.0.0.1:29798`(Windows 桌面版常见),用不需要令牌的 `GetSystemInfo` 看谁应答,把先应答的地址填回表单;点「保存配置」后才记下来。两个都不应答时报错并列出试过的两个地址,这时确认 CloudDrive2 已启动,或者把它的实际地址填进去。
- **PikPak**:PikPak 没有开放接口,Peach 照网页端的协议直连。用账号密码登录一次换取登录令牌;勾「保存密码」时登录过期会自动重新登录,不勾就要回到这张卡重新登录。登录触发人机验证时,卡上会给出验证页链接,在浏览器里完成后回来再点一次「登录」,Peach 不替你过验证。
- **目标目录**:115 填 CloudDrive2 挂载树里的路径,这个目录要落在推送发现某个「云端路径前缀」下面;PikPak 填网盘里已经存在的目录,再选 PikPak 根目录对应哪个媒体文件夹。
- **等待上限**:远端超过这么久还没下完就标为「停滞」,多半是没有人做种。
diff --git a/frontend/src/react/bundle.d.ts b/frontend/src/react/bundle.d.ts
index 3ba8e012d..d7ce9b472 100644
--- a/frontend/src/react/bundle.d.ts
+++ b/frontend/src/react/bundle.d.ts
@@ -132,6 +132,8 @@ export interface DownloadSettingsState {
/** 「检查」的结果:每一项各自报,一项失败不挡住其余几项。 */
export interface DownloadCheckReport {
ok: boolean;
+ /** 实际查的 CloudDrive2 地址。表单留空时是探测到的本机地址,探测不到时为空串。 */
+ address: string;
permissions: { name: string; label: string; granted: boolean }[];
missing: string[];
root: string;
diff --git a/frontend/src/react/settings/download-settings.tsx b/frontend/src/react/settings/download-settings.tsx
index e3b03b034..e4fbc88e1 100644
--- a/frontend/src/react/settings/download-settings.tsx
+++ b/frontend/src/react/settings/download-settings.tsx
@@ -51,6 +51,7 @@ function DownloadForm({ state, settle, receipt }: CardProps) {
const [token, setToken] = useState('');
const [hours, setHours] = useState(String(state.config.wait_hours));
const [report, setReport] = useState<DownloadCheckReport | null>(null);
+ const [detected, setDetected] = useState('');
const [failure, setFailure] = useState('');
const action = useAction();
const target = (key: '115' | 'pikpak') => config.targets[key] ?? '';
@@ -71,10 +72,17 @@ function DownloadForm({ state, settle, receipt }: CardProps) {
}, (cause) => setFailure(errorMessage(cause)));
};
+ // 地址留空时服务端探测本机端口,探测到的地址填回表单;用户点「保存配置」才落盘。
const check = () => {
+ const blank = !config.clouddrive_address.trim();
const body = { clouddrive_address: config.clouddrive_address, token, target: target('115') };
void action.run('check', (signal) => apiSend<DownloadCheckReport>(CHECK_URL, body, 'POST', signal),
- (next) => { setReport(next); setFailure(''); }, (cause) => setFailure(errorMessage(cause)));
+ (next) => {
+ if (blank && next.address) setConfig((current) => ({ ...current, clouddrive_address: next.address }));
+ setReport(next);
+ setDetected(blank ? next.address : '');
+ setFailure('');
+ }, (cause) => setFailure(errorMessage(cause)));
};
return (
@@ -82,7 +90,7 @@ function DownloadForm({ state, settle, receipt }: CardProps) {
<Stack>
<Help>把磁力交给 115 或 PikPak 离线下载,文件落在已挂载的网盘目录,再由推送发现登记入库,不经过这台电脑。
115 每个任务扣一条离线配额(年费会员每月 1500 条、月费 200 条),被判违规的资源不重试。</Help>
- <Input label="CloudDrive2 地址" placeholder="http://127.0.0.1:19798" autoComplete="off" maxLength={200}
+ <Input label="CloudDrive2 地址" placeholder="留空自动探测本机 19798 / 29798" autoComplete="off" maxLength={200}
value={config.clouddrive_address} isDisabled={!state.available}
onChange={(value) => setConfig({ ...config, clouddrive_address: value })} />
<Input label="CloudDrive2 API 令牌" type="password" autoComplete="off" maxLength={400}
@@ -111,7 +119,7 @@ function DownloadForm({ state, settle, receipt }: CardProps) {
hint={`远端超过这么久还没下完就标为停滞,多半是没有人做种。1 到 ${state.max_wait_hours} 小时。`}
value={hours} isDisabled={!state.available} onChange={setHours} />
</Stack>
- {report ? <CheckReport report={report} /> : null}
+ {report ? <CheckReport report={report} detected={detected} /> : null}
{failure || action.error ? <Stack divided><ErrorText>{failure || action.error}</ErrorText></Stack> : null}
<Footer status={state.available ? undefined : '云下载只在账本写入端可用。'}>
<Button onClick={check} disabled={!state.available} {...busyProps(action.busy === 'check')}>检查</Button>
@@ -121,10 +129,11 @@ function DownloadForm({ state, settle, receipt }: CardProps) {
);
}
-function CheckReport({ report }: { report: DownloadCheckReport }) {
+function CheckReport({ report, detected }: { report: DownloadCheckReport; detected: string }) {
return (
<Stack divided>
<FactList>
+ {detected ? <Fact term="CloudDrive2 地址">{`探测到 ${detected},保存配置后生效`}</Fact> : null}
{report.permissions.length ? (
<Fact term="离线权限">
{report.missing.length ? `缺少:${report.missing.join('、')}` : '齐全'}
diff --git a/frontend/test/react/download-settings.test.tsx b/frontend/test/react/download-settings.test.tsx
index 996fadaa1..f78856325 100644
--- a/frontend/test/react/download-settings.test.tsx
+++ b/frontend/test/react/download-settings.test.tsx
@@ -41,7 +41,7 @@ it('保存时令牌随表单交给服务端,回来后清空,提示改成已
it('检查报出缺的权限、目标目录与剩余配额,操作键都是主按钮', async () => {
vi.stubGlobal('fetch', fetchMock(200, {
- ok: true, permissions: [{ name: 'a', label: '提交离线任务', granted: true },
+ ok: true, address: 'http://127.0.0.1:19798', permissions: [{ name: 'a', label: '提交离线任务', granted: true },
{ name: 'b', label: '取消离线任务', granted: false }],
missing: ['取消离线任务'], root: '/', folder: { path: '/115/云下载', can_offline: true, cloud: '115open' },
quota: { total: 1500, used: 3, left: 1497 }, problems: [],
@@ -55,6 +55,44 @@ it('检查报出缺的权限、目标目录与剩余配额,操作键都是主
expect(host.textContent).toContain('缺少:取消离线任务');
expect(host.textContent).toContain('/115/云下载 可以离线下载');
expect(host.textContent).toContain('本月还剩 1497 条,共 1500 条');
+ expect(host.textContent).not.toContain('探测到');
+});
+
+it('地址留空时检查把探测到的本机地址填回表单,保存配置才带上它', async () => {
+ const blank = state({ config: { clouddrive_address: '', targets: { '115': '/115/云下载' },
+ pikpak_root: '', wait_hours: 168 } });
+ const fetcher = fetchMock(200, {
+ ok: true, address: 'http://127.0.0.1:29798', permissions: [], missing: [], root: '/',
+ folder: null, quota: null, problems: [],
+ });
+ vi.stubGlobal('fetch', fetcher);
+ const host = await mount(<DownloadSettings initial={blank} receipt={vi.fn()} />);
+ expect(field(host, 'CloudDrive2 地址')?.placeholder).toBe('留空自动探测本机 19798 / 29798');
+ await click(buttonNamed('检查', host));
+ await settle();
+ expect(sentBody(fetcher)).toMatchObject({ clouddrive_address: '' });
+ expect(field(host, 'CloudDrive2 地址')?.value).toBe('http://127.0.0.1:29798');
+ expect(host.textContent).toContain('探测到 http://127.0.0.1:29798,保存配置后生效');
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ fetcher.mockImplementation(async () => ({ ok: true, status: 200, json: async () => blank }));
+ await submit(section(host, '云下载'));
+ await settle();
+ expect(fetcher.mock.calls[1]?.[0]).toBe('/api/configuration/downloads');
+ expect(sentBody(fetcher, 1)).toMatchObject({ clouddrive_address: 'http://127.0.0.1:29798' });
+});
+
+it('两个本机端口都不应答时原样报出服务端列的地址,表单仍留空', async () => {
+ const blank = state({ config: { clouddrive_address: '', targets: {}, pikpak_root: '', wait_hours: 168 } });
+ const problem = '没有填 CloudDrive2 地址,本机 http://127.0.0.1:19798、http://127.0.0.1:29798 都没有应答。';
+ vi.stubGlobal('fetch', fetchMock(200, {
+ ok: false, address: '', permissions: [], missing: [], root: '', folder: null, quota: null,
+ problems: [problem],
+ }));
+ const host = await mount(<DownloadSettings initial={blank} receipt={vi.fn()} />);
+ await click(buttonNamed('检查', host));
+ await settle();
+ expect(host.textContent).toContain(problem);
+ expect(field(host, 'CloudDrive2 地址')?.value).toBe('');
});
it('PikPak 要人机验证时给出验证页,完成后再登录', async () => {
diff --git a/src/peach/downloads_clouddrive.proto b/src/peach/downloads_clouddrive.proto
index fe8578a37..4c2b77a95 100644
--- a/src/peach/downloads_clouddrive.proto
+++ b/src/peach/downloads_clouddrive.proto
@@ -1,4 +1,4 @@
-// CloudDrive2 gRPC 接口的子集:只留云下载用到的六个方法和它们的消息。
+// CloudDrive2 gRPC 接口的子集:只留云下载用到的七个方法和它们的消息。
//
// 字段号、类型与名字逐个照抄官方 https://www.clouddrive2.com/api/clouddrive.proto
// (option version = "1.1.0")。删掉的是用不到的字段,proto3 解码会跳过未知字段,
@@ -10,7 +10,10 @@ syntax = "proto3";
package clouddrive;
+import "google/protobuf/empty.proto";
+
service CloudDriveFileSrv {
+ rpc GetSystemInfo(google.protobuf.Empty) returns (CloudDriveSystemInfo) {}
rpc GetApiTokenInfo(StringValue) returns (TokenInfo) {}
rpc FindFileByPath(FindFileByPathRequest) returns (CloudDriveFile) {}
rpc AddOfflineFiles(AddOfflineFileRequest) returns (FileOperationResult) {}
@@ -19,6 +22,12 @@ service CloudDriveFileSrv {
rpc GetOfflineQuotaInfo(OfflineQuotaRequest) returns (OfflineQuotaInfo) {}
}
+message CloudDriveSystemInfo {
+ bool IsLogin = 1;
+ string UserName = 2;
+ bool SystemReady = 3;
+}
+
message StringValue { string value = 1; }
message TokenInfo {
diff --git a/src/peach/downloads_clouddrive.py b/src/peach/downloads_clouddrive.py
index eabc3f5e8..5eb301e02 100644
--- a/src/peach/downloads_clouddrive.py
+++ b/src/peach/downloads_clouddrive.py
@@ -4,7 +4,7 @@ Peach 不另申请 115 应用,复用 CloudDrive2 已有的 115open 授权:
会顶掉第一次。CloudDrive2 的 API 令牌由用户在设置页填一次,存本机 `CredentialStore`,
只放进 gRPC 的 `authorization` 元数据,不进 URL、日志与 ledger。
-用到的六个方法见 `downloads_clouddrive.proto`。流程参照 JavBoss
+用到的七个方法见 `downloads_clouddrive.proto`。流程参照 JavBoss
`internal/clouddrive/client.go` 与 `internal/service/download.go`:提交前确认目标目录
`canOfflineDownload` 并查配额,提交时让 CloudDrive2 10 秒后自己看一眼目录,之后按 infohash
在目录的离线列表里对账;列表里找不到时看目录里有没有那个文件。
@@ -19,6 +19,7 @@ from dataclasses import dataclass
from urllib.parse import urlsplit
import grpc
+from google.protobuf import empty_pb2
from . import downloads_clouddrive_pb2 as pb
from .downloads import (
@@ -31,6 +32,10 @@ SERVICE = "/clouddrive.CloudDriveFileSrv/"
CALL_TIMEOUT = 30.0
#: 提交后让 CloudDrive2 自己隔多久去目标目录看一眼。
CHECK_FOLDER_AFTER_SECS = 10
+#: 地址留空时「检查」依次试的本机地址:独立版默认 19798,Windows 桌面版有用 29798 的。
+LOCAL_ADDRESSES = ("http://127.0.0.1:19798", "http://127.0.0.1:29798")
+#: 探测一个地址的上限。本机端口没人听时立刻被拒,这个上限只兜住听着却不应答的情况。
+PROBE_TIMEOUT = 3.0
#: 「检查」要报的三项离线权限。取消要用到第三项,缺它只是不能取消。
OFFLINE_PERMISSIONS = {
@@ -40,6 +45,7 @@ OFFLINE_PERMISSIONS = {
}
_METHODS = {
+ "GetSystemInfo": (empty_pb2.Empty, pb.CloudDriveSystemInfo),
"GetApiTokenInfo": (pb.StringValue, pb.TokenInfo),
"FindFileByPath": (pb.FindFileByPathRequest, pb.CloudDriveFile),
"AddOfflineFiles": (pb.AddOfflineFileRequest, pb.FileOperationResult),
@@ -64,6 +70,36 @@ def channel_target(address: str) -> tuple[str, bool]:
return f"{host}:{port}", parts.scheme == "https"
+def open_channel(address: str) -> grpc.Channel:
+ target, secure = channel_target(address)
+ return (grpc.secure_channel(target, grpc.ssl_channel_credentials())
+ if secure else grpc.insecure_channel(target))
+
+
+def answers(address: str, *, timeout: float = PROBE_TIMEOUT) -> bool:
+ """不带令牌调 `GetSystemInfo`,正常应答才算这个地址上有 CloudDrive2。"""
+ request_type, response_type = _METHODS["GetSystemInfo"]
+ with open_channel(address) as channel:
+ stub = channel.unary_unary(
+ SERVICE + "GetSystemInfo", request_serializer=request_type.SerializeToString,
+ response_deserializer=response_type.FromString)
+ try:
+ stub(request_type(), timeout=timeout)
+ except grpc.RpcError:
+ return False
+ return True
+
+
+def discover(addresses: tuple[str, ...] = LOCAL_ADDRESSES) -> str:
+ """按顺序试,返回第一个应答的地址;都不应答时报错并原样列出试过的地址。"""
+ for address in addresses:
+ if answers(address):
+ return address
+ tried = "、".join(addresses)
+ raise DownloadError("network", f"没有填 CloudDrive2 地址,本机 {tried} 都没有应答。"
+ "确认 CloudDrive2 已启动,或在地址栏填上它的实际地址")
+
+
def _translate(error: grpc.RpcError, action: str) -> DownloadError:
code = error.code() if hasattr(error, "code") else None
details = (error.details() if hasattr(error, "details") else "") or ""
@@ -91,19 +127,14 @@ class Folder:
class CloudDriveClient:
- """六个方法的薄封装。`channel` 由测试注入,指向进程内的假服务端。"""
+ """要令牌的那六个方法的薄封装。"""
- def __init__(self, address: str, token: str, *, channel: grpc.Channel | None = None,
- timeout: float = CALL_TIMEOUT):
+ def __init__(self, address: str, token: str, *, timeout: float = CALL_TIMEOUT):
if not token:
raise DownloadError("config", "还没有填 CloudDrive2 的 API 令牌")
self.token = token
self.timeout = timeout
- if channel is None:
- target, secure = channel_target(address)
- channel = (grpc.secure_channel(target, grpc.ssl_channel_credentials())
- if secure else grpc.insecure_channel(target))
- self.channel = channel
+ self.channel = open_channel(address)
def close(self) -> None:
self.channel.close()
@@ -202,16 +233,14 @@ class CloudDriveProvider:
key = "115"
- def __init__(self, address: str, token: str, *, channel_factory=None):
+ def __init__(self, address: str, token: str):
self.address = address
self.token = token
- self.channel_factory = channel_factory
def client(self) -> CloudDriveClient:
if not self.address:
- raise DownloadError("config", "还没有填 CloudDrive2 地址")
- channel = self.channel_factory() if self.channel_factory else None
- return CloudDriveClient(self.address, self.token, channel=channel)
+ raise DownloadError("config", "还没有填 CloudDrive2 地址,先在设置页「检查」探测本机端口后保存")
+ return CloudDriveClient(self.address, self.token)
def submit(self, magnet: Magnet, target: str) -> RemoteStatus:
with self.client() as client:
@@ -251,15 +280,26 @@ class CloudDriveProvider:
client.remove(client.folder(task.target), task.info_hash or "")
-def check(address: str, token: str, target: str, *, channel_factory=None) -> dict:
+def check(address: str, token: str, target: str, *,
+ local_addresses: tuple[str, ...] = LOCAL_ADDRESSES) -> dict:
"""设置页的「检查」:令牌有没有离线权限、目标目录能不能离线、115 还剩多少配额。
- 只读:不提交、不取消。每一项各自报,一项失败不挡住其余几项。
+ 地址留空时先按 `local_addresses` 的顺序探测,报告的 `address` 是实际查的那个,页面把它
+ 填回表单,用户保存后才落盘。只读:不提交、不取消。令牌一关过不去时 `ok` 为假;之后的
+ 目录与配额各自报进 `problems`。
"""
- provider = CloudDriveProvider(address, token, channel_factory=channel_factory)
- report: dict = {"ok": True, "permissions": [], "missing": [], "root": "", "folder": None,
- "quota": None, "problems": []}
- with provider.client() as client:
+ report: dict = {"ok": True, "address": address or discover(local_addresses), "permissions": [],
+ "missing": [], "root": "", "folder": None, "quota": None, "problems": []}
+ try:
+ _inspect(report, CloudDriveClient(report["address"], token), target)
+ except DownloadError as error:
+ report["ok"] = False
+ report["problems"].append(error.detail)
+ return report
+
+
+def _inspect(report: dict, client: CloudDriveClient, target: str) -> None:
+ with client:
info = client.token_info()
permissions = info.permissions
report["root"] = info.rootDir
@@ -270,18 +310,17 @@ def check(address: str, token: str, target: str, *, channel_factory=None) -> dic
report["missing"].append(label)
if not target:
report["problems"].append("还没有填 115 目标目录")
- return report
+ return
try:
folder = client.folder(target)
except DownloadError as error:
report["problems"].append(error.detail)
- return report
+ return
report["folder"] = {"path": folder.path, "can_offline": folder.can_offline,
"cloud": folder.cloud_name}
try:
quota = client.quota(folder)
except DownloadError as error:
report["problems"].append(error.detail)
- return report
+ return
report["quota"] = {"total": quota.total, "used": quota.used, "left": quota.left}
- return report
diff --git a/src/peach/downloads_clouddrive_pb2.py b/src/peach/downloads_clouddrive_pb2.py
index 533752cdc..8446c9465 100644
--- a/src/peach/downloads_clouddrive_pb2.py
+++ b/src/peach/downloads_clouddrive_pb2.py
@@ -22,47 +22,50 @@ _runtime_version.ValidateProtobufRuntimeVersion(
_sym_db = _symbol_database.Default()
+from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
-DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1a\x64ownloads_clouddrive.proto\x12\nclouddrive\"\x1c\n\x0bStringValue\x12\r\n\x05value\x18\x01 \x01(\t\"\x9d\x01\n\tTokenInfo\x12\r\n\x05token\x18\x01 \x01(\t\x12\x0f\n\x07rootDir\x18\x02 \x01(\t\x12\x31\n\x0bpermissions\x18\x03 \x01(\x0b\x32\x1c.clouddrive.TokenPermissions\x12\x17\n\nexpires_in\x18\x04 \x01(\x04H\x00\x88\x01\x01\x12\x15\n\rfriendly_name\x18\x05 \x01(\tB\r\n\x0b_expires_in\"\x98\x01\n\x10TokenPermissions\x12\x12\n\nallow_list\x18\x01 \x01(\x08\x12\"\n\x1a\x61llow_add_offline_download\x18\x10 \x01(\x08\x12$\n\x1c\x61llow_list_offline_downloads\x18\x11 \x01(\x08\x12&\n\x1e\x61llow_modify_offline_downloads\x18\x12 \x01(\x08\"9\n\x15\x46indFileByPathRequest\x12\x12\n\nparentPath\x18\x01 \x01(\t\x12\x0c\n\x04path\x18\x02 \x01(\t\"X\n\x08\x43loudAPI\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x10\n\x08userName\x18\x02 \x01(\t\x12\x10\n\x08nickName\x18\x03 \x01(\t\x12\x11\n\x04path\x18\n \x01(\tH\x00\x88\x01\x01\x42\x07\n\x05_path\"\xd1\x01\n\x0e\x43loudDriveFile\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x14\n\x0c\x66ullPathName\x18\x03 \x01(\t\x12\x0c\n\x04size\x18\x04 \x01(\x03\x12&\n\x08\x43loudAPI\x18\t \x01(\x0b\x32\x14.clouddrive.CloudAPI\x12\x13\n\x0bisDirectory\x18\x1e \x01(\x08\x12\x1a\n\x12\x63\x61nOfflineDownload\x18\x42 \x01(\x08\x12(\n supportOfflineDownloadManagement\x18K \x01(\x08\"s\n\x15\x41\x64\x64OfflineFileRequest\x12\x0c\n\x04urls\x18\x01 \x01(\t\x12\x10\n\x08toFolder\x18\x02 \x01(\t\x12!\n\x14\x63heckFolderAfterSecs\x18\x03 \x01(\x04H\x00\x88\x01\x01\x42\x17\n\x15_checkFolderAfterSecs\"U\n\x13\x46ileOperationResult\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x14\n\x0c\x65rrorMessage\x18\x02 \x01(\t\x12\x17\n\x0fresultFilePaths\x18\x03 \x03(\t\"\x8b\x01\n\x19RemoveOfflineFilesRequest\x12\x11\n\tcloudName\x18\x01 \x01(\t\x12\x16\n\x0e\x63loudAccountId\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65leteFiles\x18\x03 \x01(\x08\x12\x12\n\ninfoHashes\x18\x04 \x03(\t\x12\x11\n\x04path\x18\x05 \x01(\tH\x00\x88\x01\x01\x42\x07\n\x05_path\"G\n\x0b\x46ileRequest\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x19\n\x0c\x66orceRefresh\x18\x02 \x01(\x08H\x00\x88\x01\x01\x42\x0f\n\r_forceRefresh\"\xcf\x01\n\x0bOfflineFile\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04size\x18\x02 \x01(\x04\x12\x0b\n\x03url\x18\x03 \x01(\t\x12-\n\x06status\x18\x04 \x01(\x0e\x32\x1d.clouddrive.OfflineFileStatus\x12\x10\n\x08infoHash\x18\x05 \x01(\t\x12\x0e\n\x06\x66ileId\x18\x06 \x01(\t\x12\x10\n\x08\x61\x64\x64_time\x18\x07 \x01(\x04\x12\x10\n\x08parentId\x18\x08 \x01(\t\x12\x13\n\x0bpercendDone\x18\t \x01(\x01\x12\r\n\x05peers\x18\n \x01(\x04\"-\n\rOfflineStatus\x12\r\n\x05quota\x18\x01 \x01(\r\x12\r\n\x05total\x18\x02 \x01(\r\"q\n\x15OfflineFileListResult\x12-\n\x0cofflineFiles\x18\x01 \x03(\x0b\x32\x17.clouddrive.OfflineFile\x12)\n\x06status\x18\x02 \x01(\x0b\x32\x19.clouddrive.OfflineStatus\"\\\n\x13OfflineQuotaRequest\x12\x11\n\tcloudName\x18\x01 \x01(\t\x12\x16\n\x0e\x63loudAccountId\x18\x02 \x01(\t\x12\x11\n\x04path\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\x07\n\x05_path\"=\n\x10OfflineQuotaInfo\x12\r\n\x05total\x18\x01 \x01(\x05\x12\x0c\n\x04used\x18\x02 \x01(\x05\x12\x0c\n\x04left\x18\x03 \x01(\x05*|\n\x11OfflineFileStatus\x12\x10\n\x0cOFFLINE_INIT\x10\x00\x12\x17\n\x13OFFLINE_DOWNLOADING\x10\x01\x12\x14\n\x10OFFLINE_FINISHED\x10\x02\x12\x11\n\rOFFLINE_ERROR\x10\x03\x12\x13\n\x0fOFFLINE_UNKNOWN\x10\x04\x32\x94\x04\n\x11\x43loudDriveFileSrv\x12\x43\n\x0fGetApiTokenInfo\x12\x17.clouddrive.StringValue\x1a\x15.clouddrive.TokenInfo\"\x00\x12Q\n\x0e\x46indFileByPath\x12!.clouddrive.FindFileByPathRequest\x1a\x1a.clouddrive.CloudDriveFile\"\x00\x12W\n\x0f\x41\x64\x64OfflineFiles\x12!.clouddrive.AddOfflineFileRequest\x1a\x1f.clouddrive.FileOperationResult\"\x00\x12^\n\x12RemoveOfflineFiles\x12%.clouddrive.RemoveOfflineFilesRequest\x1a\x1f.clouddrive.FileOperationResult\"\x00\x12V\n\x16ListOfflineFilesByPath\x12\x17.clouddrive.FileRequest\x1a!.clouddrive.OfflineFileListResult\"\x00\x12V\n\x13GetOfflineQuotaInfo\x12\x1f.clouddrive.OfflineQuotaRequest\x1a\x1c.clouddrive.OfflineQuotaInfo\"\x00\x62\x06proto3')
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1a\x64ownloads_clouddrive.proto\x12\nclouddrive\x1a\x1bgoogle/protobuf/empty.proto\"N\n\x14\x43loudDriveSystemInfo\x12\x0f\n\x07IsLogin\x18\x01 \x01(\x08\x12\x10\n\x08UserName\x18\x02 \x01(\t\x12\x13\n\x0bSystemReady\x18\x03 \x01(\x08\"\x1c\n\x0bStringValue\x12\r\n\x05value\x18\x01 \x01(\t\"\x9d\x01\n\tTokenInfo\x12\r\n\x05token\x18\x01 \x01(\t\x12\x0f\n\x07rootDir\x18\x02 \x01(\t\x12\x31\n\x0bpermissions\x18\x03 \x01(\x0b\x32\x1c.clouddrive.TokenPermissions\x12\x17\n\nexpires_in\x18\x04 \x01(\x04H\x00\x88\x01\x01\x12\x15\n\rfriendly_name\x18\x05 \x01(\tB\r\n\x0b_expires_in\"\x98\x01\n\x10TokenPermissions\x12\x12\n\nallow_list\x18\x01 \x01(\x08\x12\"\n\x1a\x61llow_add_offline_download\x18\x10 \x01(\x08\x12$\n\x1c\x61llow_list_offline_downloads\x18\x11 \x01(\x08\x12&\n\x1e\x61llow_modify_offline_downloads\x18\x12 \x01(\x08\"9\n\x15\x46indFileByPathRequest\x12\x12\n\nparentPath\x18\x01 \x01(\t\x12\x0c\n\x04path\x18\x02 \x01(\t\"X\n\x08\x43loudAPI\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x10\n\x08userName\x18\x02 \x01(\t\x12\x10\n\x08nickName\x18\x03 \x01(\t\x12\x11\n\x04path\x18\n \x01(\tH\x00\x88\x01\x01\x42\x07\n\x05_path\"\xd1\x01\n\x0e\x43loudDriveFile\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x14\n\x0c\x66ullPathName\x18\x03 \x01(\t\x12\x0c\n\x04size\x18\x04 \x01(\x03\x12&\n\x08\x43loudAPI\x18\t \x01(\x0b\x32\x14.clouddrive.CloudAPI\x12\x13\n\x0bisDirectory\x18\x1e \x01(\x08\x12\x1a\n\x12\x63\x61nOfflineDownload\x18\x42 \x01(\x08\x12(\n supportOfflineDownloadManagement\x18K \x01(\x08\"s\n\x15\x41\x64\x64OfflineFileRequest\x12\x0c\n\x04urls\x18\x01 \x01(\t\x12\x10\n\x08toFolder\x18\x02 \x01(\t\x12!\n\x14\x63heckFolderAfterSecs\x18\x03 \x01(\x04H\x00\x88\x01\x01\x42\x17\n\x15_checkFolderAfterSecs\"U\n\x13\x46ileOperationResult\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x14\n\x0c\x65rrorMessage\x18\x02 \x01(\t\x12\x17\n\x0fresultFilePaths\x18\x03 \x03(\t\"\x8b\x01\n\x19RemoveOfflineFilesRequest\x12\x11\n\tcloudName\x18\x01 \x01(\t\x12\x16\n\x0e\x63loudAccountId\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65leteFiles\x18\x03 \x01(\x08\x12\x12\n\ninfoHashes\x18\x04 \x03(\t\x12\x11\n\x04path\x18\x05 \x01(\tH\x00\x88\x01\x01\x42\x07\n\x05_path\"G\n\x0b\x46ileRequest\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x19\n\x0c\x66orceRefresh\x18\x02 \x01(\x08H\x00\x88\x01\x01\x42\x0f\n\r_forceRefresh\"\xcf\x01\n\x0bOfflineFile\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04size\x18\x02 \x01(\x04\x12\x0b\n\x03url\x18\x03 \x01(\t\x12-\n\x06status\x18\x04 \x01(\x0e\x32\x1d.clouddrive.OfflineFileStatus\x12\x10\n\x08infoHash\x18\x05 \x01(\t\x12\x0e\n\x06\x66ileId\x18\x06 \x01(\t\x12\x10\n\x08\x61\x64\x64_time\x18\x07 \x01(\x04\x12\x10\n\x08parentId\x18\x08 \x01(\t\x12\x13\n\x0bpercendDone\x18\t \x01(\x01\x12\r\n\x05peers\x18\n \x01(\x04\"-\n\rOfflineStatus\x12\r\n\x05quota\x18\x01 \x01(\r\x12\r\n\x05total\x18\x02 \x01(\r\"q\n\x15OfflineFileListResult\x12-\n\x0cofflineFiles\x18\x01 \x03(\x0b\x32\x17.clouddrive.OfflineFile\x12)\n\x06status\x18\x02 \x01(\x0b\x32\x19.clouddrive.OfflineStatus\"\\\n\x13OfflineQuotaRequest\x12\x11\n\tcloudName\x18\x01 \x01(\t\x12\x16\n\x0e\x63loudAccountId\x18\x02 \x01(\t\x12\x11\n\x04path\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\x07\n\x05_path\"=\n\x10OfflineQuotaInfo\x12\r\n\x05total\x18\x01 \x01(\x05\x12\x0c\n\x04used\x18\x02 \x01(\x05\x12\x0c\n\x04left\x18\x03 \x01(\x05*|\n\x11OfflineFileStatus\x12\x10\n\x0cOFFLINE_INIT\x10\x00\x12\x17\n\x13OFFLINE_DOWNLOADING\x10\x01\x12\x14\n\x10OFFLINE_FINISHED\x10\x02\x12\x11\n\rOFFLINE_ERROR\x10\x03\x12\x13\n\x0fOFFLINE_UNKNOWN\x10\x04\x32\xe1\x04\n\x11\x43loudDriveFileSrv\x12K\n\rGetSystemInfo\x12\x16.google.protobuf.Empty\x1a .clouddrive.CloudDriveSystemInfo\"\x00\x12\x43\n\x0fGetApiTokenInfo\x12\x17.clouddrive.StringValue\x1a\x15.clouddrive.TokenInfo\"\x00\x12Q\n\x0e\x46indFileByPath\x12!.clouddrive.FindFileByPathRequest\x1a\x1a.clouddrive.CloudDriveFile\"\x00\x12W\n\x0f\x41\x64\x64OfflineFiles\x12!.clouddrive.AddOfflineFileRequest\x1a\x1f.clouddrive.FileOperationResult\"\x00\x12^\n\x12RemoveOfflineFiles\x12%.clouddrive.RemoveOfflineFilesRequest\x1a\x1f.clouddrive.FileOperationResult\"\x00\x12V\n\x16ListOfflineFilesByPath\x12\x17.clouddrive.FileRequest\x1a!.clouddrive.OfflineFileListResult\"\x00\x12V\n\x13GetOfflineQuotaInfo\x12\x1f.clouddrive.OfflineQuotaRequest\x1a\x1c.clouddrive.OfflineQuotaInfo\"\x00\x62\x06proto3')
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'downloads_clouddrive_pb2', _globals)
if not _descriptor._USE_C_DESCRIPTORS:
DESCRIPTOR._loaded_options = None
- _globals['_OFFLINEFILESTATUS']._serialized_start=1696
- _globals['_OFFLINEFILESTATUS']._serialized_end=1820
- _globals['_STRINGVALUE']._serialized_start=42
- _globals['_STRINGVALUE']._serialized_end=70
- _globals['_TOKENINFO']._serialized_start=73
- _globals['_TOKENINFO']._serialized_end=230
- _globals['_TOKENPERMISSIONS']._serialized_start=233
- _globals['_TOKENPERMISSIONS']._serialized_end=385
- _globals['_FINDFILEBYPATHREQUEST']._serialized_start=387
- _globals['_FINDFILEBYPATHREQUEST']._serialized_end=444
- _globals['_CLOUDAPI']._serialized_start=446
- _globals['_CLOUDAPI']._serialized_end=534
- _globals['_CLOUDDRIVEFILE']._serialized_start=537
- _globals['_CLOUDDRIVEFILE']._serialized_end=746
- _globals['_ADDOFFLINEFILEREQUEST']._serialized_start=748
- _globals['_ADDOFFLINEFILEREQUEST']._serialized_end=863
- _globals['_FILEOPERATIONRESULT']._serialized_start=865
- _globals['_FILEOPERATIONRESULT']._serialized_end=950
- _globals['_REMOVEOFFLINEFILESREQUEST']._serialized_start=953
- _globals['_REMOVEOFFLINEFILESREQUEST']._serialized_end=1092
- _globals['_FILEREQUEST']._serialized_start=1094
- _globals['_FILEREQUEST']._serialized_end=1165
- _globals['_OFFLINEFILE']._serialized_start=1168
- _globals['_OFFLINEFILE']._serialized_end=1375
- _globals['_OFFLINESTATUS']._serialized_start=1377
- _globals['_OFFLINESTATUS']._serialized_end=1422
- _globals['_OFFLINEFILELISTRESULT']._serialized_start=1424
- _globals['_OFFLINEFILELISTRESULT']._serialized_end=1537
- _globals['_OFFLINEQUOTAREQUEST']._serialized_start=1539
- _globals['_OFFLINEQUOTAREQUEST']._serialized_end=1631
- _globals['_OFFLINEQUOTAINFO']._serialized_start=1633
- _globals['_OFFLINEQUOTAINFO']._serialized_end=1694
- _globals['_CLOUDDRIVEFILESRV']._serialized_start=1823
- _globals['_CLOUDDRIVEFILESRV']._serialized_end=2355
+ _globals['_OFFLINEFILESTATUS']._serialized_start=1805
+ _globals['_OFFLINEFILESTATUS']._serialized_end=1929
+ _globals['_CLOUDDRIVESYSTEMINFO']._serialized_start=71
+ _globals['_CLOUDDRIVESYSTEMINFO']._serialized_end=149
+ _globals['_STRINGVALUE']._serialized_start=151
+ _globals['_STRINGVALUE']._serialized_end=179
+ _globals['_TOKENINFO']._serialized_start=182
+ _globals['_TOKENINFO']._serialized_end=339
+ _globals['_TOKENPERMISSIONS']._serialized_start=342
+ _globals['_TOKENPERMISSIONS']._serialized_end=494
+ _globals['_FINDFILEBYPATHREQUEST']._serialized_start=496
+ _globals['_FINDFILEBYPATHREQUEST']._serialized_end=553
+ _globals['_CLOUDAPI']._serialized_start=555
+ _globals['_CLOUDAPI']._serialized_end=643
+ _globals['_CLOUDDRIVEFILE']._serialized_start=646
+ _globals['_CLOUDDRIVEFILE']._serialized_end=855
+ _globals['_ADDOFFLINEFILEREQUEST']._serialized_start=857
+ _globals['_ADDOFFLINEFILEREQUEST']._serialized_end=972
+ _globals['_FILEOPERATIONRESULT']._serialized_start=974
+ _globals['_FILEOPERATIONRESULT']._serialized_end=1059
+ _globals['_REMOVEOFFLINEFILESREQUEST']._serialized_start=1062
+ _globals['_REMOVEOFFLINEFILESREQUEST']._serialized_end=1201
+ _globals['_FILEREQUEST']._serialized_start=1203
+ _globals['_FILEREQUEST']._serialized_end=1274
+ _globals['_OFFLINEFILE']._serialized_start=1277
+ _globals['_OFFLINEFILE']._serialized_end=1484
+ _globals['_OFFLINESTATUS']._serialized_start=1486
+ _globals['_OFFLINESTATUS']._serialized_end=1531
+ _globals['_OFFLINEFILELISTRESULT']._serialized_start=1533
+ _globals['_OFFLINEFILELISTRESULT']._serialized_end=1646
+ _globals['_OFFLINEQUOTAREQUEST']._serialized_start=1648
+ _globals['_OFFLINEQUOTAREQUEST']._serialized_end=1740
+ _globals['_OFFLINEQUOTAINFO']._serialized_start=1742
+ _globals['_OFFLINEQUOTAINFO']._serialized_end=1803
+ _globals['_CLOUDDRIVEFILESRV']._serialized_start=1932
+ _globals['_CLOUDDRIVEFILESRV']._serialized_end=2541
# @@protoc_insertion_point(module_scope)
diff --git a/src/peach/web_downloads.py b/src/peach/web_downloads.py
index 6bc013225..bb733bf41 100644
--- a/src/peach/web_downloads.py
+++ b/src/peach/web_downloads.py
@@ -119,10 +119,14 @@ def save_settings(service: DownloadService, body: dict, declared_roots) -> dict:
def check_clouddrive(service: DownloadService, body: dict) -> dict:
- """「检查」按页面上此刻填的值查,没填的取已保存的。只读,不提交也不取消。"""
+ """「检查」按页面上此刻填的值查,没带的字段取已保存的。只读,不提交也不取消。
+
+ 页面带来的地址是空串时探测本机端口;报告里的 `address` 由页面填回表单,不在这里保存。
+ """
from .downloads_clouddrive import check
body = body if isinstance(body, dict) else {}
- address = clean_address(body.get("clouddrive_address") or service.config.clouddrive_address)
+ address = clean_address(body["clouddrive_address"] if "clouddrive_address" in body
+ else service.config.clouddrive_address)
token = str(body.get("token") or "").strip() or _values(
service.credentials, CLOUDDRIVE_CREDENTIAL).get("token", "")
raw_target = str(body.get("target") or service.config.targets.get("115", "")).strip()
@@ -130,8 +134,8 @@ def check_clouddrive(service: DownloadService, body: dict) -> dict:
try:
return check(address, token, target)
except DownloadError as error:
- return {"ok": False, "permissions": [], "missing": [], "root": "", "folder": None,
- "quota": None, "problems": [error.detail]}
+ return {"ok": False, "address": address, "permissions": [], "missing": [], "root": "",
+ "folder": None, "quota": None, "problems": [error.detail]}
def pikpak_login(service: DownloadService, body: dict, declared_roots, *, transport=None) -> dict:
diff --git a/tests/test_downloads_clouddrive.py b/tests/test_downloads_clouddrive.py
index c781a0708..87d5f54c7 100644
--- a/tests/test_downloads_clouddrive.py
+++ b/tests/test_downloads_clouddrive.py
@@ -1,10 +1,12 @@
"""115 云下载经 CloudDrive2 gRPC:起一个进程内的假服务端,走真实的序列化与元数据。
-假服务端只实现那六个方法,状态放在内存里。断言落在「Peach 发出去的是什么」上:令牌只在
-`authorization` 元数据里,提交前先查目录与配额,已有同一 infohash 的任务就不再提交。
+假服务端只实现那七个方法,状态放在内存里。断言落在「Peach 发出去的是什么」上:令牌只在
+`authorization` 元数据里,提交前先查目录与配额,已有同一 infohash 的任务就不再提交,
+地址留空时只用不带令牌的 `GetSystemInfo` 探测。
"""
from __future__ import annotations
+import socket
import unittest
from concurrent import futures
@@ -35,6 +37,11 @@ class FakeCloudDrive:
if header != f"Bearer {TOKEN}":
context.abort(grpc.StatusCode.UNAUTHENTICATED, "bad token")
+ def GetSystemInfo(self, request, context):
+ header = dict(context.invocation_metadata()).get("authorization", "")
+ self.calls.append(("GetSystemInfo", request, header))
+ return pb.CloudDriveSystemInfo(IsLogin=True, UserName="u1", SystemReady=True)
+
def GetApiTokenInfo(self, request, context):
self._auth("GetApiTokenInfo", request, context)
return pb.TokenInfo(token=request.value, rootDir="/", permissions=pb.TokenPermissions(
@@ -73,22 +80,33 @@ class FakeCloudDrive:
return self.quota
+def closed_address() -> str:
+ """本机一个刚放开、没人在听的端口。"""
+ with socket.socket() as probe:
+ probe.bind(("127.0.0.1", 0))
+ port = probe.getsockname()[1]
+ return f"http://127.0.0.1:{port}"
+
+
class _Server(unittest.TestCase):
def setUp(self):
self.fake = FakeCloudDrive()
+ self.server, self.address = self.serve(self.fake)
+ self.provider = cd.CloudDriveProvider(self.address, TOKEN)
+
+ def serve(self, fake: FakeCloudDrive) -> tuple[grpc.Server, str]:
handlers = {
name: grpc.unary_unary_rpc_method_handler(
- getattr(self.fake, name), request_deserializer=request.FromString,
+ getattr(fake, name), request_deserializer=request.FromString,
response_serializer=response.SerializeToString)
for name, (request, response) in cd._METHODS.items()}
- self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=2))
- self.server.add_generic_rpc_handlers(
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=2))
+ server.add_generic_rpc_handlers(
(grpc.method_handlers_generic_handler("clouddrive.CloudDriveFileSrv", handlers),))
- port = self.server.add_insecure_port("127.0.0.1:0")
- self.server.start()
- self.addCleanup(self.server.stop, None)
- self.address = f"http://127.0.0.1:{port}"
- self.provider = cd.CloudDriveProvider(self.address, TOKEN)
+ port = server.add_insecure_port("127.0.0.1:0")
+ server.start()
+ self.addCleanup(server.stop, None)
+ return server, f"http://127.0.0.1:{port}"
def methods(self) -> list[str]:
return [name for name, _request, _header in self.fake.calls]
@@ -188,13 +206,43 @@ class CheckTests(_Server):
self.assertEqual(report["folder"], {"path": TARGET, "can_offline": True, "cloud": "115open"})
self.assertEqual(report["quota"], {"total": 1500, "used": 3, "left": 1497})
self.assertEqual(report["problems"], [])
+ self.assertEqual(report["address"], self.address)
self.assertNotIn("AddOfflineFiles", self.methods())
+ self.assertNotIn("GetSystemInfo", self.methods())
def test_without_a_token_nothing_is_called(self):
- with self.assertRaises(dl.DownloadError):
- cd.check(self.address, "", TARGET)
+ report = cd.check(self.address, "", TARGET)
+ self.assertFalse(report["ok"])
+ self.assertIn("API 令牌", report["problems"][0])
self.assertEqual(self.fake.calls, [])
+ def test_a_blank_address_takes_the_first_local_address_that_answers(self):
+ second = FakeCloudDrive()
+ _server, second_address = self.serve(second)
+ report = cd.check("", TOKEN, TARGET, local_addresses=(self.address, second_address))
+ self.assertEqual((report["ok"], report["address"]), (True, self.address))
+ self.assertEqual(self.methods()[0], "GetSystemInfo")
+ self.assertEqual(self.fake.calls[0][2], "")
+ self.assertEqual(second.calls, [])
+
+ def test_a_blank_address_falls_through_to_the_second_local_address(self):
+ report = cd.check("", TOKEN, TARGET, local_addresses=(closed_address(), self.address))
+ self.assertEqual(report["address"], self.address)
+ self.assertEqual(report["quota"], {"total": 1500, "used": 3, "left": 1497})
+
+ def test_a_blank_address_without_a_token_still_finds_the_address(self):
+ report = cd.check("", "", TARGET, local_addresses=(self.address,))
+ self.assertEqual((report["ok"], report["address"]), (False, self.address))
+ self.assertEqual(self.methods(), ["GetSystemInfo"])
+
+ def test_no_local_address_answering_lists_every_address_tried(self):
+ tried = (closed_address(), closed_address())
+ with self.assertRaises(dl.DownloadError) as caught:
+ cd.check("", TOKEN, TARGET, local_addresses=tried)
+ self.assertEqual(caught.exception.failure, "network")
+ for address in tried:
+ self.assertIn(address, caught.exception.detail)
+
def test_addresses_turn_into_grpc_targets(self):
self.assertEqual(cd.channel_target("http://127.0.0.1"), ("127.0.0.1:19798", False))
self.assertEqual(cd.channel_target("https://192.0.2.10:8443"), ("192.0.2.10:8443", True))
diff --git a/web/dist/peach-react.js b/web/dist/peach-react.js
index cfeb4a75f..518df0930 100644
--- a/web/dist/peach-react.js
+++ b/web/dist/peach-react.js
@@ -48392,7 +48392,7 @@ function vge({ initial: e, receipt: t }) {
})] });
}
function yge({ state: e, settle: t, receipt: n }) {
- let [r, i] = (0, R.useState)(e.config), [a, o] = (0, R.useState)(""), [s, c] = (0, R.useState)(String(e.config.wait_hours)), [l, u] = (0, R.useState)(null), [d, f] = (0, R.useState)(""), p = ra(), m = (e) => r.targets[e] ?? "", h = (e, t) => i({
+ let [r, i] = (0, R.useState)(e.config), [a, o] = (0, R.useState)(""), [s, c] = (0, R.useState)(String(e.config.wait_hours)), [l, u] = (0, R.useState)(null), [d, f] = (0, R.useState)(""), [p, m] = (0, R.useState)(""), h = ra(), g = (e) => r.targets[e] ?? "", _ = (e, t) => i({
...r,
targets: {
...r.targets,
@@ -48408,16 +48408,16 @@ function yge({ state: e, settle: t, receipt: n }) {
wait_hours: s,
token: a
};
- p.run("save", (e) => G(mge, l, "POST", e), (e) => {
- t(e), i(e.config), c(String(e.config.wait_hours)), o(""), f(""), n("已保存配置");
- }, (e) => f(U(e)));
+ h.run("save", (e) => G(mge, l, "POST", e), (e) => {
+ t(e), i(e.config), c(String(e.config.wait_hours)), o(""), m(""), n("已保存配置");
+ }, (e) => m(U(e)));
},
children: [
/* @__PURE__ */ (0, z.jsxs)(Oy, { children: [
/* @__PURE__ */ (0, z.jsx)(Ay, { children: "把磁力交给 115 或 PikPak 离线下载,文件落在已挂载的网盘目录,再由推送发现登记入库,不经过这台电脑。 115 每个任务扣一条离线配额(年费会员每月 1500 条、月费 200 条),被判违规的资源不重试。" }),
/* @__PURE__ */ (0, z.jsx)(my, {
label: "CloudDrive2 地址",
- placeholder: "http://127.0.0.1:19798",
+ placeholder: "留空自动探测本机 19798 / 29798",
autoComplete: "off",
maxLength: 200,
value: r.clouddrive_address,
@@ -48444,9 +48444,9 @@ function yge({ state: e, settle: t, receipt: n }) {
autoComplete: "off",
maxLength: 300,
hint: "CloudDrive2 挂载树里的路径。这个目录要落在「推送发现」的某个云端路径前缀下面,下载完才找得到。",
- value: m("115"),
+ value: g("115"),
isDisabled: !e.available,
- onChange: (e) => h("115", e)
+ onChange: (e) => _("115", e)
}),
/* @__PURE__ */ (0, z.jsx)(my, {
label: "PikPak 目标目录",
@@ -48454,9 +48454,9 @@ function yge({ state: e, settle: t, receipt: n }) {
autoComplete: "off",
maxLength: 300,
hint: "PikPak 网盘里的路径,目录要已经存在。",
- value: m("pikpak"),
+ value: g("pikpak"),
isDisabled: !e.available,
- onChange: (e) => h("pikpak", e)
+ onChange: (e) => _("pikpak", e)
}),
/* @__PURE__ */ (0, z.jsxs)("div", {
className: "flex flex-col gap-1",
@@ -48486,41 +48486,51 @@ function yge({ state: e, settle: t, receipt: n }) {
onChange: c
})
] }),
- l ? /* @__PURE__ */ (0, z.jsx)(bge, { report: l }) : null,
- d || p.error ? /* @__PURE__ */ (0, z.jsx)(Oy, {
+ l ? /* @__PURE__ */ (0, z.jsx)(bge, {
+ report: l,
+ detected: d
+ }) : null,
+ p || h.error ? /* @__PURE__ */ (0, z.jsx)(Oy, {
divided: !0,
- children: /* @__PURE__ */ (0, z.jsx)(jy, { children: d || p.error })
+ children: /* @__PURE__ */ (0, z.jsx)(jy, { children: p || h.error })
}) : null,
/* @__PURE__ */ (0, z.jsxs)(ky, {
status: e.available ? void 0 : "云下载只在账本写入端可用。",
children: [/* @__PURE__ */ (0, z.jsx)(H, {
onClick: () => {
- let e = {
+ let e = !r.clouddrive_address.trim(), t = {
clouddrive_address: r.clouddrive_address,
token: a,
- target: m("115")
+ target: g("115")
};
- p.run("check", (t) => G(hge, e, "POST", t), (e) => {
- u(e), f("");
- }, (e) => f(U(e)));
+ h.run("check", (e) => G(hge, t, "POST", e), (t) => {
+ e && t.address && i((e) => ({
+ ...e,
+ clouddrive_address: t.address
+ })), u(t), f(e ? t.address : ""), m("");
+ }, (e) => m(U(e)));
},
disabled: !e.available,
- ...q(p.busy === "check"),
+ ...q(h.busy === "check"),
children: "检查"
}), /* @__PURE__ */ (0, z.jsx)(H, {
type: "submit",
disabled: !e.available,
- ...q(p.busy === "save"),
+ ...q(h.busy === "save"),
children: "保存配置"
})]
})
]
});
}
-function bge({ report: e }) {
+function bge({ report: e, detected: t }) {
return /* @__PURE__ */ (0, z.jsxs)(Oy, {
divided: !0,
children: [/* @__PURE__ */ (0, z.jsxs)(Py, { children: [
+ t ? /* @__PURE__ */ (0, z.jsx)(Fy, {
+ term: "CloudDrive2 地址",
+ children: `探测到 ${t},保存配置后生效`
+ }) : null,
e.permissions.length ? /* @__PURE__ */ (0, z.jsx)(Fy, {
term: "离线权限",
children: e.missing.length ? `缺少:${e.missing.join("、")}` : "齐全"