diff --git a/plugins/dagu-transfer/CHANGELOG.md b/plugins/dagu-transfer/CHANGELOG.md new file mode 100644 index 000000000..a7fef6d20 --- /dev/null +++ b/plugins/dagu-transfer/CHANGELOG.md @@ -0,0 +1,20 @@ +# Changelog + +## 1.0.0 - 2026-11-26 + +### 新增 + +- 「分享」:把图片或文件上传到本地目录或 SSH 服务器。下拉列表里选目标,默认选中上次使用的,回车或点击即上传;成功后目标路径复制到剪贴板并自动收起,失败可回车重试。 +- 「下载文件」:从 SSH 服务器下载到本机下载目录。在 ZTools 里输入或粘贴远端路径后选「下载远端文件」,选服务器即可下载;也可以先选服务器,再在搜索框里粘贴路径。成功后本机路径复制到剪贴板,可回车打开所在文件夹。下载类指令用向下箭头的图标,与上传区分。 +- 「分享本地文件」:在 ZTools 里粘贴或输入本地文件路径,直接上传这个文件。 +- 「快传配置」:管理上传目标(本地目录 / SSH 服务器)与下载目录。 +- 接收「大古截图」的分享:在截图工具条点「分享」后直接进入上传列表。 +- SSH 密码登录:服务器目标可以填写登录密码,上传和下载都按它登录;不填照旧免密登录(密钥 / `~/.ssh/config` / Agent)。密码只交给系统自带的 scp 去用,不写进命令行也不落盘;密码错误只尝试一次。目前只支持 Windows。 +- 登录密码的保存与大古截图的密钥一致:默认只保存在本机,打开「同步密钥」后才写入 ZTools 的 `dbStorage` 并随备份同步,关闭开关删除同步副本。 +- 跟随 ZTools 的深浅色与主题色:目标列表和配置页在深色下用深色配色。 +- 配置页的 SSH 服务器表单新增独立的「用户名(可选)」输入框:填了则以它为准拼成 `用户名@主机`(主机框里已带的账号前缀会被替换),留空时行为与从前完全一样;存储格式不变,老配置照常使用。 + +### 变更 + +- 配置页与大古截图的配置面板是同一套卡片样式,底部有「保存设置」:所有改动要点它才生效,有未保存的改动时标题栏提示,不保存就关闭则丢弃。 +- SSH 表单字段顺序调整为连接必需信息在上(主机、端口、远端目录),可选凭证在下(用户名、密码);编辑已有目标时表单在该行正下方展开,改哪条看哪条,行的移动与删除会带着表单一起走。 diff --git a/plugins/dagu-transfer/LICENSE b/plugins/dagu-transfer/LICENSE new file mode 100644 index 000000000..da6b3be55 --- /dev/null +++ b/plugins/dagu-transfer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 beierweiwei + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/dagu-transfer/README.md b/plugins/dagu-transfer/README.md new file mode 100644 index 000000000..df30ec2ad --- /dev/null +++ b/plugins/dagu-transfer/README.md @@ -0,0 +1,100 @@ +# 大古快传 + +一个运行在 ZTools 里的文件快传插件:**选目标 → 回车 → 地址进剪贴板**。把图片或文件传到本地目录、SSH 服务器,或者从 SSH 服务器把文件取回本机。 + +常见用法举几个例子: + +- 截完图想直接放到服务器上 → 在大古截图的工具条点「分享」,列表里回车就上传,远端路径已经复制好。 +- 想把一张图存进固定文件夹 → 把图片粘贴到 ZTools,选「分享图片」,选本地目录目标。 +- 想把一个文件传到服务器 → 把文件粘贴到 ZTools,选「分享文件」;手头只有文件路径(比如从别处复制来的)→ 粘贴路径,选「分享本地文件」。 +- 想把服务器上的文件拿到本机 → 在 ZTools 里输入或粘贴远端路径,选「下载远端文件」,选服务器回车;或者输入「下载文件」,选服务器后粘贴路径。 +- **远程 vib coding,想让 AI agent 看你本地的图** → 本地图片直接塞给远程开发会话里的 agent 不方便,先「分享本地文件」传到你的 SSH 服务器,把复制到的目标路径发给 agent(例如 Claude Code),它就能从服务器上读到这张图;截图同理,在大古截图点「分享」后把路径贴给 agent 即可。 + +## 如何使用 + +| 指令 | 作用 | +|---|---| +| `分享图片` | 粘贴图片到 ZTools 后出现,上传这张图片 | +| `分享文件` | 粘贴文件到 ZTools 后出现,上传这个文件(一次一个) | +| `分享本地文件` | 在 ZTools 里输入或粘贴一个本地文件路径时出现,上传这个文件 | +| `下载远端文件` | 在 ZTools 里输入或粘贴一个以 `/` 开头的远端路径时出现,选服务器即可下载 | +| `下载文件` | 先选服务器,再输入远端路径 | +| `快传配置` | 管理上传目标与下载目录 | + +输入或粘贴路径时,两条路径指令出现在 ZTools「最佳匹配」那一排:上传是向上箭头的图标,下载是向下箭头的图标。ZTools 内置的「前往文件夹」也会同时出现,而默认选中的是使用次数多的那个——直接回车打开的可能是文件夹,按 `→` 或点一下图标选中快传的指令再回车。 + +上传时是一个下拉列表:上面是 ZTools 的搜索框,可以输入名称过滤;下面是各个目标,**上次使用的排在第一位并默认选中**。 + +- 回车或点击:上传到该目标。成功后弹出通知,目标路径已复制到剪贴板,窗口自动收起。 +- 上传失败:窗口保留并显示原因,回车重试,或者回车前先选「打开配置」。 + +下载有两种走法: + +- 手头有远端路径:直接在 ZTools 的搜索框里输入或粘贴它,选「下载远端文件」。列表上方显示要下载的路径,选服务器回车就开始。 +- 从「下载文件」进:先在列表里选服务器(回车),然后在顶部搜索框里粘贴或输入远端文件的绝对路径,回车下载。输入过程中下面一行会显示将保存到本机哪里。 + +在搜索框里粘贴后,ZTools 会把粘贴的内容显示成输入框旁边的一个标签而不是填进输入框,这是 ZTools 的行为;直接按回车即可,快传会取剪贴板里的路径。 + +下载到本机的下载目录,成功后本机路径已复制,列表里回车可以打开所在文件夹。 + +## 界面 + +分享列表:上次使用的目标排在第一行并默认选中,回车即上传。 + +![分享列表:选目标回车上传](./docs/screenshots/share-list.png) + +配置页:管理本地目录与 SSH 服务器目标(主机、端口、远端目录、可选的用户名与登录密码)和下载目录。 + +![快传配置页](./docs/screenshots/setup.png) + +界面与大古截图是同一套卡片样式,并且和它一样跟随 ZTools 的深浅色与主题色。 + +## 配置 + +在「快传配置」里管理两类上传目标: + +- **本地目录**:上传就是复制到这个目录。 +- **SSH 服务器**:填 `user@host` 或 `~/.ssh/config` 里的别名、远端目录(绝对路径),端口可留空;需要密码登录的服务器再填「登录密码」,留空就是免密登录。 + +配置页上的改动(增删改目标、改下载目录、改密码、开关同步)都要点底部的**「保存设置」**才生效;有未保存的改动时标题栏会提示,不保存就关闭的话改动会丢弃。目标的名字不能重复;列表的顺序就是配置里的顺序,可以用上下箭头调整。下载目录留空时使用系统默认的下载目录。 + +上传和下载都会自动生成不重复的文件名(`原名-日期-时间-随机后缀`),不会覆盖已有文件。远端目录需要事先存在,插件不会去创建。 + +界面与大古截图是同一套卡片样式,并且和它一样跟随 ZTools 的深浅色与主题色。 + +## 配合「大古截图」使用 + +大古快传与截图插件**大古截图**是天然搭档:在大古截图的标注工具条上点「分享」,当前截图直接进入本插件的上传列表,回车选目标就传完,目标路径自动复制到剪贴板——不用先存文件、再找到文件去传。 + +![大古截图的工具条:右端有「分享」按钮](./docs/screenshots/overlay-toolbar.png) + +大古截图把截图、标注、OCR 文字识别与翻译做成一条路:按下「截图」,全屏冻结直接框选,画形状、打马赛克、加文字,然后复制、固定到屏幕,或交给 OCR / 翻译。还没有安装?在 ZTools 插件中心搜索「大古截图」即可。没装大古快传也不影响截图:点「分享」会留在截图界面并提示,截图不会丢。 + +## 关于 SSH 认证 + +传输使用系统自带的 OpenSSH `scp`,需要 9.0 及以上版本的 OpenSSH(Windows 11 自带,Windows 10 需要手动升级)。 + +- **没填密码**:免密登录,走 `~/.ssh/config`、SSH Agent 或已加载到 Agent 的私钥。 +- **填了密码**:上传和下载都按密码登录(目前只支持 Windows)。密码交给系统自带的 scp 去用,不写进命令行,也不落盘;密码错误只尝试一次,免得被服务器封禁。 + +登录密码的保存方式与大古截图的密钥一致:默认**只保存在本机**;打开配置页里的「同步密钥」后,才会额外写一份随 ZTools 备份同步的副本(该存储未声明端到端加密,请只在你信任的同步环境里开启);关闭开关会删除这份副本,本机密码保留。插件不管理 SSH 私钥文件。 + +## 为开发者准备的信息 + +```bash +npm install +npm run dev:transfer # 开发服务器,ZTools 开发者工具里添加本目录的 plugin.json +npm run build:transfer # 构建到 dist/ +``` + +preload 文件是 `preload.cjs`,不要改成 `preload.js`:项目根目录的 `package.json` 是 ES 模块类型,`.js` 会被 Electron 当成 ES 模块,开发模式下页面就拿不到 Node 侧能力。 + +开发模式下,页面代码是实时加载的,但 ZTools 登记的指令清单(`plugin.json` 里的 `features`)是点「安装(开发模式)」那一刻的快照。改了清单,要在开发者工具里先点「卸载(开发模式)」、再点「安装(开发模式)」:那里没有重载按钮,重启 ZTools 也不会更新清单。 + +图标 `icon.png`(上传)和 `download.png`(下载)由 `npm --prefix transfer run logo` 生成,用系统已安装的 Chrome 栅格化。 + +更完整的需求与测试说明见仓库根目录的 `docs/requirements-transfer.md`。 + +## 许可 + +MIT diff --git a/plugins/dagu-transfer/dagu-transfer-shared.cjs b/plugins/dagu-transfer/dagu-transfer-shared.cjs new file mode 100644 index 000000000..32f192fe8 --- /dev/null +++ b/plugins/dagu-transfer/dagu-transfer-shared.cjs @@ -0,0 +1,223 @@ +'use strict'; + +// 大古截图与大古快传共用的约定:唯一文件名的格式、交接文件的存放位置、跳转用的 token 与标签。 +// 两个插件的 preload 各自加载本插件目录内的同步副本(由 scripts/sync-shared.mjs 从 shared/ 复制)。 + +const path = require('node:path'); + +const SHARE_DIR_NAME = 'dagu-transfer'; +// 不含斜杠,写进大古快传的正则指令时无需转义。 +const TOKEN_PREFIX = 'dagu-transfer-share:'; +// 大古截图跳转时按「插件标题 + 指令名」定位大古快传,改任一侧都要同步另一侧的 plugin.json。 +const TRANSFER_TITLE = '大古快传'; +const TRANSFER_SHARE_CMD = '接收分享'; +// 已是唯一命名的文件:<名称>-YYYYMMDD-HHmmss-<6 位小写字母数字><.扩展名> +const UNIQUE_NAME_PATTERN = /^(.+)-\d{8}-\d{6}-[a-z0-9]{6}(\.[a-z0-9]{1,5})$/; +// 交接文件只接受这一种形态,token 因此无法把读取范围扩大到约定目录之外。 +const SHARE_FILE_PATTERN = /^(?:截图|图片)-\d{8}-\d{6}-[a-z0-9]{6}\.png$/; +// 目录分隔符、Windows 文件名非法字符与控制字符统一替换掉。 +const UNSAFE_CHARS = /[<>:"/\\|?*\u0000-\u001f\u007f]/g; +const STALE_MS = 24 * 60 * 60 * 1000; +// 确认文件:交接文件名后加 .ack。 +const ACK_SUFFIX = '.ack'; +const ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789'; + +const pad = (value) => String(value).padStart(2, '0'); + +function timestamp(now = new Date()) { + const date = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`; + return `${date}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`; +} + +// 36^6 ≈ 21.7 亿种组合,把 [0, 1) 的随机数均匀映射成 6 位小写字母数字。 +function randomSuffix(random = Math.random) { + let value = Math.floor(random() * 2176782336); + let text = ''; + for (let index = 0; index < 6; index += 1) { + text = ALPHABET[value % 36] + text; + value = Math.floor(value / 36); + } + return text; +} + +function isUniqueFileName(fileName) { + return UNIQUE_NAME_PATTERN.test(String(fileName || '')); +} + +// 只保留文件名部分(丢弃目录),并替换各平台都不允许的字符。 +function baseFileName(fileName) { + const normalized = String(fileName || '').replace(/\\/g, '/'); + return normalized.slice(normalized.lastIndexOf('/') + 1).replace(UNSAFE_CHARS, '_').trim(); +} + +function splitFileName(fileName) { + const base = baseFileName(fileName); + const dot = base.lastIndexOf('.'); + const hasExtension = dot > 0 && base.length - dot <= 6; + return { + base: hasExtension ? base.slice(0, dot) : base, + ext: hasExtension ? base.slice(dot).toLowerCase() : '' + }; +} + +// 已经符合唯一命名的文件名原样保留;force 为 true 时换一个新的时间与随机后缀。 +function uniqueFileName(fileName, { now = new Date(), random = Math.random, force = false } = {}) { + const source = baseFileName(fileName); + const match = UNIQUE_NAME_PATTERN.exec(source); + if (match && !force) return source; + const { base, ext } = match ? { base: match[1], ext: match[2] } : splitFileName(source); + return `${base || '文件'}-${timestamp(now)}-${randomSuffix(random)}${ext}`; +} + +function buildShareFileName(prefix = '截图', { now = new Date(), random = Math.random, ext = 'png' } = {}) { + return `${prefix}-${timestamp(now)}-${randomSuffix(random)}.${ext}`; +} + +function encodeShareToken(fileName) { + return TOKEN_PREFIX + encodeURIComponent(fileName); +} + +// 解析跳转 token;不是合法的交接文件名时返回空字符串。 +function decodeShareToken(token) { + if (typeof token !== 'string' || !token.startsWith(TOKEN_PREFIX)) return ''; + try { + const fileName = decodeURIComponent(token.slice(TOKEN_PREFIX.length)); + return SHARE_FILE_PATTERN.test(fileName) ? fileName : ''; + } catch { + return ''; + } +} + +function isShareFileName(fileName) { + return SHARE_FILE_PATTERN.test(String(fileName || '')); +} + +function redirectLabel() { + return [TRANSFER_TITLE, TRANSFER_SHARE_CMD]; +} + +// 「复制为路径」得到的路径文本带着成对的双引号或单引号,这里去掉首尾空白与成对引号。 +function unquotePath(text) { + const value = String(text ?? '').trim(); + const first = value[0]; + if ((first === '"' || first === "'") && value.length > 1 && value.endsWith(first)) { + return value.slice(1, -1).trim(); + } + return value; +} + +function shareDir(tmpdir) { + return path.join(tmpdir, SHARE_DIR_NAME); +} + +// 只为合法的交接文件名拼路径,其它输入一律返回空字符串。 +function shareFilePath(tmpdir, fileName) { + return isShareFileName(fileName) ? path.join(shareDir(tmpdir), fileName) : ''; +} + +// 截图侧使用:把图片写进交接目录,并在每次写入后清理过期的交接文件。 +// 宿主的 redirect 找不到目标插件时照样返回成功,所以「对方是否接手」要靠确认文件来判断: +// 快传读到交接文件后调用 ack 留下 <文件名>.ack,截图侧用 isAcked 轮询。 +function createShareWriter({ fs, tmpdir, now = () => new Date(), random = Math.random, staleMs = STALE_MS } = {}) { + const dir = shareDir(tmpdir); + + const filePathOf = (fileName) => (isShareFileName(fileName) ? path.join(dir, fileName) : ''); + const ackPathOf = (fileName) => { + const filePath = filePathOf(fileName); + return filePath ? `${filePath}${ACK_SUFFIX}` : ''; + }; + + const remove = (target) => { + if (!target) return false; + try { + fs.rmSync(target, { force: true }); + return true; + } catch { + return false; + } + }; + + const pruneStale = () => { + let entries = []; + try { + entries = fs.readdirSync(dir); + } catch { + return; + } + const cutoff = now().getTime() - staleMs; + for (const entry of entries) { + if (!isShareFileName(entry.replace(/\.ack$/, ''))) continue; + const target = path.join(dir, entry); + try { + if (fs.statSync(target).mtimeMs < cutoff) fs.rmSync(target, { force: true }); + } catch { + // 清理失败不影响分享主流程。 + } + } + }; + + const write = (base64, { prefix = '截图', ext = 'png' } = {}) => { + const fileName = buildShareFileName(prefix, { now: now(), random, ext }); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, fileName), Buffer.from(String(base64 || ''), 'base64')); + pruneStale(); + return { fileName, token: encodeShareToken(fileName), label: redirectLabel() }; + }; + + return Object.freeze({ + dir, + write, + pruneStale, + // 快传侧调用:确认已经拿到这个交接文件。 + ack: (fileName) => { + const ackPath = ackPathOf(fileName); + if (!ackPath) return false; + try { + fs.writeFileSync(ackPath, ''); + return true; + } catch { + return false; + } + }, + // 截图侧调用:对方是否已经确认接手。 + isAcked: (fileName) => { + const ackPath = ackPathOf(fileName); + if (!ackPath) return false; + try { + return fs.existsSync(ackPath); + } catch { + return false; + } + }, + // 连同确认文件一起删除。 + discard: (fileName) => { + const removed = remove(filePathOf(fileName)); + remove(ackPathOf(fileName)); + return removed; + }, + // 跳转前清掉上一次可能残留的确认文件,避免把旧确认当成本次的结果。 + clearAck: (fileName) => remove(ackPathOf(fileName)) + }); +} + +module.exports = { + SHARE_DIR_NAME, + TOKEN_PREFIX, + TRANSFER_TITLE, + TRANSFER_SHARE_CMD, + timestamp, + randomSuffix, + baseFileName, + splitFileName, + isUniqueFileName, + uniqueFileName, + buildShareFileName, + encodeShareToken, + decodeShareToken, + isShareFileName, + redirectLabel, + unquotePath, + shareDir, + shareFilePath, + createShareWriter +}; diff --git a/plugins/dagu-transfer/docs/screenshots/overlay-toolbar.png b/plugins/dagu-transfer/docs/screenshots/overlay-toolbar.png new file mode 100644 index 000000000..c9b2d9b2d Binary files /dev/null and b/plugins/dagu-transfer/docs/screenshots/overlay-toolbar.png differ diff --git a/plugins/dagu-transfer/docs/screenshots/setup.png b/plugins/dagu-transfer/docs/screenshots/setup.png new file mode 100644 index 000000000..b754cb43e Binary files /dev/null and b/plugins/dagu-transfer/docs/screenshots/setup.png differ diff --git a/plugins/dagu-transfer/docs/screenshots/share-list.png b/plugins/dagu-transfer/docs/screenshots/share-list.png new file mode 100644 index 000000000..767fc03bf Binary files /dev/null and b/plugins/dagu-transfer/docs/screenshots/share-list.png differ diff --git a/plugins/dagu-transfer/download.png b/plugins/dagu-transfer/download.png new file mode 100644 index 000000000..516e54fcf Binary files /dev/null and b/plugins/dagu-transfer/download.png differ diff --git a/plugins/dagu-transfer/icon.png b/plugins/dagu-transfer/icon.png new file mode 100644 index 000000000..fc8dceb04 Binary files /dev/null and b/plugins/dagu-transfer/icon.png differ diff --git a/plugins/dagu-transfer/index.html b/plugins/dagu-transfer/index.html new file mode 100644 index 000000000..3e06d555b --- /dev/null +++ b/plugins/dagu-transfer/index.html @@ -0,0 +1,23 @@ + + + + + + 大古快传 + + +
+ + + + diff --git a/plugins/dagu-transfer/node/transfer-services.cjs b/plugins/dagu-transfer/node/transfer-services.cjs new file mode 100644 index 000000000..cca85c553 --- /dev/null +++ b/plugins/dagu-transfer/node/transfer-services.cjs @@ -0,0 +1,305 @@ +'use strict'; + +// 大古快传的 Node 侧能力。页面不能直接使用 Node,只能调用 createTransferServices() 暴露的几个窄接口。 +// 这里不提供任意命令执行:scp 的参数、文件的最终名字都由页面侧的纯函数决定,这里只负责执行。 + +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawn } = require('node:child_process'); +const shared = require('../dagu-transfer-shared.cjs'); + +const SCP_TIMEOUT_MS = 120 * 1000; +// 粘贴进来的图片只接受这些格式,扩展名据此决定。 +const DATA_URL = /^data:image\/(png|jpe?g|webp|gif|bmp);base64,([A-Za-z0-9+/=\s]+)$/; + +function isFile(fsImpl, filePath) { + if (typeof filePath !== 'string' || !filePath) return false; + try { + return fsImpl.statSync(filePath).isFile(); + } catch { + return false; + } +} + +// Windows 自带的 OpenSSH 客户端不一定在 PATH 里:先按常见安装位置定位,最后才退回 PATH 中的 scp。 +function scpCandidates({ platform, env }) { + if (platform !== 'win32') return ['scp']; + const roots = []; + if (env.WINDIR) roots.push(path.join(env.WINDIR, 'System32', 'OpenSSH')); + if (env.ProgramFiles) roots.push(path.join(env.ProgramFiles, 'OpenSSH')); + if (env['ProgramFiles(x86)']) roots.push(path.join(env['ProgramFiles(x86)'], 'OpenSSH')); + return [...roots.map((root) => path.join(root, 'scp.exe')), 'scp']; +} + +function resolveScpBinary({ platform = process.platform, env = process.env, exists = (candidate) => fs.existsSync(candidate) } = {}) { + // 不带目录的候选交给 PATH 解析,启动失败时再如实报错。 + return scpCandidates({ platform, env }).find((candidate) => !path.isAbsolute(candidate) || exists(candidate)) || ''; +} + +// Windows 的 OpenSSH 客户端没有「命令行传密码」的参数,要用它内置的 askpass 机制: +// ssh 需要密码时不去读键盘,而是启动 SSH_ASKPASS 指定的程序,把它打印的第一行当作密码。 +// 这里生成一个很小的辅助脚本,只负责把环境变量 DAGU_SSH_ASKPASS 的内容原样打印出来;脚本本身不含密码, +// 密码只出现在这次 scp 子进程的环境变量里,不落盘、不进命令行。 +// - 用 PowerShell 打印而不是 echo:密码里的 & | % ! ^ " 等字符不会被改写; +// - 按 UTF-8 输出:含中文的密码也能原样送达; +// - SSH_ASKPASS_REQUIRE=force 必须带:不带的话 Windows 11 上的 ssh 会一直等一个不会出现的输入; +// - 同时必须去掉 BatchMode=yes,带着它 ssh 根本不询问密码。 +// 以上都是对 OpenSSH_for_Windows_9.5p1 实测得到的。 +const ASKPASS_ENV = 'DAGU_SSH_ASKPASS'; +const ASKPASS_DIR = 'dagu-transfer-askpass'; +const ASKPASS_NAME = /^askpass-\d+-[a-z0-9]+\.cmd$/; +const ASKPASS_MAX_AGE_MS = 60 * 60 * 1000; +const ASKPASS_SCRIPT = [ + '@echo off', + 'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "[Console]::OutputEncoding=[Text.Encoding]::UTF8; [Console]::Out.Write($env:DAGU_SSH_ASKPASS)"', + '' +].join('\r\n'); + +// 写出一个 askpass 辅助脚本并返回路径。上次异常退出留下的脚本顺手清掉(里面没有密码)。 +function createAskpassHelper({ fsImpl = fs, tmpdir = os.tmpdir(), now = Date.now, random = Math.random } = {}) { + const dir = path.join(tmpdir, ASKPASS_DIR); + fsImpl.mkdirSync(dir, { recursive: true }); + const cutoff = now() - ASKPASS_MAX_AGE_MS; + for (const entry of fsImpl.readdirSync(dir)) { + if (!ASKPASS_NAME.test(entry)) continue; + const stale = path.join(dir, entry); + try { + if (fsImpl.statSync(stale).mtimeMs < cutoff) fsImpl.rmSync(stale, { force: true }); + } catch { + // 清不掉旧脚本不影响这次登录。 + } + } + const helper = path.join(dir, `askpass-${now()}-${Math.floor(random() * 36 ** 6).toString(36).padStart(6, '0')}.cmd`); + fsImpl.writeFileSync(helper, ASKPASS_SCRIPT, 'utf8'); + return helper; +} + +function removeAskpassHelper(helper, fsImpl) { + try { + fsImpl.rmSync(helper, { force: true }); + } catch { + // 脚本里没有密码,删不掉也不泄密。 + } +} + +// 超时后要结束整棵进程树:scp 会再启动 ssh(密码登录时还有 askpass),只结束 scp 的话, +// ssh 会残留下来并占着管道,close 事件迟迟不来。 +function killProcessTree(child, platform = process.platform) { + if (platform !== 'win32') { + child.kill(); + return; + } + const killer = spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }); + killer.on('error', () => child.kill()); +} + +function hasPassword(password) { + return typeof password === 'string' && password.length > 0; +} + +// 以参数数组启动 scp,不经过任何 shell。cwd 不存在时先创建(下载目录属于这种情况)。 +// 带 password 时按密码登录(目前只支持 Windows),否则免密登录,子进程直接继承本进程的环境。 +function runScp( + { args, cwd, password }, + { + binary, + spawnImpl = spawn, + timeoutMs = SCP_TIMEOUT_MS, + platform = process.platform, + env = process.env, + fsImpl = fs, + tmpdir = os.tmpdir(), + now = Date.now, + random = Math.random, + killTree = killProcessTree + } = {} +) { + return new Promise((resolve) => { + const usePassword = hasPassword(password); + if (!binary) { + resolve({ ok: false, reason: 'scp-not-found', code: null, stderr: '' }); + return; + } + if (usePassword && platform !== 'win32') { + resolve({ ok: false, reason: 'password-unsupported', code: null, stderr: '' }); + return; + } + + let helper = ''; + let spawnOptions = { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }; + if (usePassword) { + try { + helper = createAskpassHelper({ fsImpl, tmpdir, now, random }); + } catch (error) { + resolve({ ok: false, reason: 'askpass-failed', code: null, stderr: '', error }); + return; + } + spawnOptions = { + ...spawnOptions, + env: { ...env, SSH_ASKPASS: helper, SSH_ASKPASS_REQUIRE: 'force', [ASKPASS_ENV]: password } + }; + } + + let child; + try { + fsImpl.mkdirSync(cwd, { recursive: true }); + child = spawnImpl(binary, args, spawnOptions); + } catch (error) { + if (helper) removeAskpassHelper(helper, fsImpl); + resolve({ ok: false, reason: 'spawn-failed', code: null, stderr: '', error }); + return; + } + let stderr = ''; + let timedOut = false; + let settled = false; + let timer; + let fallback; + const finish = (result) => { + if (settled) return; + settled = true; + clearTimeout(timer); + clearTimeout(fallback); + if (helper) removeAskpassHelper(helper, fsImpl); + resolve(result); + }; + const outcome = (code) => ({ + ok: !timedOut && code === 0, + reason: timedOut ? 'timeout' : code === 0 ? '' : 'exit', + code, + stderr: stderr.trim().slice(-2000) + }); + timer = setTimeout(() => { + timedOut = true; + killTree(child, platform); + }, timeoutMs); + child.stderr?.setEncoding('utf8'); + child.stderr?.on('data', (chunk) => { + stderr += chunk; + }); + child.stdout?.resume(); + child.on('error', (error) => { + finish({ ok: false, reason: error?.code === 'ENOENT' ? 'scp-not-found' : 'spawn-failed', code: null, stderr }); + }); + child.on('close', (code) => finish(outcome(code))); + // 进程已经退出却还有别的进程握着管道时,close 会迟到;退出一小段时间后按已有结果收尾。 + child.on('exit', () => { + fallback = setTimeout(() => finish(outcome(child.exitCode)), 1000); + }); + }); +} + +// 把文件复制到目标目录。绝不覆盖已有文件:撞名时换一个后缀重试一次。 +function copyFile({ sourcePath, targetDir, fileName }, { fsImpl = fs } = {}) { + try { + if (!isFile(fsImpl, sourcePath)) return { ok: false, reason: 'source-missing', path: '' }; + const safeName = shared.baseFileName(fileName); + if (!safeName) return { ok: false, reason: 'copy-failed', path: '' }; + fsImpl.mkdirSync(targetDir, { recursive: true }); + let finalName = safeName; + if (fsImpl.existsSync(path.join(targetDir, finalName))) { + finalName = shared.uniqueFileName(safeName, { force: true }); + } + const target = path.join(targetDir, finalName); + if (fsImpl.existsSync(target)) return { ok: false, reason: 'exists', path: target }; + fsImpl.copyFileSync(sourcePath, target); + return { ok: true, path: target, name: finalName }; + } catch (error) { + return { ok: false, reason: 'copy-failed', path: '', error }; + } +} + +// 把「进入插件时带的输入」变成一个待上传的本地文件。 +// - 大古截图跳转过来:token 指向交接目录里的文件 +// - 主搜索框里粘贴的本地文件路径文本(例如在资源管理器里「复制为路径」):文件存在就直接用 +// - ZTools 图片输入:dataURL 写成交接文件 +// - ZTools 文件输入:直接使用用户选的文件 +function prepareShareSource({ type, payload }, { fsImpl = fs, tmpdir = os.tmpdir() } = {}) { + if (typeof payload === 'string') { + const fileName = shared.decodeShareToken(payload); + if (fileName) { + const filePath = shared.shareFilePath(tmpdir, fileName); + if (!isFile(fsImpl, filePath)) return { ok: false, reason: 'source-missing' }; + // 留下确认文件:截图侧据此得知这边确实接手了。 + shared.createShareWriter({ fs: fsImpl, tmpdir }).ack(fileName); + return { ok: true, path: filePath, name: fileName, temporary: true }; + } + const localFile = shared.unquotePath(payload); + // 只认存在的普通文件:路径文本恰好是别的内容时不当成文件,交回各输入类型继续判断。 + if (path.isAbsolute(localFile) && isFile(fsImpl, localFile)) { + return { ok: true, path: localFile, name: path.basename(localFile), temporary: false }; + } + } + if (type === 'regex' || type === 'over') return { ok: false, reason: 'no-input' }; + if (type === 'img') { + const match = DATA_URL.exec(String(payload || '')); + if (!match) return { ok: false, reason: 'source-invalid' }; + const ext = match[1].toLowerCase().replace('jpeg', 'jpg'); + const writer = shared.createShareWriter({ fs: fsImpl, tmpdir }); + const fileName = writer.write(match[2], { prefix: '图片', ext }).fileName; + return { ok: true, path: shared.shareFilePath(tmpdir, fileName), name: fileName, temporary: true }; + } + if (type === 'files') { + const first = Array.isArray(payload) ? payload[0] : null; + const filePath = typeof first === 'string' ? first : first?.path; + if (typeof filePath !== 'string' || !filePath) return { ok: false, reason: 'no-input' }; + if (!isFile(fsImpl, filePath)) return { ok: false, reason: 'source-missing' }; + return { ok: true, path: filePath, name: path.basename(filePath), temporary: false }; + } + return { ok: false, reason: 'no-input' }; +} + +// 只删除交接目录里、名字符合约定的文件,不碰其它任何路径。 +function discardShareSource({ path: filePath }, { fsImpl = fs, tmpdir = os.tmpdir() } = {}) { + try { + if (typeof filePath !== 'string') return false; + if (path.dirname(filePath) !== shared.shareDir(tmpdir)) return false; + if (!shared.isShareFileName(path.basename(filePath))) return false; + fsImpl.rmSync(filePath, { force: true }); + return true; + } catch { + return false; + } +} + +function createTransferServices(options = {}) { + const platform = options.platform ?? process.platform; + const env = options.env ?? process.env; + const scope = { fsImpl: options.fs ?? fs, tmpdir: options.tmpdir ?? os.tmpdir() }; + const binary = () => options.scpBinary + ?? resolveScpBinary({ platform, env, ...(options.exists ? { exists: options.exists } : {}) }); + + return Object.freeze({ + // 已经符合唯一命名的文件名原样返回;force 为 true 时换一个新的后缀。 + uniqueName: (fileName, { force = false } = {}) => shared.uniqueFileName(fileName, { force }), + // 去掉路径文本首尾的空白与成对引号(「复制为路径」会带引号)。 + cleanPath: (text) => shared.unquotePath(text), + fileExists: (filePath) => isFile(scope.fsImpl, filePath), + defaultDownloadDir: () => path.join(os.homedir(), 'Downloads'), + scpBinary: () => binary(), + copyFile: (request) => copyFile(request, scope), + prepareShareSource: (action) => prepareShareSource(action, scope), + discardShareSource: (request) => discardShareSource(request, scope), + runScp: (request) => runScp(request, { + binary: binary(), + platform, + env, + fsImpl: scope.fsImpl, + tmpdir: scope.tmpdir, + ...(options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}), + ...(options.spawnImpl ? { spawnImpl: options.spawnImpl } : {}) + }) + }); +} + +module.exports = { + ASKPASS_SCRIPT, + createAskpassHelper, + createTransferServices, + copyFile, + discardShareSource, + prepareShareSource, + resolveScpBinary, + runScp, + scpCandidates +}; diff --git a/plugins/dagu-transfer/package.json b/plugins/dagu-transfer/package.json new file mode 100644 index 000000000..cd370a9a9 --- /dev/null +++ b/plugins/dagu-transfer/package.json @@ -0,0 +1,22 @@ +{ + "name": "dagu-transfer", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "大古快传:把图片或文件快速上传到本地目录、SSH 服务器,或从 SSH 服务器下载文件", + "scripts": { + "dev": "vite --port 5174 --strictPort", + "build": "vite build && node scripts/copy-plugin-files.mjs", + "icons": "node scripts/generate-icons.mjs", + "logo": "node scripts/generate-logo.mjs", + "preview": "vite preview" + }, + "dependencies": { + "vue": "^3.5.13" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^6.0.8", + "lucide-static": "^1.45.0", + "vite": "^8.0.10" + } +} diff --git a/plugins/dagu-transfer/plugin.json b/plugins/dagu-transfer/plugin.json new file mode 100644 index 000000000..54db85c5f --- /dev/null +++ b/plugins/dagu-transfer/plugin.json @@ -0,0 +1,70 @@ +{ + "name": "dagu-transfer", + "title": "大古快传", + "version": "1.0.0", + "description": "把图片或文件快速上传到本地目录、SSH 服务器,或从 SSH 服务器下载文件", + "author": "beierweiwei", + "logo": "icon.png", + "main": "index.html", + "preload": "preload.cjs", + "development": { + "main": "http://127.0.0.1:5174/index.html" + }, + "width": 800, + "height": 600, + "features": [ + { + "code": "share", + "explain": "上传到本地目录或 SSH 服务器", + "icon": "icon.png", + "cmds": [ + { + "type": "regex", + "label": "接收分享", + "match": "/^dagu-transfer-share:[A-Za-z0-9._~%+-]+$/", + "minLength": 24, + "maxLength": 512 + }, + { + "type": "regex", + "label": "分享本地文件", + "match": "/^(?:\"([A-Za-z]:[\\\\/][^\"]+)\"|'([A-Za-z]:[\\\\/][^']+)'|[A-Za-z]:[\\\\/][^\"']+)$/", + "minLength": 4, + "maxLength": 4096 + }, + { + "type": "img", + "label": "分享图片" + }, + { + "type": "files", + "label": "分享文件", + "fileType": "file", + "maxLength": 1 + } + ] + }, + { + "code": "download", + "explain": "从 SSH 服务器下载文件:输入远端路径直接下载,或先选服务器", + "icon": "download.png", + "cmds": [ + "下载文件", + "Download File", + { + "type": "regex", + "label": "下载远端文件", + "match": "/^\\/.+$/", + "minLength": 2, + "maxLength": 4096 + } + ] + }, + { + "code": "setup", + "explain": "管理上传目标与下载目录", + "icon": "icon.png", + "cmds": ["快传配置", "Transfer Settings"] + } + ] +} diff --git a/plugins/dagu-transfer/preload.cjs b/plugins/dagu-transfer/preload.cjs new file mode 100644 index 000000000..6f1980375 --- /dev/null +++ b/plugins/dagu-transfer/preload.cjs @@ -0,0 +1,9 @@ +// 大古快传 preload:向页面暴露受限的 Node 能力(拷贝文件、调用系统 scp、读写交接文件)。 +// 页面不能直接使用 Node;文件名与参数怎么定都由页面侧决定,这里只负责执行。 +try { + const services = require('./node/transfer-services.cjs'); + window.__daguTransfer = services.createTransferServices(); +} catch (error) { + // 普通浏览器开发环境没有 Node 能力:页面会提示需要在 ZTools 中运行。 + console.warn('[transfer] preload 初始化失败:', error); +} diff --git a/plugins/dagu-transfer/scripts/copy-plugin-files.mjs b/plugins/dagu-transfer/scripts/copy-plugin-files.mjs new file mode 100644 index 000000000..6cd3dab96 --- /dev/null +++ b/plugins/dagu-transfer/scripts/copy-plugin-files.mjs @@ -0,0 +1,20 @@ +import { copyFileSync, cpSync, mkdirSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +const pluginRoot = fileURLToPath(new URL('..', import.meta.url)) +const distDir = fileURLToPath(new URL('../dist/', import.meta.url)) + +mkdirSync(distDir, { recursive: true }) + +for (const file of ['plugin.json', 'preload.cjs', 'dagu-transfer-shared.cjs', 'icon.png', 'download.png', 'LICENSE', 'CHANGELOG.md', 'README.md']) { + copyFileSync(`${pluginRoot}${file}`, `${distDir}${file}`) +} + +// 随 README 一起发布的界面截图 +mkdirSync(`${distDir}docs/screenshots/`, { recursive: true }) +for (const file of ['share-list.png', 'setup.png']) { + copyFileSync(`${pluginRoot}docs/screenshots/${file}`, `${distDir}docs/screenshots/${file}`) +} + +// Node 侧能力不经过 Vite,原样复制。 +cpSync(`${pluginRoot}node/`, `${distDir}node/`, { recursive: true }) diff --git a/plugins/dagu-transfer/scripts/generate-icons.mjs b/plugins/dagu-transfer/scripts/generate-icons.mjs new file mode 100644 index 000000000..7baae0c83 --- /dev/null +++ b/plugins/dagu-transfer/scripts/generate-icons.mjs @@ -0,0 +1,61 @@ +// 从 lucide-static 生成 src/ui/icons.js,保证图标始终来自 Lucide 官方资源。 +// 用法:npm --prefix transfer run icons (图标目录不在常规位置时用 LUCIDE_ICONS_DIR 指定) +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const pluginRoot = fileURLToPath(new URL('..', import.meta.url)) +const targetFile = path.join(pluginRoot, 'src', 'ui', 'icons.js') + +const ICONS = { + settings: 'settings', + plus: 'plus', + edit: 'pencil', + folder: 'folder', + server: 'server', + up: 'chevron-up', + down: 'chevron-down', + trash: 'trash-2', + check: 'check', + close: 'x', + eye: 'eye', + eyeOff: 'eye-off' +} + +const lucideDir = [ + process.env.LUCIDE_ICONS_DIR, + path.join(pluginRoot, 'node_modules', 'lucide-static', 'icons'), + path.join(pluginRoot, '..', 'plugin', 'node_modules', 'lucide-static', 'icons'), + path.join(pluginRoot, '..', 'node_modules', 'lucide-static', 'icons') +].find((candidate) => candidate && existsSync(path.join(candidate, `${Object.values(ICONS)[0]}.svg`))) + +if (!lucideDir) { + console.error('未找到 lucide-static,请先安装依赖或用 LUCIDE_ICONS_DIR 指定图标目录') + process.exit(1) +} + +function readIconBody(name) { + const source = readFileSync(path.join(lucideDir, `${name}.svg`), 'utf8') + const body = source.replace(/^[\s\S]*?]*>/, '').replace(/<\/svg>\s*$/, '') + return body.replace(/\s*\n\s*/g, '').trim() +} + +const entries = Object.entries(ICONS) + .map(([key, name]) => ` ${key}: '${readIconBody(name)}'`) + .join(',\n') + +mkdirSync(path.dirname(targetFile), { recursive: true }) +writeFileSync(targetFile, `// 界面图标取自 Lucide (https://lucide.dev),ISC 许可证;由 scripts/generate-icons.mjs 生成,请勿手改。 +// 使用图标:${Object.values(ICONS).join(', ')} + +export const ICON_PATHS = { +${entries} +}; + +export function iconMarkup(name) { + const body = ICON_PATHS[name]; + if (!body) return ''; + return \`\`; +} +`, 'utf8') +console.log(`已生成 ${path.relative(pluginRoot, targetFile)}(${Object.keys(ICONS).length} 个图标)`) diff --git a/plugins/dagu-transfer/scripts/generate-logo.mjs b/plugins/dagu-transfer/scripts/generate-logo.mjs new file mode 100644 index 000000000..313cfc986 --- /dev/null +++ b/plugins/dagu-transfer/scripts/generate-logo.mjs @@ -0,0 +1,55 @@ +// 生成 transfer/ 下的图标:用系统已安装的 Chrome 把 SVG 栅格化,不下载任何浏览器。 +// icon.png 插件 logo,也是上传(分享)指令的图标 +// download.png 下载指令的图标 +// 用法:npm --prefix transfer run logo +import { chromium } from '@playwright/test' +import { existsSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +// 与「大古截图」同一套视觉:蓝色渐变圆角方块、白色图形、右上角一枚橙色圆点。 +// 背景必须是渐变:纯色图标会被 ZTools 在深色主题下整体反色。 +// 图形取自 Lucide 的 upload / download(24 网格,箭头在上、托盘在下)。 +const GLYPHS = { + 'icon.png': ` + + + `, + 'download.png': ` + + + ` +} + +const logoSvg = (glyph) => ` + + + + + + + + + + ${glyph} + +` + +const executablePath = [ + process.env.DAGU_OCR_PLAYWRIGHT_EXECUTABLE_PATH, + 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + '/usr/bin/google-chrome' +].find((candidate) => candidate && existsSync(candidate)) + +const browser = await chromium.launch(executablePath ? { executablePath } : { channel: 'chrome' }) +try { + const page = await browser.newPage({ viewport: { width: 512, height: 512 }, deviceScaleFactor: 1 }) + for (const [name, glyph] of Object.entries(GLYPHS)) { + await page.setContent(`${logoSvg(glyph)}`) + const target = fileURLToPath(new URL(`../${name}`, import.meta.url)) + await page.locator('svg').screenshot({ path: target, omitBackground: true }) + console.log(`已生成 ${target}`) + } +} finally { + await browser.close() +} diff --git a/plugins/dagu-transfer/src/App.vue b/plugins/dagu-transfer/src/App.vue new file mode 100644 index 000000000..bc3a7ec84 --- /dev/null +++ b/plugins/dagu-transfer/src/App.vue @@ -0,0 +1,17 @@ + + + diff --git a/plugins/dagu-transfer/src/core/config-store.js b/plugins/dagu-transfer/src/core/config-store.js new file mode 100644 index 000000000..2f261efc9 --- /dev/null +++ b/plugins/dagu-transfer/src/core/config-store.js @@ -0,0 +1,42 @@ +// 大古快传的配置存取,与大古截图的密钥同一套规则: +// - 偏好(目标、下载目录、上次使用的目标、是否同步密钥)存成一个文档,放进 ZTools 的 dbStorage,没有时退回本地存储; +// - 密码单独存:本机副本始终写入,打开「同步密钥」后另外写一份随 ZTools 备份同步的副本。 + +import { normalizeConfig, pickPasswords, withPasswords } from './targets.js'; +import { loadSecrets, saveSecrets } from '../shared/synced-secrets.js'; + +export const CONFIG_KEY = 'dagu-transfer/config'; +export const SECRET_KEYS = Object.freeze({ local: 'dagu-transfer.secrets', synced: 'dagu-transfer/secrets' }); + +export function createConfigStore({ kv, key = CONFIG_KEY, secretKeys = SECRET_KEYS } = {}) { + return { + // 读出偏好,并把密码并到各个 SSH 目标上。 + async load() { + const preferences = normalizeConfig(await kv.load(key)); + const secrets = await loadSecrets({ kv, keys: secretKeys, sync: preferences.syncSecrets, fallback: {} }); + return withPasswords(preferences, secrets.passwords); + }, + // 只写偏好。流程记住「上次使用的目标」时用它:传进来的对象里即使带着密码,也不会被写进去。 + save(config) { + return kv.save(key, normalizeConfig(config)); + }, + // 配置页「保存设置」:偏好和密码一起写入,密码按「同步密钥」开关决定要不要同步副本。 + async saveSettings(config) { + const preferences = normalizeConfig(config); + // 只保留合法目标的密码:填坏了的目标在归一化时已被丢弃,它的密码不该留下来。 + const entered = new Map( + (Array.isArray(config?.targets) ? config.targets : []) + .filter((target) => target && typeof target === 'object') + .map((target) => [target.id, target]) + ); + const secrets = { + passwords: pickPasswords({ + targets: preferences.targets.map((target) => ({ ...target, password: entered.get(target.id)?.password })) + }) + }; + const saved = await kv.save(key, preferences); + await saveSecrets({ kv, keys: secretKeys, secrets, sync: preferences.syncSecrets }); + return saved; + } + }; +} diff --git a/plugins/dagu-transfer/src/core/list-model.js b/plugins/dagu-transfer/src/core/list-model.js new file mode 100644 index 000000000..62e99ea35 --- /dev/null +++ b/plugins/dagu-transfer/src/core/list-model.js @@ -0,0 +1,23 @@ +// 列表的纯逻辑:排序、过滤、高亮移动。 + +import { targetDestination } from './targets.js'; + +// 列表默认高亮第一项,所以把上次使用的目标排在第一位,其余保持配置顺序。 +export function orderTargets(targets, lastUsedId) { + const last = targets.find((target) => target.id === lastUsedId); + if (!last) return [...targets]; + return [last, ...targets.filter((target) => target.id !== last.id)]; +} + +// 按名称或目标位置过滤,不区分大小写。 +export function filterTargets(targets, query) { + const needle = String(query ?? '').trim().toLowerCase(); + if (!needle) return [...targets]; + return targets.filter((target) => `${target.name}\n${targetDestination(target)}`.toLowerCase().includes(needle)); +} + +// 高亮在首尾之间移动,到头就停住。 +export function moveHighlight(index, delta, length) { + if (length <= 0) return 0; + return Math.min(Math.max(index + delta, 0), length - 1); +} diff --git a/plugins/dagu-transfer/src/core/paths.js b/plugins/dagu-transfer/src/core/paths.js new file mode 100644 index 000000000..ef78cd501 --- /dev/null +++ b/plugins/dagu-transfer/src/core/paths.js @@ -0,0 +1,20 @@ +// 路径的小工具:本地路径同时兼容 / 与 \ 两种分隔符。 + +// 拆出所在目录与文件名;没有目录时用当前目录。 +export function splitLocalPath(filePath) { + const value = String(filePath || ''); + const index = Math.max(value.lastIndexOf('/'), value.lastIndexOf('\\')); + return { dir: index > 0 ? value.slice(0, index) : '.', name: value.slice(index + 1) }; +} + +// 仅用于展示:沿用目录已有的分隔符风格。 +export function joinLocalPath(dir, name) { + const base = String(dir || ''); + const separator = /\\/.test(base) && !/\//.test(base) ? '\\' : '/'; + return base.replace(/[\\/]+$/, '') + (base ? separator : '') + name; +} + +export function remoteBaseName(remotePath) { + const value = String(remotePath || ''); + return value.slice(value.lastIndexOf('/') + 1); +} diff --git a/plugins/dagu-transfer/src/core/scp-args.js b/plugins/dagu-transfer/src/core/scp-args.js new file mode 100644 index 000000000..80c045bca --- /dev/null +++ b/plugins/dagu-transfer/src/core/scp-args.js @@ -0,0 +1,102 @@ +// 系统 scp 的参数拼装与错误翻译。scp 以参数数组启动,不经过本地 shell;-s 走 SFTP 协议, +// 远端路径原样传给服务端,同样不经过远端 shell,所以路径不做任何引号处理,只拒绝控制字符。 + +// 免密登录:不向用户询问任何东西,认证只走 ~/.ssh/config、SSH Agent 或已加载的私钥。 +const KEY_OPTIONS = ['-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=accept-new']; +// 密码登录:允许 ssh 询问密码(由 askpass 辅助程序回答,见 transfer/node/transfer-services.cjs)。 +// 只试密码、只试一次:错密码连试三次容易被服务器封禁;不去试公钥,免得把密码当成私钥口令送去。 +const PASSWORD_OPTIONS = [ + '-o', 'StrictHostKeyChecking=accept-new', + '-o', 'PubkeyAuthentication=no', + '-o', 'PreferredAuthentications=password,keyboard-interactive', + '-o', 'NumberOfPasswordPrompts=1' +]; +export const CONTROL_CHARS = /[\u0000-\u001f\u007f]/; + +// 有密码就按密码登录,否则照旧免密登录。 +export function authMode(password) { + return typeof password === 'string' && password.length > 0 ? 'password' : 'key'; +} + +function sshOptions(password) { + return authMode(password) === 'password' ? PASSWORD_OPTIONS : KEY_OPTIONS; +} + +// SFTP 协议不展开 ~,也不按登录目录补全相对路径,所以远端路径必须以 / 开头。 +export function remotePathProblem(remotePath) { + const value = String(remotePath ?? '').trim(); + if (!value) return '路径不能为空'; + if (CONTROL_CHARS.test(value)) return '路径不能包含换行或控制字符'; + if (!value.startsWith('/')) return '必须是绝对路径(以 / 开头)'; + return ''; +} + +// 端口留空时不传 -P,交给 ~/.ssh/config 或默认的 22 决定,避免覆盖别名里配置的端口。 +function portOptions(port) { + return port ? ['-P', String(port)] : []; +} + +export function joinRemotePath(dir, name) { + return `${String(dir).replace(/\/+$/, '')}/${name}`; +} + +// localName 只传文件名,调用方把工作目录设为它所在目录,避开 Windows 盘符里的冒号被当成主机名。 +export function buildUploadArgs({ target, port, localName, remoteDir, remoteName, password }) { + return ['-s', ...sshOptions(password), ...portOptions(port), localName, `${target}:${joinRemotePath(remoteDir, remoteName)}`]; +} + +export function buildDownloadArgs({ target, port, remotePath, localName, password }) { + return ['-s', ...sshOptions(password), ...portOptions(port), `${target}:${remotePath}`, localName]; +} + +// 交给 runScp 的请求:没有密码时不带 password 字段,免密登录的调用与以前完全一样。 +export function scpRequest({ args, cwd, password }) { + return authMode(password) === 'password' ? { args, cwd, password } : { args, cwd }; +} + +const lastLine = (stderr) => String(stderr || '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean).at(-1) || ''; + +// 「Permission denied (方法, 方法)」里列的是服务器允许的认证方法。 +function denialAllowsPassword(text) { + const methods = /Permission denied \(([^)]*)\)/i.exec(text)?.[1] ?? ''; + return /password|keyboard-interactive/i.test(methods); +} + +// 把 scp 的失败翻译成用户能看懂的原因。退出码 255 是连接或认证阶段失败,1 是传输阶段失败。 +// auth 是 'password'(按保存的密码登录)或 'key'(免密登录),决定认证失败时怎么提示。 +export function describeScpFailure({ reason = '', code = null, stderr = '', direction = 'upload', auth = 'key' }) { + const text = String(stderr || ''); + if (reason === 'scp-not-found') return '未找到系统自带的 OpenSSH scp,无法传输'; + if (reason === 'timeout') return '传输超时'; + if (reason === 'spawn-failed') return '无法启动 scp'; + if (reason === 'askpass-failed') return '无法准备密码登录,请改用密钥免密登录'; + if (reason === 'password-unsupported') return '密码登录目前只支持 Windows,请改用密钥免密登录'; + if (/unknown option|invalid option|usage: scp|illegal option/i.test(text)) { + return '系统自带的 OpenSSH 版本过旧,传输需要 9.0 及以上'; + } + if (code === 255) { + if (/Permission denied/i.test(text)) { + if (auth === 'password') { + return denialAllowsPassword(text) + ? '密码登录失败:请检查账号和密码' + : '服务器不允许密码登录(只接受密钥),请清空密码或改用密钥'; + } + return '认证失败:请确认 SSH 密钥或 ~/.ssh/config 可用,或在配置里填写登录密码'; + } + if (/Could not resolve hostname/i.test(text)) return '无法解析主机名'; + if (/Connection refused/i.test(text)) return '连接被拒绝,请检查地址和端口'; + if (/timed out/i.test(text)) return '连接超时'; + if (/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(text)) { + return '主机密钥校验失败,请先用 ssh 确认该主机'; + } + return lastLine(text) ? `连接失败:${lastLine(text)}` : '连接失败'; + } + if (/No such file or directory/i.test(text)) { + return direction === 'download' ? '远端文件不存在' : '远端目录不存在'; + } + if (/Permission denied/i.test(text)) { + return direction === 'download' ? '远端文件没有读取权限' : '远端目录没有写入权限'; + } + if (/disk quota|No space left/i.test(text)) return '远端空间不足'; + return lastLine(text) ? `传输失败:${lastLine(text)}` : '传输失败'; +} diff --git a/plugins/dagu-transfer/src/core/store.js b/plugins/dagu-transfer/src/core/store.js new file mode 100644 index 000000000..fa73e4971 --- /dev/null +++ b/plugins/dagu-transfer/src/core/store.js @@ -0,0 +1,17 @@ +// 极简的状态容器:保存当前状态,变化时通知订阅者。流程逻辑不依赖任何界面框架。 + +export function createStore(initial) { + let state = initial; + const listeners = new Set(); + return { + get: () => state, + set(patch) { + state = { ...state, ...(typeof patch === 'function' ? patch(state) : patch) }; + listeners.forEach((listener) => listener(state)); + }, + subscribe(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + } + }; +} diff --git a/plugins/dagu-transfer/src/core/targets.js b/plugins/dagu-transfer/src/core/targets.js new file mode 100644 index 000000000..07e464e18 --- /dev/null +++ b/plugins/dagu-transfer/src/core/targets.js @@ -0,0 +1,102 @@ +// 上传/下载目标(本地目录或 SSH 服务器)的归一化、校验与展示文案。 + +import { remotePathProblem } from './scp-args.js'; + +export const TARGET_TYPES = Object.freeze(['local', 'ssh']); + +// user@host,或 ~/.ssh/config 里的别名(不含 @)。 +const SSH_TARGET = /^[A-Za-z0-9][A-Za-z0-9._-]*(@[A-Za-z0-9][A-Za-z0-9._-]*)?$/; +const ABSOLUTE_LOCAL_PATH = /^([A-Za-z]:[\\/]|\\\\|\/(?!\/))/; +const ID_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789'; + +const text = (value) => String(value ?? '').trim(); + +export function createTargetId(random = Math.random) { + return `t-${Array.from({ length: 10 }, () => ID_ALPHABET[Math.floor(random() * 36)]).join('')}`; +} + +export function normalizeTarget(raw = {}) { + const type = TARGET_TYPES.includes(raw.type) ? raw.type : 'local'; + return { + id: text(raw.id) || createTargetId(), + name: text(raw.name), + type, + dir: type === 'local' ? text(raw.dir) : '', + target: type === 'ssh' ? text(raw.target) : '', + port: type === 'ssh' ? text(raw.port) : '', + remoteDir: type === 'ssh' ? text(raw.remoteDir) : '' + }; +} + +// 返回「字段名 → 错误文案」,为空对象表示合法。others 用来检查名称是否与其它目标重复。 +export function validateTarget(target, others = []) { + const errors = {}; + if (!target.name) { + errors.name = '请填写名称'; + } else if (others.some((other) => other.id !== target.id && other.name.toLowerCase() === target.name.toLowerCase())) { + errors.name = '名称已被其它目标使用'; + } + if (target.type === 'local') { + if (!target.dir) errors.dir = '请选择本地目录'; + else if (!ABSOLUTE_LOCAL_PATH.test(target.dir)) errors.dir = '必须是绝对路径'; + return errors; + } + if (!target.target) errors.target = '请填写 user@host 或 ~/.ssh/config 里的别名'; + else if (!SSH_TARGET.test(target.target)) errors.target = '只能填 user@host 或 ~/.ssh/config 中的别名'; + if (target.port && !(/^\d{1,5}$/.test(target.port) && Number(target.port) >= 1 && Number(target.port) <= 65535)) { + errors.port = '端口须是 1 到 65535 的整数'; + } + const problem = remotePathProblem(target.remoteDir); + if (problem) errors.remoteDir = problem; + return errors; +} + +// 读出来的配置只保留合法目标,避免一条坏数据让整个列表不可用。密码不在这里:它单独存放,见 pickPasswords。 +export function normalizeConfig(raw = {}) { + const targets = []; + for (const item of Array.isArray(raw?.targets) ? raw.targets : []) { + const target = normalizeTarget(item); + if (!Object.keys(validateTarget(target, targets)).length) targets.push(target); + } + const lastUsedId = text(raw?.lastUsedId); + return { + targets, + downloadDir: text(raw?.downloadDir), + lastUsedId: targets.some((target) => target.id === lastUsedId) ? lastUsedId : '', + syncSecrets: raw?.syncSecrets === true + }; +} + +// 把各个 SSH 目标上的密码拆成「目标 id → 密码」的表;密码不进偏好文档。 +export function pickPasswords(config) { + const passwords = {}; + for (const target of Array.isArray(config?.targets) ? config.targets : []) { + if (!target || target.type !== 'ssh') continue; + const password = text(target.password); + if (password) passwords[target.id] = password; + } + return passwords; +} + +// 把密码表并回各个 SSH 目标;表里没有的目标不带 password 字段。 +export function withPasswords(config, passwords = {}) { + return { + ...config, + targets: config.targets.map((target) => { + const password = target.type === 'ssh' ? text(passwords?.[target.id]) : ''; + return password ? { ...target, password } : target; + }) + }; +} + +// 列表里展示的目标位置;用密码登录的目标带一个标记,但不显示密码。 +export function targetDestination(target) { + if (target.type === 'local') return target.dir; + const port = target.port ? `(端口 ${target.port})` : ''; + return `${target.target}:${target.remoteDir}${port}`; +} + +export function targetAuthLabel(target) { + if (target.type !== 'ssh') return ''; + return target.password ? '密码登录' : '免密登录'; +} diff --git a/plugins/dagu-transfer/src/flows/download-flow.js b/plugins/dagu-transfer/src/flows/download-flow.js new file mode 100644 index 000000000..2b7d1f779 --- /dev/null +++ b/plugins/dagu-transfer/src/flows/download-flow.js @@ -0,0 +1,279 @@ +// 「下载」列表的流程,有两种进入方式: +// - 在 ZTools 主搜索框里输入或粘贴一个远端绝对路径,选「下载远端文件」:带着路径进来,直接选服务器。 +// - 输入「下载文件」:先选服务器,再在启动器的搜索框里粘贴或输入路径。 +// 路径始终在启动器的搜索框里输入,插件不在列表里另放输入框。为此要处理宿主搜索框的一个行为: +// 搜索框为空时粘贴文本,宿主不把文字放进输入框,而是在旁边显示成一个标签,也不通知插件。 +// 所以按回车时如果还没有路径,就取剪贴板里最近的一条文本当作路径。 +// 只依赖注入的 services(Node 侧能力)、host(ZTools 接口)与 configStore,不涉及界面。 + +import { authMode, buildDownloadArgs, describeScpFailure, remotePathProblem, scpRequest } from '../core/scp-args.js'; +import { joinLocalPath, remoteBaseName } from '../core/paths.js'; +import { filterTargets, moveHighlight, orderTargets } from '../core/list-model.js'; +import { createStore } from '../core/store.js'; +import { targetDestination } from '../core/targets.js'; +import { SELECTABLE_PHASES, collapse, errorText, setupRow, targetRow } from './list-rows.js'; + +// stepTick 每进入一个步骤加一,boxValue 是这一步开始时搜索框应有的内容;界面层据此设置搜索框并全选。 +const IDLE = Object.freeze({ + phase: 'idle', rows: [], highlight: 0, status: null, query: '', placeholder: '', stepTick: 0, boxValue: '' +}); +const PICK_PLACEHOLDER = '搜索服务器,回车继续'; +const PATH_PLACEHOLDER = '粘贴或输入远端文件的绝对路径,回车下载'; +const NO_PASTED_PATH = '没有读到粘贴的内容:请先复制远端路径,粘贴后回车,或直接输入'; + +export function createDownloadFlow({ services, host, configStore, openSetup = () => {} }) { + const store = createStore({ ...IDLE }); + let targets = []; + let config = { targets: [], downloadDir: '', lastUsedId: '' }; + let chosen = null; + let remotePath = ''; + let busy = false; + let stepTick = 0; + let boxValue = ''; + + // 进入一个步骤:记下这一步开始时搜索框应有的内容。只在这里计数,不能放在渲染函数里: + // 输入过程中每敲一个字都会重新渲染,那样每输入一个字符搜索框就被重设一次。 + const enterStep = (value) => { + stepTick += 1; + boxValue = value; + }; + const step = () => ({ stepTick, boxValue }); + + const show = (rows, phase, status = null, extra = {}) => store.set({ rows, phase, status, highlight: 0, ...step(), ...extra }); + const trimmedPath = () => remotePath.trim(); + const hasPath = () => !remotePathProblem(trimmedPath()); + const downloadDir = () => config.downloadDir || host?.getPath?.('downloads') || services?.defaultDownloadDir?.() || ''; + + // 选服务器。带着路径进来时这一步就直接可以下载,列表末尾留一个「更改远端路径」。 + const renderPick = () => { + const visible = filterTargets(orderTargets(targets, config.lastUsedId), store.get().query); + const withPath = hasPath(); + const tools = withPath ? [{ key: 'edit-path', kind: 'editPath', title: '更改远端路径', subtitle: '' }] : []; + const downloading = { title: `下载 ${trimmedPath()}` }; + const stepState = { ...step(), placeholder: PICK_PLACEHOLDER }; + if (!targets.length) { + show([setupRow('回车打开配置,添加 SSH 服务器')], 'no-targets', { title: '还没有可用的 SSH 服务器' }, stepState); + return; + } + if (!visible.length) { + show(tools, 'pick', withPath ? downloading : { title: '没有匹配的服务器' }, stepState); + return; + } + show([...visible.map(targetRow), ...tools], 'pick', withPath ? { ...downloading, subtitle: '选择服务器,回车开始' } : null, stepState); + }; + + const enterPick = () => { + // 搜索框在这一步用来过滤服务器,从空开始。 + enterStep(''); + renderPick(); + }; + + // 输入路径。可能还没选服务器(带着路径进来后点「更改远端路径」),这时回车是回到选服务器。 + const renderPath = () => { + const path = trimmedPath(); + const problem = remotePathProblem(path); + const saveTo = path && !problem ? `保存到 ${joinLocalPath(downloadDir(), services.uniqueName(remoteBaseName(path)))}` : ''; + const idleTitle = chosen ? '粘贴远端路径后回车下载' : '粘贴远端路径后回车继续'; + store.set({ + phase: 'path', + query: '', + highlight: 0, + placeholder: PATH_PLACEHOLDER, + ...step(), + status: chosen ? { title: `从「${chosen.name}」下载`, subtitle: targetDestination(chosen) } : null, + rows: [ + { key: 'download', kind: 'download', title: path ? `下载 ${path}` : idleTitle, subtitle: problem || saveTo }, + { key: 'back', kind: 'back', title: '返回选择服务器', subtitle: '' } + ] + }); + }; + + const enterPath = () => { + // 搜索框带着已经确定的路径,全选之后用户粘贴或输入的新路径会直接替换它。 + enterStep(remotePath); + renderPath(); + }; + + // 空搜索框里粘贴的内容只显示成启动器的一个标签,宿主不会把它交给插件; + // 标签显示的就是剪贴板里最近的一条内容,所以这里取最近的一条文本。 + async function readPastedPath() { + try { + const history = await host?.clipboard?.getHistory?.(1, 1); + const latest = history?.items?.[0]; + if (latest?.type !== 'text' || typeof latest.content !== 'string') return ''; + return services.cleanPath(latest.content); + } catch { + return ''; + } + } + + async function usePastedPath() { + if (busy) return; + busy = true; + const pasted = await readPastedPath(); + busy = false; + remotePath = pasted; + if (!pasted) { + store.set({ + rows: [ + { key: 'download', kind: 'download', title: '粘贴远端路径后回车下载', subtitle: NO_PASTED_PATH }, + { key: 'back', kind: 'back', title: '返回选择服务器', subtitle: '' } + ] + }); + return; + } + if (hasPath()) { + if (chosen) await runDownload(); + else enterPick(); + return; + } + renderPath(); + } + + async function enter(action = {}) { + store.set({ ...IDLE, phase: 'loading', placeholder: PICK_PLACEHOLDER, status: { title: '正在加载…' } }); + if (!services) { + show([], 'error', { title: '需要在 ZTools 中运行', tone: 'danger' }); + return; + } + try { + config = await configStore.load(); + } catch (error) { + show([], 'error', { title: '读取配置失败', subtitle: errorText(error), tone: 'danger' }); + return; + } + targets = config.targets.filter((target) => target.type === 'ssh'); + chosen = null; + // 在主搜索框里直接输入或粘贴路径进来的,路径已经确定。只看内容是不是合法路径,不看宿主给的类型标记: + // 输入触发的是正则指令,粘贴触发的是宿主对粘贴文本的匹配,两者的标记不一样。 + const typed = services.cleanPath(typeof action.payload === 'string' ? action.payload : ''); + remotePath = remotePathProblem(typed) ? '' : typed; + enterPick(); + } + + function search(text) { + const value = String(text ?? ''); + const { phase } = store.get(); + if (phase === 'pick') { + store.set({ query: value }); + renderPick(); + } else if (phase === 'path') { + remotePath = services.cleanPath(value); + renderPath(); + } + } + + function move(delta) { + const { phase, rows, highlight } = store.get(); + if (SELECTABLE_PHASES.has(phase) && rows.length) store.set({ highlight: moveHighlight(highlight, delta, rows.length) }); + } + + async function runDownload() { + if (busy) return; + const path = trimmedPath(); + const dir = downloadDir(); + if (!dir) { + show([setupRow('回车打开配置,先选择一个下载目录')], 'failed', { title: '下载失败', subtitle: '无法确定下载目录', tone: 'danger' }, { placeholder: PATH_PLACEHOLDER }); + return; + } + busy = true; + // 绝不覆盖已有文件:默认名字撞上已有文件时换一个后缀。 + let name = services.uniqueName(remoteBaseName(path)); + if (services.fileExists(joinLocalPath(dir, name))) name = services.uniqueName(name, { force: true }); + store.set({ + phase: 'downloading', + rows: [], + highlight: 0, + status: { title: `正在从「${chosen.name}」下载…`, subtitle: path, tone: 'busy' } + }); + // 这台服务器保存了密码就按密码登录,否则免密登录。 + const password = chosen.password; + const args = buildDownloadArgs({ target: chosen.target, port: chosen.port, remotePath: path, localName: name, password }); + let result; + try { + result = await services.runScp(scpRequest({ args, cwd: dir, password })); + } catch (error) { + result = { ok: false, reason: 'spawn-failed', code: null, stderr: '', error }; + } + busy = false; + const localPath = joinLocalPath(dir, name); + if (!result.ok) { + store.set({ + phase: 'failed', + highlight: 0, + status: { title: '下载失败', subtitle: describeScpFailure({ ...result, direction: 'download', auth: authMode(password) }), tone: 'danger' }, + rows: [ + { key: 'retry', kind: 'retry', title: `回车重试:下载 ${path}`, subtitle: targetDestination(chosen) }, + { key: 'edit-path', kind: 'editPath', title: '更改远端路径', subtitle: '' }, + setupRow() + ] + }); + return; + } + try { + await configStore.save({ ...config, lastUsedId: chosen.id }); + } catch { + // 记不住「上次使用」不影响本次下载结果。 + } + host?.copyText?.(localPath); + await host?.showNotification?.('已下载,本机路径已复制'); + show( + [{ key: 'reveal', kind: 'reveal', title: '已下载,回车打开所在文件夹', subtitle: localPath, path: localPath }], + 'done' + ); + } + + async function select(index) { + const row = store.get().rows[index]; + const { phase } = store.get(); + if (!row) return; + if (row.kind === 'setup') openSetup(); + else if (row.kind === 'target') { + chosen = row.target; + if (hasPath()) await runDownload(); + else enterPath(); + } else if (row.kind === 'editPath') { + enterPath(); + } else if (row.kind === 'back') { + enterPick(); + } else if (row.kind === 'download' && phase === 'path') { + if (hasPath()) { + if (chosen) await runDownload(); + else enterPick(); + } else if (!trimmedPath()) { + // 框里没有路径就按了回车:多半是粘贴变成了启动器里的标签,去剪贴板里取。 + // 输入了不合法的内容时只提示原因,不拿剪贴板内容覆盖它。 + await usePastedPath(); + } + } else if (row.kind === 'retry') { + await runDownload(); + } else if (row.kind === 'reveal') { + host?.shellShowItemInFolder?.(row.path); + store.set({ placeholder: '' }); + await collapse(host); + } + } + + function reset() { + targets = []; + chosen = null; + remotePath = ''; + stepTick = 0; + boxValue = ''; + busy = false; + store.set({ ...IDLE }); + } + + return Object.freeze({ + enter, + search, + move, + select, + activate: () => select(store.get().highlight), + reset, + subscribe: store.subscribe, + get state() { + return store.get(); + } + }); +} diff --git a/plugins/dagu-transfer/src/flows/list-rows.js b/plugins/dagu-transfer/src/flows/list-rows.js new file mode 100644 index 000000000..90651eb1e --- /dev/null +++ b/plugins/dagu-transfer/src/flows/list-rows.js @@ -0,0 +1,24 @@ +// 两个列表流程共用的行构造与收尾动作。 + +import { targetDestination } from '../core/targets.js'; + +// 这些阶段下,列表里的行可以用上下键选择、回车触发。 +export const SELECTABLE_PHASES = new Set(['targets', 'pick', 'path', 'failed', 'no-targets', 'no-input', 'done']); + +export function targetRow(target) { + return { key: `target:${target.id}`, kind: 'target', target, title: target.name, subtitle: targetDestination(target) }; +} + +export function setupRow(subtitle = '管理上传目标与下载目录') { + return { key: 'setup', kind: 'setup', title: '打开配置', subtitle }; +} + +export function errorText(error) { + return error instanceof Error ? error.message : String(error ?? '未知错误'); +} + +// 一次操作完成后的收起:隐藏启动器主窗口并退出插件视图。 +export async function collapse(host) { + await host?.hideMainWindow?.(); + await host?.outPlugin?.(false); +} diff --git a/plugins/dagu-transfer/src/flows/share-flow.js b/plugins/dagu-transfer/src/flows/share-flow.js new file mode 100644 index 000000000..e81d5cd1c --- /dev/null +++ b/plugins/dagu-transfer/src/flows/share-flow.js @@ -0,0 +1,187 @@ +// 「分享」列表的流程:解析待分享的文件 → 列出目标(上次使用的排第一)→ 回车或点击上传 → 成功后收起。 +// 只依赖注入的 services(Node 侧能力)、host(ZTools 接口)与 configStore,不涉及界面。 + +import { authMode, buildUploadArgs, describeScpFailure, joinRemotePath, scpRequest } from '../core/scp-args.js'; +import { splitLocalPath } from '../core/paths.js'; +import { filterTargets, moveHighlight, orderTargets } from '../core/list-model.js'; +import { createStore } from '../core/store.js'; +import { targetDestination } from '../core/targets.js'; +import { SELECTABLE_PHASES, collapse, errorText, setupRow, targetRow } from './list-rows.js'; + +const IDLE = Object.freeze({ phase: 'idle', rows: [], highlight: 0, status: null, query: '', placeholder: '' }); + +const LOCAL_PROBLEMS = { + 'source-missing': '待分享的文件已不可用,请重新分享', + exists: '目标目录里已有同名文件', + 'copy-failed': '写入本地目录失败,请检查目录是否可写' +}; + +export function createShareFlow({ services, host, configStore, openSetup = () => {} }) { + const store = createStore({ ...IDLE }); + let config = { targets: [], downloadDir: '', lastUsedId: '' }; + let source = null; + let busy = false; + + const show = (rows, phase, status = null) => store.set({ rows, phase, status, highlight: 0 }); + + const renderTargets = () => { + const visible = filterTargets(orderTargets(config.targets, config.lastUsedId), store.get().query); + if (!visible.length) { + show([], 'targets', { title: '没有匹配的上传目标' }); + return; + } + show(visible.map(targetRow), 'targets'); + }; + + // 交接文件只供一次上传使用:上传成功或放弃时删除,避免临时目录越积越多。 + const discardSource = () => { + if (source?.temporary) services?.discardShareSource?.({ path: source.path }); + source = null; + }; + + async function enter(action = {}) { + store.set({ ...IDLE, phase: 'loading', placeholder: '搜索上传目标', status: { title: '正在加载…' } }); + if (!services) { + show([], 'error', { title: '需要在 ZTools 中运行', tone: 'danger' }); + return; + } + discardSource(); + try { + config = await configStore.load(); + } catch (error) { + show([], 'error', { title: '读取配置失败', subtitle: errorText(error), tone: 'danger' }); + return; + } + let prepared; + try { + prepared = services.prepareShareSource(action); + } catch (error) { + prepared = { ok: false, reason: 'source-missing' }; + console.warn('[transfer] 解析待分享文件失败:', error); + } + if (!prepared.ok) { + if (prepared.reason === 'no-input') { + show([setupRow()], 'no-input', { + title: '没有可分享的文件', + subtitle: '把图片或文件粘贴到 ZTools,再选择「分享图片」或「分享文件」' + }); + } else { + show([setupRow()], 'error', { title: '待分享的文件已不可用', subtitle: '请重新分享一次', tone: 'danger' }); + } + return; + } + source = prepared; + if (!config.targets.length) { + show([setupRow('回车打开配置,添加本地目录或 SSH 服务器')], 'no-targets', { title: '还没有可用的上传目标' }); + return; + } + renderTargets(); + } + + function search(text) { + store.set({ query: text }); + if (store.get().phase === 'targets') renderTargets(); + } + + function move(delta) { + const { phase, rows, highlight } = store.get(); + if (SELECTABLE_PHASES.has(phase) && rows.length) store.set({ highlight: moveHighlight(highlight, delta, rows.length) }); + } + + function uploadLocal(target) { + const fileName = services.uniqueName(source.name); + const result = services.copyFile({ sourcePath: source.path, targetDir: target.dir, fileName }); + return { ok: result.ok, path: result.path || '', message: LOCAL_PROBLEMS[result.reason] || '' }; + } + + async function uploadSsh(target) { + const local = splitLocalPath(source.path); + const remoteName = services.uniqueName(source.name); + // 目标上保存了密码就按密码登录,否则免密登录。 + const password = target.password; + const args = buildUploadArgs({ + target: target.target, + port: target.port, + localName: local.name, + remoteDir: target.remoteDir, + remoteName, + password + }); + const result = await services.runScp(scpRequest({ args, cwd: local.dir, password })); + return { + ok: result.ok, + path: joinRemotePath(target.remoteDir, remoteName), + message: result.ok ? '' : describeScpFailure({ ...result, direction: 'upload', auth: authMode(password) }) + }; + } + + async function upload(target) { + if (busy) return; + busy = true; + store.set({ + phase: 'uploading', + rows: [], + highlight: 0, + status: { title: `正在上传到「${target.name}」…`, subtitle: targetDestination(target), tone: 'busy' } + }); + let result; + try { + result = target.type === 'local' ? uploadLocal(target) : await uploadSsh(target); + } catch (error) { + result = { ok: false, message: errorText(error) }; + } + busy = false; + if (result.ok) { + await finish(target, result.path); + return; + } + store.set({ + phase: 'failed', + highlight: 0, + status: { title: '上传失败', subtitle: result.message, tone: 'danger' }, + rows: [ + { key: 'retry', kind: 'retry', target, title: `回车重试:上传到「${target.name}」`, subtitle: targetDestination(target) }, + setupRow() + ] + }); + } + + async function finish(target, path) { + discardSource(); + try { + await configStore.save({ ...config, lastUsedId: target.id }); + } catch { + // 记不住「上次使用」不影响本次上传结果。 + } + host?.copyText?.(path); + await host?.showNotification?.(`已上传到「${target.name}」,路径已复制`); + store.set({ placeholder: '' }); + await collapse(host); + } + + async function select(index) { + const row = store.get().rows[index]; + if (!row) return; + if (row.kind === 'setup') openSetup(); + else if (row.kind === 'target' || row.kind === 'retry') await upload(row.target); + } + + function reset() { + discardSource(); + busy = false; + store.set({ ...IDLE }); + } + + return Object.freeze({ + enter, + search, + move, + select, + activate: () => select(store.get().highlight), + reset, + subscribe: store.subscribe, + get state() { + return store.get(); + } + }); +} diff --git a/plugins/dagu-transfer/src/list/TransferList.vue b/plugins/dagu-transfer/src/list/TransferList.vue new file mode 100644 index 000000000..8f33d6253 --- /dev/null +++ b/plugins/dagu-transfer/src/list/TransferList.vue @@ -0,0 +1,51 @@ + + + diff --git a/plugins/dagu-transfer/src/list/host-glue.js b/plugins/dagu-transfer/src/list/host-glue.js new file mode 100644 index 000000000..58cc1aba2 --- /dev/null +++ b/plugins/dagu-transfer/src/list/host-glue.js @@ -0,0 +1,61 @@ +// 把列表流程接到 ZTools 启动器:搜索框、上下键与回车、按内容高度调整插件视图高度。 +// 列表由插件自己画,筛选和输入内容都用宿主的搜索框(setSubInput),做法与生态里的「VSCode 最近项目」插件一致。 + +// 宿主把插件视图的高度上限设在 541px,超出后由列表自己滚动。 +const MAX_VIEW_HEIGHT = 541; + +// 文档写的是 (text),实际收到的是 { text },两种都兼容。 +const subInputText = (details) => (typeof details === 'string' ? details : details?.text ?? ''); + +export function attachListToHost(flow, host, element) { + // 初始值与流程的空闲状态一致:组件挂载时不应该触发任何宿主调用。 + let placeholder = ''; + let stepTick = 0; + + // 流程进入任何阶段后,上下键与回车都交给流程处理,包括搜索框被收起之后(下载中、失败、完成), + // 否则失败后无法回车重试。 + const active = () => flow.state.phase !== 'idle'; + + const fitHeight = () => { + if (!element || !active()) return; + const height = element.offsetHeight + 8; + if (height > 8) host?.setExpendHeight?.(Math.min(height, MAX_VIEW_HEIGHT)); + }; + // 等浏览器完成布局再量高度:连续两帧可避开「同一帧内测量早于样式生效」的竞争。 + const scheduleFit = () => requestAnimationFrame(() => requestAnimationFrame(fitHeight)); + + const apply = (state) => { + if (state.placeholder !== placeholder) { + placeholder = state.placeholder; + if (placeholder) host?.setSubInput?.((details) => flow.search(subInputText(details)), placeholder); + else host?.removeSubInput?.(); + } + // 每进入一个步骤,把搜索框设成这一步应有的内容并整段选中:上一步留下的文字被清掉或替换, + // 用户接着粘贴或输入时也会直接替换掉框里已有的内容。宿主设置搜索框后会把它回传给流程。 + if (state.stepTick !== stepTick) { + stepTick = state.stepTick; + host?.setSubInputValue?.(state.boxValue ?? ''); + host?.subInputSelect?.(); + } + scheduleFit(); + }; + + const onKeydown = (event) => { + // 输入法组字期间的回车是在选词,不是在确认。 + if (!active() || event.defaultPrevented || event.isComposing) return; + if (event.key === 'ArrowDown') flow.move(1); + else if (event.key === 'ArrowUp') flow.move(-1); + else if (event.key === 'Enter') flow.activate(); + else return; + event.preventDefault(); + }; + + const unsubscribe = flow.subscribe(apply); + document.addEventListener('keydown', onKeydown); + apply(flow.state); + + return () => { + unsubscribe(); + document.removeEventListener('keydown', onKeydown); + }; +} diff --git a/plugins/dagu-transfer/src/main.js b/plugins/dagu-transfer/src/main.js new file mode 100644 index 000000000..8cee9c2ef --- /dev/null +++ b/plugins/dagu-transfer/src/main.js @@ -0,0 +1,60 @@ +import { createApp, reactive } from 'vue'; +import App from './App.vue'; +import './styles.css'; +import { createZtoolsThemeSync } from './shared/theme.js'; +import { createKvStore } from './shared/kv.js'; +import { createConfigStore } from './core/config-store.js'; +import { createShareFlow } from './flows/share-flow.js'; +import { createDownloadFlow } from './flows/download-flow.js'; + +const win = globalThis.window; +const host = win.ztools || win.utools || null; +// Node 侧能力由 preload 注入;普通浏览器里没有,列表会提示需要在 ZTools 中运行。 +const services = win.__daguTransfer || null; + +const LIST_CODES = new Set(['share', 'download']); +const SETUP_HEIGHT = 600; + +const view = reactive({ route: '' }); +const configStore = createConfigStore({ kv: createKvStore({ win }) }); +const show = (route) => { + view.route = route; + // 配置页没有可筛选的列表,不能留着上一步的搜索框。 + if (!LIST_CODES.has(route)) host?.removeSubInput?.(); +}; +const flows = { + share: createShareFlow({ services, host, configStore, openSetup: () => show('setup') }), + download: createDownloadFlow({ services, host, configStore, openSetup: () => show('setup') }) +}; + +async function enter(param = {}) { + if (LIST_CODES.has(param.code)) { + show(param.code); + // 先清掉上一次留下的搜索框回调,流程进入时会重新设置。 + await host?.removeSubInput?.(); + await flows[param.code].enter(param); + return; + } + show('setup'); + host?.setExpendHeight?.(SETUP_HEIGHT); +} + +function leave() { + Object.values(flows).forEach((flow) => flow.reset()); + view.route = ''; +} + +// 主色与深浅色都跟随 ZTools(宿主设置默认跟随系统),与大古截图共用同一份实现。 +createZtoolsThemeSync({ win, doc: win.document }); + +createApp(App, { view, flows, host, configStore }).mount('#app'); + +host?.onPluginOut?.(leave); +host?.onPluginEnter?.((param) => enter(param)); + +// index.html 的内联脚本接住了页面脚本执行前到达的进入事件,这里补上。 +const earlyParam = win.__ztoolsEnterParam; +if (earlyParam) { + win.__ztoolsEnterParam = null; + void enter(earlyParam); +} diff --git a/plugins/dagu-transfer/src/setup/SetupView.vue b/plugins/dagu-transfer/src/setup/SetupView.vue new file mode 100644 index 000000000..f0181e23e --- /dev/null +++ b/plugins/dagu-transfer/src/setup/SetupView.vue @@ -0,0 +1,221 @@ + + + diff --git a/plugins/dagu-transfer/src/setup/TargetForm.vue b/plugins/dagu-transfer/src/setup/TargetForm.vue new file mode 100644 index 000000000..807abcde1 --- /dev/null +++ b/plugins/dagu-transfer/src/setup/TargetForm.vue @@ -0,0 +1,83 @@ + + + diff --git a/plugins/dagu-transfer/src/setup/settings-draft.js b/plugins/dagu-transfer/src/setup/settings-draft.js new file mode 100644 index 000000000..24ab8d6d8 --- /dev/null +++ b/plugins/dagu-transfer/src/setup/settings-draft.js @@ -0,0 +1,80 @@ +// 配置页的草稿:所有改动先留在草稿里,点「保存设置」才写入存储。这里都是纯函数,不碰存储和界面。 + +import { CONTROL_CHARS } from '../core/scp-args.js'; +import { normalizeTarget, validateTarget } from '../core/targets.js'; + +export function createDraft(config) { + return { + targets: (config?.targets || []).map((target) => ({ ...target })), + downloadDir: config?.downloadDir || '', + syncSecrets: config?.syncSecrets === true + }; +} + +// 新建目标的表单初值。username 是表单专用的输入位:存储里只存拼好的 user@host,见 composeTargetInput。 +export function newTargetForm(type) { + return { ...normalizeTarget({ type }), username: '', password: '' }; +} + +// 把存储里的 user@host 拆成表单用的「用户名 + 主机」;没有账号前缀时用户名为空。 +// 尾随或开头的 @ 拆不出合法账号,原样交给主机框,由目标校验去报错。 +export function splitTargetForForm(targetValue) { + const value = String(targetValue ?? '').trim(); + const at = value.lastIndexOf('@'); + if (at <= 0 || at === value.length - 1) return { username: '', host: value }; + return { username: value.slice(0, at), host: value.slice(at + 1) }; +} + +// 表单的「用户名 + 主机框」拼回最终目标串。用户名留空时主机框原样(可含 user@ 前缀或别名); +// 填了则以它为准——主机框里已带的账号前缀被替换。 +export function composeTargetInput(username, hostInput) { + const host = String(hostInput ?? '').trim(); + const user = String(username ?? '').trim(); + if (!user) return host; + const bareHost = host.includes('@') ? host.slice(host.lastIndexOf('@') + 1) : host; + return `${user}@${bareHost}`; +} + +// 只比较用户能改的内容;目标的先后顺序不同也算有改动。 +const fingerprint = (draft) => JSON.stringify([draft.targets, draft.downloadDir, draft.syncSecrets]); + +export function isDirty(draft, saved) { + return fingerprint(draft) !== fingerprint(createDraft(saved)); +} + +// 把表单里的目标加进草稿(已有同一个 id 时原地替换)。返回 { draft, errors },errors 为空对象表示成功。 +export function upsertTarget(draft, form) { + // 用户名可选,填了才校验:拼成 user@host 后要能通过目标校验,所以不能有空白、@、冒号或控制字符。 + const username = String(form.username ?? '').trim(); + const errors = {}; + if (username && /[\s@:]/.test(username)) errors.username = '用户名不能包含空格、@ 或冒号'; + else if (username && CONTROL_CHARS.test(username)) errors.username = '用户名不能包含换行或控制字符'; + if (errors.username) return { draft, errors }; + + // 存储里只存拼好的 user@host:用户名框填了就以它为准,主机框里已带的账号前缀被替换。 + const composed = composeTargetInput(username, form.target); + Object.assign(errors, validateTarget({ ...form, target: composed }, draft.targets.filter((item) => item.id !== form.id))); + const password = form.type === 'ssh' ? String(form.password ?? '') : ''; + // askpass 辅助脚本按行输出密码,所以密码里不能有换行或其它控制字符。 + if (!errors.password && CONTROL_CHARS.test(password)) errors.password = '密码不能包含换行或控制字符'; + if (Object.keys(errors).length) return { draft, errors }; + + const target = { ...normalizeTarget({ ...form, target: composed }), ...(password ? { password } : {}) }; + const index = draft.targets.findIndex((item) => item.id === target.id); + const targets = index < 0 ? [...draft.targets, target] : draft.targets.map((item) => (item.id === target.id ? target : item)); + return { draft: { ...draft, targets }, errors: {} }; +} + +export function removeTarget(draft, id) { + return { ...draft, targets: draft.targets.filter((item) => item.id !== id) }; +} + +// 上下移动目标;移出列表边界时原样返回。 +export function moveTarget(draft, id, offset) { + const from = draft.targets.findIndex((item) => item.id === id); + const to = from + offset; + if (from < 0 || to < 0 || to >= draft.targets.length) return draft; + const targets = [...draft.targets]; + [targets[from], targets[to]] = [targets[to], targets[from]]; + return { ...draft, targets }; +} diff --git a/plugins/dagu-transfer/src/shared/controls.css b/plugins/dagu-transfer/src/shared/controls.css new file mode 100644 index 000000000..b68702df7 --- /dev/null +++ b/plugins/dagu-transfer/src/shared/controls.css @@ -0,0 +1,182 @@ +/* 两个插件共用的表单控件与配置面板样式:按钮、字段、开关、说明块、卡片面板。源文件在 plugin/src,快传目录里是同步副本。 */ + +.icon-button, .text-button, .swap-button, .ghost-button, .secondary-button, .primary-button { + border: 1px solid transparent; + border-radius: var(--radius-sm); + transition: background-color var(--transition-fast), border-color var(--transition-fast), color var(--transition-fast), box-shadow var(--transition-fast); +} +.icon-button { + min-height: 32px; + padding: 5px 11px; + border-color: var(--border-color); + background: var(--surface); + color: var(--text-color); + font-size: 12px; + font-weight: 550; +} +.icon-button:hover, .secondary-button:hover { border-color: var(--primary-color); background: var(--hover-bg); } +.primary-button, .secondary-button, .ghost-button { min-height: 34px; padding: 6px 13px; font-size: 13px; font-weight: 600; } +.primary-button { + min-width: 74px; + background: var(--primary-color); + color: var(--primary-contrast); + box-shadow: 0 3px 10px var(--accent-soft); +} +.primary-button:hover { background: var(--primary-hover); } +.secondary-button { border-color: var(--border-color); background: var(--surface); color: var(--text-color); } +.ghost-button { background: transparent; color: var(--text-secondary); } +.ghost-button:hover { color: var(--danger-color); background: rgba(239, 68, 68, .08); } +/* 次级文字入口(复制/编辑/历史等)用次级字体色,主题色只留给主操作按钮。 */ +.text-button { padding: 4px 0; background: transparent; color: var(--text-secondary); font-size: 12px; font-weight: 550; } +.text-button:hover { color: var(--text-color); } +.danger-text { color: var(--danger-color); } + +.primary-button, .secondary-button, .ghost-button, .icon-button, .text-button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; +} +.button-icon { display: inline-flex; align-items: center; } +.button-icon svg { width: 16px; height: 16px; } +.icon-button .button-icon svg { width: 17px; height: 17px; } +[data-icon] { display: inline-flex; align-items: center; justify-content: center; } +[data-icon] svg { width: 16px; height: 16px; } +.icon-button [data-icon] svg { width: 17px; height: 17px; } +.swap-button [data-icon] svg { width: 18px; height: 18px; } + +/* 表单里的输入框与下拉框 */ +.field select, .config-fields select { + width: 100%; + min-height: var(--control-height); + padding: 7px 10px; + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + background: var(--surface-muted); + color: var(--text-color); + outline: none; +} +.form-grid input:focus, .form-grid select:focus, .field select:focus, .config-fields select:focus { + border-color: var(--primary-color); + background: var(--surface); + box-shadow: 0 0 0 3px var(--accent-soft); +} + +/* 配置面板:标题栏、可滚动的卡片内容区、底部操作栏 */ +.config-panel { + width: min(100%, 760px); + max-height: min(88vh, 720px); + max-height: min(88dvh, 720px); + min-height: 0; + display: flex; + flex-direction: column; + overflow: hidden; + border: 1px solid var(--border-color); + border-radius: var(--radius-lg); + background: var(--surface); + box-shadow: var(--shadow-pop); +} +.config-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 16px 18px 12px; + border-bottom: 1px solid var(--divider-color); +} +.config-header h2 { margin: 0; font-size: 16px; } +.config-scroll { flex: 1 1 auto; min-height: 0; overflow: auto; padding: 12px 18px 18px; } +.config-card { + margin-top: 10px; + padding: 14px; + border: 1px solid var(--divider-color); + border-radius: var(--radius-md); + background: var(--surface-muted); +} +.config-fields { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; +} +.field, .form-grid label { + display: flex; + flex-direction: column; + gap: 6px; + color: var(--text-secondary); + font-size: 12px; +} +.field > span { font-weight: 600; } +.field select { min-height: var(--control-height); } +.provider-guide { margin-top: 10px; color: var(--text-secondary); font-size: 12px; } +.provider-guide summary { cursor: pointer; color: var(--primary-color); font-weight: 600; user-select: none; } +.provider-guide summary::marker { content: ''; } +.provider-guide[open] summary { margin-bottom: 8px; } +.provider-guide-body { + padding: 10px 12px; + border-left: 3px solid var(--primary-color); + border-radius: 0 var(--radius-sm) var(--radius-sm) 0; + background: var(--accent-soft); + color: var(--text-color); +} +.provider-guide-body p { margin: 0 0 7px; } +.provider-guide-body p:last-child { margin-bottom: 0; } +.provider-guide-body strong { color: var(--primary-color); } +.card-label { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-bottom: 12px; } +.card-label span { color: var(--text-color); font-size: 13px; font-weight: 650; } +.card-label small { color: var(--text-secondary); font-size: 11px; } +.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } +.form-grid input, .form-grid select { + min-height: var(--control-height); + padding: 7px 10px; + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + background: var(--surface); + color: var(--text-color); + outline: none; +} +.full-field { grid-column: 1 / -1; } +.form-grid small { color: var(--text-secondary); font-size: 10px; } +.sync-warning { + margin-top: 14px; + padding: 12px; + border: 1px solid var(--warning-border); + border-radius: var(--radius-md); + background: var(--warning-bg); +} +.switch-line { display: inline-flex; align-items: center; gap: 8px; color: var(--text-color); font-size: 12px; font-weight: 650; } +.switch-line input { position: absolute; opacity: 0; } +.switch-ui { + position: relative; + width: 32px; + height: 18px; + border-radius: var(--radius-full); + background: var(--border-color); + transition: background var(--transition-fast); +} +.switch-ui::after { + content: ''; + position: absolute; + top: 3px; + left: 3px; + width: 12px; + height: 12px; + border-radius: 50%; + background: #fff; + transition: transform var(--transition-fast); +} +.switch-line input:checked + .switch-ui { background: var(--primary-color); } +.switch-line input:checked + .switch-ui::after { transform: translateX(14px); } +.sync-warning p { margin: 8px 0 0 40px; color: var(--text-secondary); font-size: 11px; line-height: 1.55; } +.config-footer { + display: flex; + flex: 0 0 auto; + justify-content: space-between; + gap: 8px; + padding: 13px 18px 15px; + border-top: 1px solid var(--divider-color); +} + +@media (max-width: 700px) { + .config-fields, .form-grid { grid-template-columns: 1fr; } + .full-field { grid-column: auto; } +} diff --git a/plugins/dagu-transfer/src/shared/kv.js b/plugins/dagu-transfer/src/shared/kv.js new file mode 100644 index 000000000..cc3217c5a --- /dev/null +++ b/plugins/dagu-transfer/src/shared/kv.js @@ -0,0 +1,120 @@ +// 宿主 dbStorage 与本地存储的通用键值读写:有 dbStorage 时优先使用它,否则退回本地存储。 +// 大古截图与大古快传共用(大古快传目录内是同步副本)。 + +function parseStoredValue(value) { + if (value === null || value === undefined || value === '') return null; + if (typeof value === 'string') { + try { + return JSON.parse(value); + } catch { + return null; + } + } + return value; +} + +function getLocalStorage(win) { + try { + return win?.localStorage || globalThis.localStorage || null; + } catch { + return null; + } +} + +// window 与 localStorage 通过参数注入,测试里可以替换;不传时取当前全局环境。 +export function createKvStore({ win, localStorage } = {}) { + const host = win || globalThis.window || globalThis; + const local = localStorage || getLocalStorage(host); + + const dbStorage = () => host?.ztools?.dbStorage || host?.utools?.dbStorage || null; + + return { + get dbStorage() { + return dbStorage(); + }, + + hasDbStorage() { + const storage = dbStorage(); + return Boolean( + storage && ( + typeof storage.getItem === 'function' || + typeof storage.get === 'function' || + typeof storage.setItem === 'function' || + typeof storage.set === 'function' + ) + ); + }, + + async readDb(key) { + const storage = dbStorage(); + if (!storage) return null; + if (typeof storage.getItem === 'function') return parseStoredValue(await storage.getItem(key)); + if (typeof storage.get === 'function') return parseStoredValue(await storage.get(key)); + return null; + }, + + async writeDb(key, value) { + const storage = dbStorage(); + if (!storage) return false; + if (typeof storage.setItem === 'function') { + await storage.setItem(key, value); + return true; + } + if (typeof storage.set === 'function') { + await storage.set(key, value); + return true; + } + return false; + }, + + async removeDb(key) { + const storage = dbStorage(); + if (!storage) return false; + if (typeof storage.removeItem === 'function') { + await storage.removeItem(key); + return true; + } + if (typeof storage.delete === 'function') { + await storage.delete(key); + return true; + } + return false; + }, + + readLocal(key) { + try { + return parseStoredValue(local?.getItem(key)); + } catch { + return null; + } + }, + + writeLocal(key, value) { + try { + local?.setItem(key, JSON.stringify(value)); + return true; + } catch { + return false; + } + }, + + removeLocal(key) { + try { + local?.removeItem?.(key); + } catch { + // Storage can be unavailable in private browser contexts. + } + }, + + // 同一个键:先读 dbStorage,读不到再读本地存储。 + async load(key) { + const stored = this.hasDbStorage() ? await this.readDb(key) : null; + return stored ?? this.readLocal(key); + }, + + // 写入当前可用的存储,返回是否写入成功。 + async save(key, value) { + return this.hasDbStorage() ? this.writeDb(key, value) : this.writeLocal(key, value); + } + }; +} diff --git a/plugins/dagu-transfer/src/shared/synced-secrets.js b/plugins/dagu-transfer/src/shared/synced-secrets.js new file mode 100644 index 000000000..7b7e4ff65 --- /dev/null +++ b/plugins/dagu-transfer/src/shared/synced-secrets.js @@ -0,0 +1,20 @@ +// 「密钥」的存取规则,大古截图与大古快传共用(快传目录内是同步副本): +// - 本机副本始终写在插件自己的 localStorage 里,不随 ZTools 同步; +// - 打开「同步密钥」后,另外往 dbStorage 写一份同步副本(dbStorage 的内容随 ZTools 账号备份同步); +// - 关闭「同步密钥」时删除同步副本,保留本机副本;开关打开时读取以同步副本为准。 + +// keys 是 { local, synced } 两个存储键;fallback 在两处都没有数据时返回。 +export async function loadSecrets({ kv, keys, sync, fallback = null }) { + const local = kv.readLocal(keys.local); + if (!sync || !kv.hasDbStorage()) return local ?? fallback; + const synced = await kv.readDb(keys.synced); + return synced ?? local ?? fallback; +} + +// 返回本机副本是否写入成功。 +export async function saveSecrets({ kv, keys, secrets, sync }) { + const saved = kv.writeLocal(keys.local, secrets); + if (sync && kv.hasDbStorage()) await kv.writeDb(keys.synced, secrets); + else if (kv.hasDbStorage()) await kv.removeDb(keys.synced); + return saved; +} diff --git a/plugins/dagu-transfer/src/shared/theme.css b/plugins/dagu-transfer/src/shared/theme.css new file mode 100644 index 000000000..8e922c712 --- /dev/null +++ b/plugins/dagu-transfer/src/shared/theme.css @@ -0,0 +1,93 @@ +/* ZTools aligned base theme. Runtime host values may override --primary-color. */ +:root { + color-scheme: light; + --bg-color: #f4f4f4; + --surface: #ffffff; + --surface-muted: #f9fafb; + --hover-bg: #f3f4f6; + --active-bg: rgba(2, 132, 199, .10); + --text-color: #333333; + --text-secondary: #616161; + --placeholder-color: #8a8f98; + --border-color: #e5e7eb; + --divider-color: rgba(0, 0, 0, .08); + --primary-color: #0284c7; + --primary-hover: #0369a1; + --primary-contrast: #ffffff; + --accent-soft: rgba(2, 132, 199, .10); + --focus-ring: rgba(2, 132, 199, .28); + --success-color: #10b981; + --warning-color: #f59e0b; + --danger-color: #ef4444; + --warning-bg: rgba(245, 158, 11, .10); + --warning-border: rgba(245, 158, 11, .28); + --overlay-bg: rgba(15, 23, 42, .36); + --shadow-card: 0 1px 2px rgba(0, 0, 0, .04), 0 8px 24px rgba(15, 23, 42, .04); + --shadow-pop: 0 16px 48px rgba(15, 23, 42, .14); + + /* Compatibility aliases used by existing component styles. */ + --canvas: var(--bg-color); + --ink: var(--text-color); + --muted: var(--text-secondary); + --line: var(--border-color); + --teal: var(--primary-color); + --teal-dark: var(--primary-hover); + --orange: var(--warning-color); + --danger: var(--danger-color); + + --radius-sm: 8px; + --radius-md: 10px; + --radius-lg: 12px; + --radius-full: 999px; + --space-1: 4px; + --space-2: 8px; + --space-3: 12px; + --space-4: 16px; + --space-5: 20px; + --space-6: 24px; + --control-height: 36px; + --transition-fast: 150ms ease; + --transition: 180ms ease; +} + +html.dark { + color-scheme: dark; + --bg-color: #303133; + --surface: #374151; + --surface-muted: #414b56; + --hover-bg: rgba(255, 255, 255, .06); + --active-bg: rgba(14, 165, 233, .18); + --text-color: #f3f4f6; + --text-secondary: #bfc0c3; + --placeholder-color: #9ca3af; + --border-color: #4b5563; + --divider-color: rgba(255, 255, 255, .10); + --primary-color: #0ea5e9; + --primary-hover: #38bdf8; + --primary-contrast: #062c3a; + --accent-soft: rgba(14, 165, 233, .18); + --focus-ring: rgba(14, 165, 233, .38); + --success-color: #34d399; + --warning-color: #fbbf24; + --danger-color: #f87171; + --warning-bg: rgba(251, 191, 36, .14); + --warning-border: rgba(251, 191, 36, .32); + --overlay-bg: rgba(0, 0, 0, .46); + --shadow-card: 0 1px 2px rgba(0, 0, 0, .16), 0 10px 28px rgba(0, 0, 0, .16); + --shadow-pop: 0 18px 52px rgba(0, 0, 0, .28); +} +/* Named host themes. A runtime custom color still wins via --primary-color. */ +.theme-blue { --primary-color: #0284c7; --primary-hover: #0369a1; --accent-soft: rgba(2, 132, 199, .10); --focus-ring: rgba(2, 132, 199, .28); } +.theme-purple { --primary-color: #7c3aed; --primary-hover: #6d28d9; --accent-soft: rgba(124, 58, 237, .10); --focus-ring: rgba(124, 58, 237, .28); } +.theme-green { --primary-color: #059669; --primary-hover: #047857; --accent-soft: rgba(5, 150, 105, .10); --focus-ring: rgba(5, 150, 105, .28); } +.theme-orange { --primary-color: #ea580c; --primary-hover: #c2410c; --accent-soft: rgba(234, 88, 12, .10); --focus-ring: rgba(234, 88, 12, .28); } +.theme-red { --primary-color: #dc2626; --primary-hover: #b91c1c; --accent-soft: rgba(220, 38, 38, .10); --focus-ring: rgba(220, 38, 38, .28); } +.theme-pink { --primary-color: #db2777; --primary-hover: #be185d; --accent-soft: rgba(219, 39, 119, .10); --focus-ring: rgba(219, 39, 119, .28); } + +html.dark.theme-blue { --primary-color: #0ea5e9; --primary-hover: #38bdf8; --accent-soft: rgba(14, 165, 233, .18); --focus-ring: rgba(14, 165, 233, .38); } +html.dark.theme-purple { --primary-color: #a78bfa; --primary-hover: #c4b5fd; --accent-soft: rgba(167, 139, 250, .18); --focus-ring: rgba(167, 139, 250, .38); } +html.dark.theme-green { --primary-color: #34d399; --primary-hover: #6ee7b7; --accent-soft: rgba(52, 211, 153, .18); --focus-ring: rgba(52, 211, 153, .38); } +html.dark.theme-orange { --primary-color: #fb923c; --primary-hover: #fdba74; --accent-soft: rgba(251, 146, 60, .18); --focus-ring: rgba(251, 146, 60, .38); } +html.dark.theme-red { --primary-color: #f87171; --primary-hover: #fca5a5; --accent-soft: rgba(248, 113, 113, .18); --focus-ring: rgba(248, 113, 113, .38); } +html.dark.theme-pink { --primary-color: #f472b6; --primary-hover: #f9a8d4; --accent-soft: rgba(244, 114, 182, .18); --focus-ring: rgba(244, 114, 182, .38); } + diff --git a/plugins/dagu-transfer/src/shared/theme.js b/plugins/dagu-transfer/src/shared/theme.js new file mode 100644 index 000000000..103a5c460 --- /dev/null +++ b/plugins/dagu-transfer/src/shared/theme.js @@ -0,0 +1,104 @@ +// 主色与深浅色都跟随 ZTools,规则与其主进程保持一致: +// - 只有 primaryColor === 'custom' 时才使用 customColor,否则按命名主题取色阶,深色下取深色一组; +// - 深浅色取宿主的 isDark(宿主设置默认跟随系统)。宿主没有主题接口时(浏览器)深浅色取系统的 prefers-color-scheme。 +const PRIMARY_COLORS = { + light: { blue: '#0284c7', purple: '#7c3aed', green: '#059669', orange: '#ea580c', red: '#dc2626', pink: '#db2777' }, + dark: { blue: '#38bdf8', purple: '#a78bfa', green: '#34d399', orange: '#fb923c', red: '#f87171', pink: '#f472b6' } +}; + +const DERIVED_TOKENS = ['--primary-color', '--primary-hover', '--primary-contrast', '--accent-soft', '--focus-ring']; + +export function resolveThemePrimaryColor(theme = {}) { + const palette = theme.isDark ? PRIMARY_COLORS.dark : PRIMARY_COLORS.light; + const named = String(theme.primaryColor || ''); + const custom = String(theme.customColor || ''); + if (named === 'custom' && /^#[0-9a-f]{6}$/i.test(custom)) return custom.toLowerCase(); + return palette[named] || palette.green; +} + +function parseHexColor(color) { + const match = /^#([0-9a-f]{6})$/i.exec(String(color || '').trim()); + if (!match) return null; + const value = parseInt(match[1], 16); + return { r: (value >> 16) & 255, g: (value >> 8) & 255, b: value & 255 }; +} + +function toHex({ r, g, b }) { + return `#${[r, g, b].map((channel) => Math.max(0, Math.min(255, Math.round(channel))).toString(16).padStart(2, '0')).join('')}`; +} + +// 主色按钮上的文字按亮度自动选黑/白,自定义亮色时不会出现白字发虚。 +// 深色下宿主的主色都是偏亮的一组,深色文字的门槛相应放低,否则浅色按钮上会出现白字。 +function contrastColor({ r, g, b }, isDark) { + const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255; + return luminance > (isDark ? 0.5 : 0.62) ? '#1f2937' : '#ffffff'; +} + +export function createZtoolsThemeSync({ win = window, doc = document } = {}) { + const root = doc.documentElement; + + const clearDerivedTokens = () => { + DERIVED_TOKENS.forEach((token) => root.style.removeProperty(token)); + }; + // 样式表里 html.dark 这一组变量随之生效。 + const setDark = (isDark) => { + if (isDark) root.classList.add('dark'); + else root.classList.remove('dark'); + }; + + const applyColor = (color, isDark) => { + const rgb = parseHexColor(color); + if (!rgb) { + clearDerivedTokens(); + return; + } + const hover = toHex({ r: rgb.r * 0.88, g: rgb.g * 0.88, b: rgb.b * 0.88 }); + root.style.setProperty('--primary-color', toHex(rgb)); + root.style.setProperty('--primary-hover', hover); + root.style.setProperty('--primary-contrast', contrastColor(rgb, isDark)); + root.style.setProperty('--accent-soft', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, .10)`); + root.style.setProperty('--focus-ring', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, .28)`); + }; + + // 宿主会注入 --plugin-primary-color(含自定义色判定),优先直接采用它。 + const hostInjectedColor = () => { + try { + const value = win.getComputedStyle?.(root)?.getPropertyValue?.('--plugin-primary-color')?.trim(); + return /^#[0-9a-f]{6}$/i.test(value || '') ? value : ''; + } catch { + return ''; + } + }; + + const applyTheme = (theme = {}) => { + const isDark = Boolean(theme?.isDark); + setDark(isDark); + applyColor(hostInjectedColor() || resolveThemePrimaryColor(theme), isDark); + }; + + const host = win.ztools; + if (typeof host?.getThemeInfo === 'function' && typeof host?.onThemeChange === 'function') { + applyTheme(host.getThemeInfo()); + host.onThemeChange(applyTheme); + return () => { + clearDerivedTokens(); + setDark(false); + }; + } + + // 没有宿主主题接口(普通浏览器):深浅色取系统设置,主色沿用样式表里的默认值。 + let media = null; + try { + media = typeof win.matchMedia === 'function' ? win.matchMedia('(prefers-color-scheme: dark)') : null; + } catch { + media = null; + } + if (!media) return () => {}; + const applySystem = (event) => setDark(Boolean(event?.matches)); + applySystem(media); + media.addEventListener?.('change', applySystem); + return () => { + media.removeEventListener?.('change', applySystem); + setDark(false); + }; +} diff --git a/plugins/dagu-transfer/src/styles.css b/plugins/dagu-transfer/src/styles.css new file mode 100644 index 000000000..92323c917 --- /dev/null +++ b/plugins/dagu-transfer/src/styles.css @@ -0,0 +1,109 @@ +@import './shared/theme.css'; +@import './shared/controls.css'; + +* { box-sizing: border-box; } + +html, body, #app { min-height: 100%; margin: 0; } + +body { + overflow-x: hidden; + background: var(--surface); + color: var(--text-color); + font-size: 13px; + line-height: 1.6; + font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif; +} + +button, input { font: inherit; color: inherit; } +button { cursor: pointer; } +button:disabled { cursor: default; opacity: .45; } +button:focus-visible, input:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 2px; } +svg { display: block; width: 16px; height: 16px; } + +/* ── 启动器里的下拉列表 ── */ +.transfer-list { padding: 4px 0; } +.transfer-status { padding: 10px 16px; } +.transfer-status-title { font-weight: 500; } +.transfer-status-subtitle { color: var(--text-secondary); font-size: 12px; word-break: break-all; } +.tone-danger .transfer-status-title { color: var(--danger-color); } + +.transfer-rows { max-height: 480px; overflow-y: auto; } +.transfer-row { margin: 0 8px; padding: 8px 12px; border-radius: var(--radius-sm); cursor: pointer; } +.transfer-row-title { font-weight: 500; } +.transfer-row-subtitle { color: var(--text-secondary); font-size: 12px; word-break: break-all; } +.transfer-row:hover { background: var(--hover-bg); } +.transfer-row.active, .transfer-row.active:hover { background: var(--primary-color); color: var(--primary-contrast); } +.transfer-row.active .transfer-row-subtitle { color: var(--primary-contrast); opacity: .82; } + +/* ── 配置页 ── + 按钮、字段、开关、卡片面板的样式与大古截图共用 controls.css,这里只放快传特有的部分。 */ +.setup-shell { min-height: 100vh; padding: 12px; display: flex; background: var(--bg-color); } +.setup-shell .config-panel { flex: 1; width: 100%; max-height: calc(100vh - 24px); } + +.setup-header-side { display: flex; align-items: center; gap: 12px; } +.setup-notice { color: var(--text-secondary); font-size: 12px; } +.setup-notice[data-tone='warning'] { color: var(--warning-color); } +.setup-notice[data-tone='danger'] { color: var(--danger-color); } +.setup-actions { display: inline-flex; gap: 8px; } +.setup-footer-note { color: var(--text-secondary); font-size: 12px; } + +.target-form { + margin-bottom: 12px; + padding: 12px; + border: 1px solid var(--border-color); + border-radius: var(--radius-md); + background: var(--surface); +} +.field-control { display: flex; gap: 8px; align-items: center; } +.field-control input { flex: 1; min-width: 0; } +/* 校验提示跟在对应的输入框下面(字段本身是纵向排列的 label)。 */ +.form-grid .field-error { color: var(--danger-color); font-size: 11px; } +.form-actions { grid-column: 1 / -1; display: flex; gap: 8px; justify-content: flex-end; } + +/* 编辑表单在被编辑行下方展开:缩进对齐行内容,边框弱化成从属观感。 */ +.target-edit-slot { list-style: none; } +.target-form-inline { margin: -2px 0 0 0; padding: 10px; padding-left: 22px; } +.target-form-inline .form-actions { justify-content: flex-end; } + +.target-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; max-height: 220px; overflow-y: auto; } +/* 行内展开编辑表单时放开列表限高,让表单完整可见。 */ +.target-list-editing { max-height: none; overflow-y: visible; } +.target-item { + display: flex; align-items: center; gap: 12px; + padding: 8px 10px; + border: 1px solid var(--border-color); + border-radius: var(--radius-md); + background: var(--surface); +} +.target-icon { + display: grid; place-items: center; flex: none; + width: 32px; height: 32px; border-radius: var(--radius-sm); + background: var(--accent-soft); color: var(--primary-color); +} +.target-main { flex: 1; min-width: 0; display: flex; flex-direction: column; } +.target-name { font-weight: 500; } +/* 只标出登录方式,不显示密码。 */ +.target-auth { + margin-left: 6px; padding: 0 7px; + border-radius: var(--radius-full); + background: var(--accent-soft); color: var(--primary-color); + font-size: 11px; font-weight: 500; +} +.target-dest { color: var(--text-secondary); font-size: 12px; word-break: break-all; } +.target-tools { display: flex; gap: 2px; } +.tool-btn { + display: inline-grid; place-items: center; + width: 28px; height: 28px; padding: 0; + border: 0; border-radius: var(--radius-sm); + background: transparent; color: var(--text-secondary); +} +.tool-btn svg { width: 14px; height: 14px; } +.tool-btn:hover:not(:disabled) { background: var(--hover-bg); color: var(--text-color); } +.tool-btn.danger:hover:not(:disabled) { color: var(--danger-color); background: rgba(239, 68, 68, .08); } +.setup-empty { + margin: 0; padding: 16px; text-align: center; color: var(--text-secondary); + border: 1px dashed var(--border-color); border-radius: var(--radius-md); +} + +.download-row { display: flex; align-items: center; gap: 12px; } +.download-dir { flex: 1; min-width: 0; word-break: break-all; color: var(--text-secondary); } diff --git a/plugins/dagu-transfer/src/ui/icons.js b/plugins/dagu-transfer/src/ui/icons.js new file mode 100644 index 000000000..99780a61a --- /dev/null +++ b/plugins/dagu-transfer/src/ui/icons.js @@ -0,0 +1,23 @@ +// 界面图标取自 Lucide (https://lucide.dev),ISC 许可证;由 scripts/generate-icons.mjs 生成,请勿手改。 +// 使用图标:settings, plus, pencil, folder, server, chevron-up, chevron-down, trash-2, check, x, eye, eye-off + +export const ICON_PATHS = { + settings: '', + plus: '', + edit: '', + folder: '', + server: '', + up: '', + down: '', + trash: '', + check: '', + close: '', + eye: '', + eyeOff: '' +}; + +export function iconMarkup(name) { + const body = ICON_PATHS[name]; + if (!body) return ''; + return ``; +} diff --git a/plugins/dagu-transfer/vite.config.js b/plugins/dagu-transfer/vite.config.js new file mode 100644 index 000000000..596e4e5be --- /dev/null +++ b/plugins/dagu-transfer/vite.config.js @@ -0,0 +1,31 @@ +import { defineConfig } from 'vite'; +import vue from '@vitejs/plugin-vue'; +import { fileURLToPath } from 'node:url'; +import { resolve } from 'node:path'; + +const pluginRoot = fileURLToPath(new URL('.', import.meta.url)); + +export default defineConfig({ + root: pluginRoot, + plugins: [vue()], + css: { + lightningcss: { + errorRecovery: true + } + }, + base: './', + // 宿主的开发入口是 http://127.0.0.1:5174/index.html(见 plugin.json 的 development.main)。 + // 不指定 host 时 vite 监听 localhost,Node 17+ 在 Windows 上把它解析成 IPv6 的 ::1, + // 宿主连 127.0.0.1 会被拒绝,页面空白。 + server: { + host: '127.0.0.1', + }, + build: { + outDir: 'dist', + rollupOptions: { + input: { + index: resolve(pluginRoot, 'index.html') + } + } + } +});