diff --git a/plugins/link-to-idm/.gitignore b/plugins/link-to-idm/.gitignore
new file mode 100644
index 000000000..b94707787
--- /dev/null
+++ b/plugins/link-to-idm/.gitignore
@@ -0,0 +1,2 @@
+node_modules/
+dist/
diff --git a/plugins/link-to-idm/CHANGELOG.md b/plugins/link-to-idm/CHANGELOG.md
new file mode 100644
index 000000000..5308ff864
--- /dev/null
+++ b/plugins/link-to-idm/CHANGELOG.md
@@ -0,0 +1,14 @@
+# Changelog
+
+## 1.0.0 - 2026-12-03
+
+### 新增
+
+- **粘贴即下载**:识别搜索栏中的 `http` / `https` 链接,直接调用 IDM 下载,无需打开面板
+- **文件名推断**:依次尝试链接路径末段、查询参数(`filename` / `file` / `name` / `download` / `fname`)、HEAD 请求的 `Content-Disposition` 与 `Content-Type`,最终回退到时间戳命名
+- **文件名清洗**:替换 Windows 非法字符、去除结尾空格与点、规避 `CON` / `PRN` / `NUL` 等保留名、截断至 120 字符并保留扩展名
+- **控制面板**:手动填写链接、修改文件名、选择保存目录、切换「粘贴后自动发送」与「仅加入队列」、查看最近 10 条操作记录
+- **搜索栏内联结果**:开启「搜索栏推送」后,粘贴链接可直接选择「用 IDM 下载」或「打开面板调整」
+- **设置持久化**:保存目录、自动发送、队列模式等选项通过 ZTools `dbStorage` 保存
+- **重复提交保护**:相同链接与文件名在 30 秒内重复提交会被拒绝
+- **IDM 定位**:读取 `HKCU\Software\DownloadManager` 获取 IDMan.exe 路径与默认下载目录,失败时回退到常见安装路径与 `%USERPROFILE%\Downloads`
\ No newline at end of file
diff --git a/plugins/link-to-idm/README.md b/plugins/link-to-idm/README.md
new file mode 100644
index 000000000..f18d516cb
--- /dev/null
+++ b/plugins/link-to-idm/README.md
@@ -0,0 +1,60 @@
+# 链接转 IDM 下载
+
+ZTools 插件。在搜索栏粘贴链接,自动识别文件名并交给 Internet Download Manager 下载。
+
+## 功能
+
+**粘贴即下载** — 粘贴 `http` / `https` 链接,直接调用 IDM 下载,无需打开面板。
+
+**文件名识别** — 按以下顺序推断,取到即停:
+
+1. 链接路径末段(自动 URL 解码,如 `%E4%B8%AD%E6%96%87.zip` → `中文.zip`)
+2. 查询参数 `filename` / `file` / `name` / `download` / `fname`
+3. HEAD 请求的 `Content-Disposition`,其次 `Content-Type`
+4. 时间戳 `download_20261203_150405`(不编造扩展名)
+
+结果会清洗为 Windows 合法文件名:替换非法字符、去除结尾空格与点、避开 `CON`/`PRN`/`NUL` 等保留名、截断至 120 字符并保留扩展名。
+
+**控制面板** — 搜索 `链接转IDM` / `IDM下载` / `link to idm` 进入,可手动填写链接、修改文件名、选择保存目录、切换「粘贴后自动发送」「仅加入队列」,并查看最近 10 条记录。
+
+**搜索栏内联结果** — 在插件详情中开启「搜索栏推送」后,粘贴链接时可直接看到「用 IDM 下载」和「打开面板调整」两个选项。
+
+## 安装
+
+1. ZTools → 设置 → 插件 → **导入本地插件**
+2. 选择 `dist/link-to-idm-1.0.0.zip`
+
+打包时 `plugin.json` 必须位于 zip 根目录,不能有外层文件夹。
+
+## 使用说明
+
+- 默认开启「粘贴后自动发送」,粘贴链接后直接提交 IDM
+- 「仅加入队列」对应 IDM 的 `/a` 参数,任务入队但不立即开始
+- 保存目录不存在时会直接报错,不会静默失败
+- 相同链接 + 相同文件名在 30 秒内重复提交会被拒绝
+
+## 文件结构
+
+```
+├── plugin.json 插件清单(2 个功能)
+├── preload.js 主逻辑:宿主事件、IDM 调用、设置持久化
+├── index.html 面板界面
+├── index.js 面板逻辑
+├── index.css 样式
+├── logo.png 图标
+├── CHANGELOG.md 更新日志
+├── lib/
+│ ├── url-parse.js URL 解析、文件名推断、IDM 参数构造
+│ └── idm.js IDM 定位与调用
+└── dist/
+ └── link-to-idm-1.0.0.zip
+```
+
+## 说明
+
+- 仅支持 Windows(依赖注册表与 `IDMan.exe`)
+- 通过 `HKCU\Software\DownloadManager` 读取 IDM 路径与默认下载目录,不写入任何配置
+- 启动参数以数组传递,不使用 shell 拼接;不传 `/q`(该参数会让 IDM 下载完成后退出)
+- 提交成功仅代表命令已交给 IDM,是否真正入队请在 IDM 中确认
+- 一次粘贴多个链接时只取第一个
+- Deepseek-4.1F编写
diff --git a/plugins/link-to-idm/index.css b/plugins/link-to-idm/index.css
new file mode 100644
index 000000000..686f898cf
--- /dev/null
+++ b/plugins/link-to-idm/index.css
@@ -0,0 +1,340 @@
+/* 链接转 IDM 下载 —— 面板样式 */
+
+:root {
+ --bg: #ffffff;
+ --bg-soft: #f6f7f9;
+ --border: #e3e6ea;
+ --text: #1f2328;
+ --text-dim: #6b7280;
+ --primary: #2f6feb;
+ --primary-hover: #2558c4;
+ --primary-text: #ffffff;
+ --danger: #d92d20;
+ --success: #12805c;
+ --radius: 10px;
+ --shadow: 0 1px 2px rgba(16, 24, 40, 0.06);
+}
+
+@media (prefers-color-scheme: dark) {
+ :root {
+ --bg: #1c1f24;
+ --bg-soft: #24282e;
+ --border: #33383f;
+ --text: #e6e8eb;
+ --text-dim: #9aa2ad;
+ --primary: #4a86f7;
+ --primary-hover: #6b9cf9;
+ --primary-text: #ffffff;
+ --danger: #f97066;
+ --success: #3ddc97;
+ --shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
+ }
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html,
+body {
+ margin: 0;
+ padding: 0;
+ height: 100%;
+ background: var(--bg);
+ color: var(--text);
+ font-family: "Microsoft YaHei UI", "Microsoft YaHei", "PingFang SC", system-ui, sans-serif;
+ font-size: 13px;
+ overflow: hidden;
+}
+
+.app {
+ display: flex;
+ flex-direction: column;
+ height: 100vh;
+}
+
+.app-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 16px;
+ border-bottom: 1px solid var(--border);
+ background: var(--bg-soft);
+ flex: 0 0 auto;
+}
+
+.title-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.title {
+ font-size: 14px;
+ font-weight: 600;
+}
+
+.badge {
+ font-size: 11px;
+ padding: 2px 8px;
+ border-radius: 999px;
+ border: 1px solid var(--border);
+ color: var(--text-dim);
+ white-space: nowrap;
+}
+
+.badge.ok {
+ color: var(--success);
+ border-color: currentColor;
+}
+
+.badge.error {
+ color: var(--danger);
+ border-color: currentColor;
+}
+
+.icon-button {
+ border: 1px solid var(--border);
+ background: transparent;
+ color: var(--text-dim);
+ border-radius: 8px;
+ padding: 4px 10px;
+ cursor: pointer;
+ font-size: 12px;
+}
+
+.icon-button:hover {
+ color: var(--text);
+}
+
+.app-main {
+ flex: 1 1 auto;
+ overflow-y: auto;
+ padding: 12px 16px 20px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.card {
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ background: var(--bg-soft);
+ padding: 12px;
+ box-shadow: var(--shadow);
+}
+
+.field-label,
+.info-label {
+ display: block;
+ font-size: 11px;
+ color: var(--text-dim);
+ margin-bottom: 4px;
+}
+
+.url-input,
+.text-input {
+ width: 100%;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--bg);
+ color: var(--text);
+ padding: 7px 9px;
+ font-size: 13px;
+ font-family: inherit;
+ outline: none;
+ resize: none;
+}
+
+.url-input {
+ word-break: break-all;
+}
+
+.url-input:focus,
+.text-input:focus {
+ border-color: var(--primary);
+}
+
+.row {
+ display: flex;
+ align-items: center;
+}
+
+.row.gap {
+ gap: 8px;
+ margin-top: 8px;
+}
+
+.grow {
+ flex: 1 1 auto;
+}
+
+.hint {
+ font-size: 11px;
+ color: var(--text-dim);
+ margin-left: auto;
+}
+
+.button {
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 6px 12px;
+ font-size: 12px;
+ font-family: inherit;
+ cursor: pointer;
+ background: var(--bg);
+ color: var(--text);
+ white-space: nowrap;
+}
+
+.button:hover {
+ border-color: var(--primary);
+}
+
+.button.primary {
+ background: var(--primary);
+ border-color: var(--primary);
+ color: var(--primary-text);
+ font-weight: 600;
+ padding: 8px 18px;
+}
+
+.button.primary:hover {
+ background: var(--primary-hover);
+ border-color: var(--primary-hover);
+}
+
+.button.secondary {
+ background: var(--bg);
+ color: var(--text);
+}
+
+.button:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+.info-grid {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: 10px;
+ margin-bottom: 10px;
+}
+
+.info-item.full {
+ grid-column: 1 / -1;
+}
+
+.info-value {
+ display: block;
+ font-size: 13px;
+ padding: 7px 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.actions {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ flex-wrap: wrap;
+}
+
+.switch {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ color: var(--text-dim);
+ cursor: pointer;
+ user-select: none;
+}
+
+.switch input {
+ accent-color: var(--primary);
+ cursor: pointer;
+}
+
+.log-card {
+ flex: 1 1 auto;
+ display: flex;
+ flex-direction: column;
+ min-height: 110px;
+}
+
+.log-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 6px;
+}
+
+.link-button {
+ border: none;
+ background: transparent;
+ color: var(--primary);
+ font-size: 11px;
+ cursor: pointer;
+ padding: 0;
+}
+
+.log-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ overflow-y: auto;
+ flex: 1 1 auto;
+ font-size: 12px;
+}
+
+.log-list li {
+ display: flex;
+ gap: 8px;
+ padding: 4px 0;
+ border-bottom: 1px dashed var(--border);
+ word-break: break-all;
+}
+
+.log-list li:last-child {
+ border-bottom: none;
+}
+
+.log-time {
+ color: var(--text-dim);
+ flex: 0 0 auto;
+ font-variant-numeric: tabular-nums;
+}
+
+.log-text {
+ flex: 1 1 auto;
+}
+
+.log-text.error {
+ color: var(--danger);
+}
+
+.log-text.success {
+ color: var(--success);
+}
+
+.log-empty {
+ color: var(--text-dim);
+ font-size: 12px;
+ padding: 6px 0;
+}
+
+/* 滚动条 */
+::-webkit-scrollbar {
+ width: 8px;
+ height: 8px;
+}
+
+::-webkit-scrollbar-thumb {
+ background: var(--border);
+ border-radius: 4px;
+}
+
+::-webkit-scrollbar-thumb:hover {
+ background: var(--text-dim);
+}
diff --git a/plugins/link-to-idm/index.html b/plugins/link-to-idm/index.html
new file mode 100644
index 000000000..d3cf88ac2
--- /dev/null
+++ b/plugins/link-to-idm/index.html
@@ -0,0 +1,90 @@
+
+
+
+
+
+ 链接转 IDM 下载
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 文件名
+
+
+
+ 类型
+ —
+
+
+ 大小
+ 未知
+
+
+ 来源站点
+ —
+
+
+
+
保存目录
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/plugins/link-to-idm/index.js b/plugins/link-to-idm/index.js
new file mode 100644
index 000000000..bf502c21d
--- /dev/null
+++ b/plugins/link-to-idm/index.js
@@ -0,0 +1,380 @@
+'use strict';
+
+/**
+ * 链接转 IDM 下载 —— 页面逻辑
+ *
+ * 渲染进程没有 Node 权限,所有系统能力都通过 preload 暴露的 window.linkToIdm 调用。
+ */
+
+(function () {
+ const api = window.linkToIdm
+ const MAX_LOG = 10
+
+ const el = {
+ envBadge: document.getElementById('envBadge'),
+ inputUrl: document.getElementById('inputUrl'),
+ analyzeHint: document.getElementById('analyzeHint'),
+ inputFileName: document.getElementById('inputFileName'),
+ infoExtension: document.getElementById('infoExtension'),
+ infoSize: document.getElementById('infoSize'),
+ infoHost: document.getElementById('infoHost'),
+ inputSaveDir: document.getElementById('inputSaveDir'),
+ chkAutoSend: document.getElementById('chkAutoSend'),
+ chkQueueOnly: document.getElementById('chkQueueOnly'),
+ btnPaste: document.getElementById('btnPaste'),
+ btnClear: document.getElementById('btnClear'),
+ btnChooseDir: document.getElementById('btnChooseDir'),
+ btnOpenDir: document.getElementById('btnOpenDir'),
+ btnSend: document.getElementById('btnSend'),
+ btnCopy: document.getElementById('btnCopy'),
+ btnIdmSite: document.getElementById('btnIdmSite'),
+ btnClearLog: document.getElementById('btnClearLog'),
+ logList: document.getElementById('logList')
+ }
+
+ /** 当前分析结果 */
+ let current = null
+ /** 分析序号,用于丢弃过期结果 */
+ let analyzeToken = 0
+
+ /**
+ * 追加一条操作记录。
+ * @param {string} text 内容
+ * @param {'info' | 'success' | 'error'} [kind] 类型
+ * @returns {void}
+ */
+ function addLog(text, kind = 'info') {
+ const empty = el.logList.querySelector('.log-empty')
+ if (empty) empty.remove()
+
+ const now = new Date()
+ const pad = (value) => String(value).padStart(2, '0')
+ const time = pad(now.getHours()) + ':' + pad(now.getMinutes()) + ':' + pad(now.getSeconds())
+
+ const li = document.createElement('li')
+ const timeSpan = document.createElement('span')
+ timeSpan.className = 'log-time'
+ timeSpan.textContent = time
+
+ const textSpan = document.createElement('span')
+ textSpan.className = 'log-text' + (kind === 'info' ? '' : ' ' + kind)
+ textSpan.textContent = text
+
+ li.appendChild(timeSpan)
+ li.appendChild(textSpan)
+ el.logList.insertBefore(li, el.logList.firstChild)
+
+ while (el.logList.children.length > MAX_LOG) {
+ el.logList.removeChild(el.logList.lastChild)
+ }
+ }
+
+ /**
+ * 格式化文件大小。
+ * @param {number} bytes 字节数
+ * @returns {string}
+ */
+ function formatSize(bytes) {
+ const value = Number(bytes || 0)
+ if (!value || value <= 0) return '未知'
+ const units = ['B', 'KB', 'MB', 'GB', 'TB']
+ let size = value
+ let index = 0
+ while (size >= 1024 && index < units.length - 1) {
+ size /= 1024
+ index += 1
+ }
+ return (index === 0 ? size : size.toFixed(1)) + ' ' + units[index]
+ }
+
+ /**
+ * 把分析结果渲染到界面。
+ * @param {object | null} info analyze 结果
+ * @returns {void}
+ */
+ function renderInfo(info) {
+ current = info
+ if (!info) {
+ el.inputFileName.value = ''
+ el.infoExtension.textContent = '—'
+ el.infoSize.textContent = '未知'
+ el.infoHost.textContent = '—'
+ el.analyzeHint.textContent = ''
+ return
+ }
+ if (!info.ok) {
+ el.inputFileName.value = ''
+ el.infoExtension.textContent = '—'
+ el.infoSize.textContent = '未知'
+ el.infoHost.textContent = '—'
+ el.analyzeHint.textContent = info.reason || '链接无效'
+ return
+ }
+ el.inputFileName.value = info.fileName || ''
+ el.infoExtension.textContent = info.extension ? info.extension.toUpperCase() : '未知'
+ el.infoSize.textContent = formatSize(info.contentLength)
+ el.infoHost.textContent = info.host || '—'
+ el.analyzeHint.textContent = info.nameSource === 'timestamp'
+ ? '未能从链接得到文件名,已用时间戳命名'
+ : ''
+ }
+
+ /**
+ * 分析当前输入框里的链接。
+ * @returns {Promise}
+ */
+ async function analyzeInput() {
+ const text = el.inputUrl.value.trim()
+ if (!text) {
+ renderInfo(null)
+ return
+ }
+
+ const token = ++analyzeToken
+ el.analyzeHint.textContent = '识别中…'
+
+ let info
+ try {
+ info = await api.analyze(text)
+ } catch (error) {
+ if (token === analyzeToken) {
+ el.analyzeHint.textContent = '识别失败: ' + (error && error.message ? error.message : error)
+ }
+ return
+ }
+
+ if (token !== analyzeToken) return
+ renderInfo(info)
+ }
+
+ /**
+ * 发送当前任务到 IDM。
+ * @returns {Promise}
+ */
+ async function doSend() {
+ const url = el.inputUrl.value.trim()
+ if (!url) {
+ addLog('请先填入链接', 'error')
+ return
+ }
+
+ el.btnSend.disabled = true
+ try {
+ const result = await api.send({
+ url: current && current.ok ? current.url : url,
+ fileName: el.inputFileName.value.trim(),
+ saveDir: el.inputSaveDir.value.trim(),
+ queueOnly: el.chkQueueOnly.checked
+ })
+
+ if (result.ok) {
+ addLog(
+ result.unverified
+ ? '已提交给 IDM:' + result.fileName + '(请在 IDM 里确认是否已入队)'
+ : '已发送到 IDM:' + result.fileName,
+ 'success'
+ )
+ } else {
+ addLog(result.error || '发送失败', 'error')
+ }
+ } catch (error) {
+ addLog('发送异常: ' + (error && error.message ? error.message : error), 'error')
+ } finally {
+ el.btnSend.disabled = false
+ }
+ }
+
+ /**
+ * 把设置里的自动发送/仅队列同步到控件。
+ * @param {object} settings 设置
+ * @returns {void}
+ */
+ function renderSettings(settings) {
+ el.chkAutoSend.checked = Boolean(settings.autoSend)
+ el.chkQueueOnly.checked = Boolean(settings.queueOnly)
+ }
+
+ /**
+ * 初始化:读取环境与设置。
+ * @returns {Promise}
+ */
+ async function init() {
+ if (!api) {
+ el.envBadge.textContent = '宿主未就绪'
+ el.envBadge.className = 'badge error'
+ addLog('未检测到 ZTools 运行环境', 'error')
+ return
+ }
+
+ let state
+ try {
+ state = api.getState()
+ } catch (error) {
+ el.envBadge.textContent = '读取失败'
+ el.envBadge.className = 'badge error'
+ addLog('读取环境失败: ' + (error && error.message ? error.message : error), 'error')
+ return
+ }
+
+ if (state.env && state.env.idmFound) {
+ el.envBadge.textContent = 'IDM 已就绪'
+ el.envBadge.className = 'badge ok'
+ el.envBadge.title = state.env.exePath
+ } else {
+ el.envBadge.textContent = '未找到 IDM'
+ el.envBadge.className = 'badge error'
+ el.envBadge.title = state.env ? state.env.exePath || '未检测到 IDMan.exe' : '未检测到 IDMan.exe'
+ addLog('未找到 IDMan.exe,请确认已安装 IDM', 'error')
+ }
+
+ el.inputSaveDir.value = state.saveDir || ''
+ renderSettings(state.settings || {})
+
+ // 处理进入插件时带过来的待处理项
+ const pending = state.pending
+ if (pending) {
+ if (pending.ok) {
+ el.inputUrl.value = pending.url || ''
+ renderInfo(pending)
+ if (pending.handled) {
+ const result = pending.result
+ if (result && result.ok) {
+ addLog(
+ result.unverified
+ ? '已提交给 IDM:' + result.fileName + '(请在 IDM 里确认是否已入队)'
+ : '已发送到 IDM:' + result.fileName,
+ 'success'
+ )
+ } else if (result && result.error) {
+ addLog(result.error, 'error')
+ }
+ }
+ } else if (pending.raw) {
+ el.inputUrl.value = pending.raw
+ renderInfo(pending)
+ addLog(pending.reason || '链接无效', 'error')
+ }
+ api.clearPending()
+ }
+
+ if (typeof api.onPendingChange === 'function') {
+ api.onPendingChange((item) => {
+ if (!item) return
+ if (item.ok) {
+ el.inputUrl.value = item.url || ''
+ renderInfo(item)
+ }
+ })
+ }
+
+ if (typeof api.setHeight === 'function') {
+ api.setHeight(560)
+ }
+ }
+
+ // --- 事件绑定 ---
+
+ el.inputUrl.addEventListener('input', () => {
+ void analyzeInput()
+ })
+
+ el.inputUrl.addEventListener('paste', () => {
+ // 粘贴后内容还没写入,等一拍再分析
+ setTimeout(() => {
+ void analyzeInput()
+ }, 0)
+ })
+
+ el.btnPaste.addEventListener('click', async () => {
+ let text = ''
+ try {
+ if (typeof api.readClipboardText === 'function') {
+ text = await api.readClipboardText()
+ }
+ } catch {
+ text = ''
+ }
+ if (!text) {
+ addLog('剪贴板里没有文本,请手动粘贴', 'error')
+ return
+ }
+ el.inputUrl.value = text
+ await analyzeInput()
+ })
+
+ el.btnClear.addEventListener('click', () => {
+ el.inputUrl.value = ''
+ renderInfo(null)
+ })
+
+ el.btnChooseDir.addEventListener('click', () => {
+ const dir = api.chooseDir()
+ if (dir) {
+ el.inputSaveDir.value = dir
+ api.saveSettings({ saveDir: dir })
+ addLog('保存目录已更新: ' + dir)
+ }
+ })
+
+ el.btnOpenDir.addEventListener('click', () => {
+ api.openFolder(el.inputSaveDir.value.trim())
+ })
+
+ el.btnSend.addEventListener('click', () => {
+ void doSend()
+ })
+
+ el.btnCopy.addEventListener('click', () => {
+ const url = el.inputUrl.value.trim()
+ if (!url) {
+ addLog('没有可复制的链接', 'error')
+ return
+ }
+ if (api.copyText(url)) {
+ addLog('链接已复制')
+ } else {
+ addLog('复制失败', 'error')
+ }
+ })
+
+ el.btnIdmSite.addEventListener('click', () => {
+ api.openIdmWebsite()
+ })
+
+ el.btnClearLog.addEventListener('click', () => {
+ el.logList.innerHTML = ''
+ const li = document.createElement('li')
+ li.className = 'log-empty'
+ li.textContent = '暂无记录'
+ el.logList.appendChild(li)
+ })
+
+ el.chkAutoSend.addEventListener('change', () => {
+ api.saveSettings({ autoSend: el.chkAutoSend.checked })
+ addLog(el.chkAutoSend.checked ? '已开启粘贴后自动发送' : '已关闭粘贴后自动发送')
+ })
+
+ el.chkQueueOnly.addEventListener('change', () => {
+ api.saveSettings({ queueOnly: el.chkQueueOnly.checked })
+ addLog(el.chkQueueOnly.checked ? '已开启仅加入队列' : '已改为立即开始下载')
+ })
+
+ el.inputSaveDir.addEventListener('change', () => {
+ api.saveSettings({ saveDir: el.inputSaveDir.value.trim() })
+ })
+
+ el.inputFileName.addEventListener('change', () => {
+ if (current && current.ok) {
+ current.fileName = el.inputFileName.value.trim()
+ }
+ })
+
+ document.addEventListener('keydown', (event) => {
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
+ event.preventDefault()
+ void doSend()
+ }
+ })
+
+ void init()
+})()
diff --git a/plugins/link-to-idm/lib/idm.js b/plugins/link-to-idm/lib/idm.js
new file mode 100644
index 000000000..df08eae7e
--- /dev/null
+++ b/plugins/link-to-idm/lib/idm.js
@@ -0,0 +1,325 @@
+'use strict'
+
+/**
+ * IDM 定位与调用。
+ *
+ * 只做三件事:找到 IDMan.exe、找到默认下载目录、把链接交给 IDM。
+ * 全部通过命令行参数数组传参,不拼接 shell 字符串。
+ */
+
+const fs = require('node:fs')
+const os = require('node:os')
+const path = require('node:path')
+const { spawn, spawnSync } = require('node:child_process')
+
+const REG_KEY = 'HKCU\\Software\\DownloadManager'
+
+/**
+ * 观察 IDMan.exe 退出的时间窗(毫秒)。
+ * IDM 已在运行时子进程会立即以 0 退出;未运行时它会常驻不退出。
+ * 窗口内既未退出也未报错,即认为任务已交给 IDM。
+ */
+const EXIT_WINDOW_MS = 1200
+
+/** 常见安装路径,按优先级排列 */
+const FALLBACK_PATHS = [
+ 'C:\\Program Files (x86)\\Internet Download Manager\\IDMan.exe',
+ 'C:\\Program Files\\Internet Download Manager\\IDMan.exe'
+]
+
+/**
+ * 查询注册表字符串值。
+ * @param {string} name 值名
+ * @returns {string} 值内容,失败返回空串
+ */
+function readRegString(name) {
+ try {
+ const result = spawnSync('reg', ['query', REG_KEY, '/v', name], {
+ encoding: 'utf8',
+ windowsHide: true,
+ timeout: 5000
+ })
+ if (!result || result.status !== 0 || !result.stdout) return ''
+ const line = result.stdout
+ .split(/\r?\n/)
+ .find((item) => item.trim().startsWith(name))
+ if (!line) return ''
+ const match = line.match(/REG_SZ\s+(.+)$/)
+ return match ? match[1].trim() : ''
+ } catch {
+ return ''
+ }
+}
+
+/**
+ * 把 `reg query` 输出的 REG_NONE 十六进制串解码成路径。
+ *
+ * IDM 把 LocalPathW 存为 UTF-16LE 字节串,输出形如
+ * `43003A005C0055007300650072007300...`,末尾带 `0000`。
+ *
+ * @param {string} hex 十六进制串(可含空格)
+ * @returns {string} 解码后的路径,无法解码返回空串
+ */
+function decodeRegHexPath(hex) {
+ const clean = String(hex || '').replace(/\s+/g, '')
+ if (!clean || clean.length % 4 !== 0 || !/^[0-9A-Fa-f]+$/.test(clean)) return ''
+ try {
+ const bytes = Buffer.from(clean, 'hex')
+ return bytes.toString('utf16le').replace(/\u0000+$/, '').trim()
+ } catch {
+ return ''
+ }
+}
+
+/**
+ * 查询 LocalPathW(IDM 存为 REG_NONE 的 UTF-16LE 字节串)并解码。
+ * @returns {string} 下载目录,失败返回空串
+ */
+function readRegLocalPathW() {
+ try {
+ const result = spawnSync('reg', ['query', REG_KEY, '/v', 'LocalPathW'], {
+ encoding: 'utf8',
+ windowsHide: true,
+ timeout: 5000
+ })
+ if (!result || result.status !== 0 || !result.stdout) return ''
+ const line = result.stdout
+ .split(/\r?\n/)
+ .find((item) => item.trim().startsWith('LocalPathW'))
+ if (!line) return ''
+
+ // 形如:LocalPathW REG_NONE 43003A005C00...
+ const match = line.match(/REG_NONE\s+([0-9A-Fa-f\s]+)$/)
+ if (match) {
+ return decodeRegHexPath(match[1])
+ }
+
+ // 有些版本可能退化为 REG_SZ
+ const plain = line.match(/REG_SZ\s+(.+)$/)
+ return plain ? plain[1].trim() : ''
+ } catch {
+ return ''
+ }
+}
+
+/**
+ * 定位 IDMan.exe。
+ * @returns {{ exePath: string, source: 'registry' | 'fallback' | 'path' | 'none' }}
+ */
+function resolveIdmExe() {
+ const fromRegistry = readRegString('ExePath')
+ if (fromRegistry && fs.existsSync(fromRegistry)) {
+ return { exePath: fromRegistry, source: 'registry' }
+ }
+
+ for (const candidate of FALLBACK_PATHS) {
+ if (fs.existsSync(candidate)) {
+ return { exePath: candidate, source: 'fallback' }
+ }
+ }
+
+ try {
+ const result = spawnSync('where', ['IDMan.exe'], {
+ encoding: 'utf8',
+ windowsHide: true,
+ timeout: 5000
+ })
+ if (result && result.status === 0 && result.stdout) {
+ const first = result.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean)[0]
+ if (first && fs.existsSync(first)) {
+ return { exePath: first, source: 'path' }
+ }
+ }
+ } catch {
+ // 忽略,继续走兜底
+ }
+
+ return { exePath: '', source: 'none' }
+}
+
+/**
+ * 规范化目录路径:去掉末尾多余的反斜杠,但保留盘符根(如 `D:\`)。
+ * @param {string} dir 目录
+ * @returns {string} 规范化后的目录
+ */
+function normalizeDir(dir) {
+ let value = String(dir || '').trim()
+ if (!value) return ''
+ // 统一成反斜杠
+ value = value.replace(/\//g, '\\')
+ // 反复去掉末尾反斜杠,除非只剩盘符根
+ while (value.length > 3 && value.endsWith('\\')) {
+ value = value.slice(0, -1)
+ }
+ return value
+}
+
+/**
+ * 解析默认下载目录:注册表 → 用户 Downloads。
+ * @returns {{ saveDir: string, source: 'registry' | 'default' }}
+ */
+function resolveDefaultSaveDir() {
+ const fromRegistry = normalizeDir(readRegLocalPathW())
+ if (fromRegistry) {
+ return { saveDir: fromRegistry, source: 'registry' }
+ }
+ return { saveDir: normalizeDir(path.join(os.homedir(), 'Downloads')), source: 'default' }
+}
+
+/**
+ * 把链接交给 IDM。
+ *
+ * 判定逻辑(依据 2026-12-03 在本机的实测):
+ *
+ * 实测背景:本机 IDM 主实例早在 14:39:06 就已由用户启动并常驻。
+ * 在这个前提下调用 `IDMan.exe /d <假域名> /n`,新进程 24ms spawn、178ms 以 exit 0 退出。
+ * 这与「单实例程序把命令转发给常驻实例后自行退出」的行为一致。
+ *
+ * 因此:
+ * - exit 0 = 启动器把命令交出去了,但**没有证据表明任务真的入了队列**
+ * (实测该假域名始终没出现在 IDM 队列和 UrlHistory 里,大概率是域名无法解析);
+ * - exit 非 0 = 可以确定失败(参数错误、进程起不来);
+ * - 窗口内未退出 = 进程还在跑,按已提交处理。
+ *
+ * 返回值语义是「已提交给 IDM 启动器」,不是「下载已开始」,所以成功时带 unverified 标记。
+ *
+ * @param {object} options 参数
+ * @param {string} options.url 下载链接(必填)
+ * @param {string} [options.saveDir] 保存目录
+ * @param {string} [options.fileName] 保存文件名
+ * @param {boolean} [options.queueOnly] 是否只加入队列(/a)
+ * @param {string[]} [options.args] 已构造好的参数(传入则忽略上面三项)
+ * @param {string} [options.exePath] 指定可执行文件(仅用于测试,正常不传)
+ * @returns {Promise<{ ok: boolean, error?: string, exePath?: string, args?: string[], unverified?: boolean }>}
+ */
+function sendToIdm(options = {}) {
+ return new Promise((resolve) => {
+ const url = String(options.url || '').trim()
+ if (!url) {
+ resolve({ ok: false, error: '链接为空' })
+ return
+ }
+
+ const resolved = String(options.exePath || '').trim()
+ ? { exePath: String(options.exePath).trim(), source: 'override' }
+ : resolveIdmExe()
+ const { exePath, source } = resolved
+ if (!exePath) {
+ resolve({
+ ok: false,
+ error: '未找到 IDM(IDMan.exe)。请确认已安装 Internet Download Manager。',
+ detail: { source }
+ })
+ return
+ }
+
+ let args = Array.isArray(options.args) ? options.args : null
+ if (!args) {
+ const { buildIdmArgs } = require('./url-parse')
+ try {
+ args = buildIdmArgs({
+ url,
+ saveDir: options.saveDir,
+ fileName: options.fileName,
+ queueOnly: options.queueOnly
+ })
+ } catch (error) {
+ resolve({ ok: false, error: '构造 IDM 参数失败: ' + error.message })
+ return
+ }
+ }
+
+ let child
+ try {
+ child = spawn(exePath, args, {
+ detached: true,
+ stdio: 'ignore',
+ windowsHide: true
+ })
+ } catch (error) {
+ resolve({
+ ok: false,
+ error: '启动 IDM 失败: ' + (error && error.message ? error.message : String(error)),
+ exePath,
+ args
+ })
+ return
+ }
+
+ let settled = false
+ const finish = (payload) => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ resolve(payload)
+ }
+
+ // 等待窗口内没有退出:按已提交处理,但标记为未确证
+ // 注意:这个定时器不能 unref,否则在空闲的事件循环里进程可能先退出、Promise 永不结算
+ const timer = setTimeout(() => {
+ finish({ ok: true, unverified: true, exePath, args })
+ }, EXIT_WINDOW_MS)
+
+ child.once('error', (error) => {
+ const message = error && error.code === 'ENOENT'
+ ? 'IDM 可执行文件不存在: ' + exePath
+ : '启动 IDM 失败: ' + (error && error.message ? error.message : String(error))
+ finish({ ok: false, error: message, exePath, args })
+ })
+
+ child.once('exit', (code, signal) => {
+ if (code === 0) {
+ // 启动器正常退出:只能说明它没崩,任务是否入队无法从此判断
+ finish({ ok: true, unverified: true, exePath, args })
+ return
+ }
+ const detail = code === null ? 'signal ' + signal : 'exit code ' + code
+ finish({
+ ok: false,
+ error: 'IDM 退出异常(' + detail + '),任务很可能未提交',
+ exePath,
+ args
+ })
+ })
+
+ if (typeof child.unref === 'function') {
+ child.unref()
+ }
+ })
+}
+
+/**
+ * 一次拿到环境信息,供界面展示。
+ * @returns {{
+ * idmFound: boolean,
+ * exePath: string,
+ * exeSource: string,
+ * saveDir: string,
+ * saveDirSource: string
+ * }}
+ */
+function getEnvironment() {
+ const exe = resolveIdmExe()
+ const dir = resolveDefaultSaveDir()
+ return {
+ idmFound: Boolean(exe.exePath),
+ exePath: exe.exePath,
+ exeSource: exe.source,
+ saveDir: dir.saveDir,
+ saveDirSource: dir.source
+ }
+}
+
+module.exports = {
+ REG_KEY,
+ EXIT_WINDOW_MS,
+ FALLBACK_PATHS,
+ decodeRegHexPath,
+ normalizeDir,
+ readRegString,
+ readRegLocalPathW,
+ resolveIdmExe,
+ resolveDefaultSaveDir,
+ sendToIdm,
+ getEnvironment
+}
diff --git a/plugins/link-to-idm/lib/url-parse.js b/plugins/link-to-idm/lib/url-parse.js
new file mode 100644
index 000000000..55396aa4e
--- /dev/null
+++ b/plugins/link-to-idm/lib/url-parse.js
@@ -0,0 +1,388 @@
+'use strict'
+
+/**
+ * 纯函数集合:链接识别、文件名推断、IDM 参数构造。
+ *
+ * 本文件不依赖 electron / fs / child_process,也不做任何 IO,
+ * 因此可以在 Node 里直接跑单元测试(见 test/url-parse.test.js)。
+ */
+
+/**
+ * 从一段文本中抓出第一个 http(s) 链接。
+ *
+ * 排除空白、引号、尖括号、反引号,以及中日韩标点/全角符号/弯引号/破折号,
+ * 这样「https://a.com/x.zip,谢谢」只会取到链接本身。
+ * 中文汉字(\u4e00-\u9fff)不排除,因为有些站点的链接里直接含中文。
+ */
+const URL_PATTERN = /https?:\/\/[^\s"'<>`\u3000-\u303f\uff00-\uffef\u2018\u2019\u201c\u201d\u2013\u2014]+/i
+
+/** 文件名主体最大长度(含扩展名),超过后截断 */
+const MAX_FILE_NAME_LENGTH = 120
+
+/** Windows 文件名非法字符 */
+const ILLEGAL_CHARS = /[\\/:*?"<>|\u0000-\u001f]/g
+
+/** Windows 保留设备名 */
+const RESERVED_NAMES = new Set([
+ 'con', 'prn', 'aux', 'nul',
+ 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9',
+ 'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9'
+])
+
+/** content-type 到扩展名的常见映射,仅用于界面提示 */
+const CONTENT_TYPE_EXT = {
+ 'application/zip': 'zip',
+ 'application/x-zip-compressed': 'zip',
+ 'application/x-rar-compressed': 'rar',
+ 'application/vnd.rar': 'rar',
+ 'application/x-7z-compressed': '7z',
+ 'application/pdf': 'pdf',
+ 'application/json': 'json',
+ 'application/xml': 'xml',
+ 'application/msword': 'doc',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
+ 'application/vnd.ms-excel': 'xls',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
+ 'application/vnd.ms-powerpoint': 'ppt',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
+ 'application/octet-stream': '',
+ 'text/plain': 'txt',
+ 'text/csv': 'csv',
+ 'text/html': 'html',
+ 'image/jpeg': 'jpg',
+ 'image/png': 'png',
+ 'image/gif': 'gif',
+ 'image/webp': 'webp',
+ 'audio/mpeg': 'mp3',
+ 'video/mp4': 'mp4',
+ 'video/x-matroska': 'mkv'
+}
+
+/**
+ * 去掉粘贴文本尾部常见的标点(中英文句号、逗号、引号、括号等)。
+ * 只有括号不配对时才去掉右括号,避免破坏 wikipedia/xxx_(yyy) 这类链接。
+ * @param {string} url 原始链接
+ * @returns {string} 清理后的链接
+ */
+function trimUrlTail(url) {
+ let result = String(url || '')
+ const trailingPunctuation =
+ /[.,;:!?'"\u3002\uff0c\uff1b\uff1a\uff01\uff1f\u3001\u3010\u3011\u300a\u300b\u300c\u300d\u2018\u2019\u201c\u201d]+$/
+ result = result.replace(trailingPunctuation, '')
+ // 全角括号和半角括号分别判断配对
+ const bracketPairs = [
+ { close: ')', open: '(' },
+ { close: '\uff09', open: '\uff08' },
+ { close: ']', open: '[' },
+ { close: '\u3011', open: '\u3010' }
+ ]
+ for (const pair of bracketPairs) {
+ while (result.endsWith(pair.close)) {
+ const open = result.split(pair.open).length - 1
+ const close = result.split(pair.close).length - 1
+ if (close > open) {
+ result = result.slice(0, -1)
+ } else {
+ break
+ }
+ }
+ }
+ return result
+}
+
+/**
+ * 从用户输入(可能是一整段文字)里提取第一个 http(s) 链接。
+ * @param {unknown} input 用户输入
+ * @returns {string} 链接,没有则返回空串
+ */
+function extractUrl(input) {
+ if (typeof input !== 'string') return ''
+ const match = input.match(URL_PATTERN)
+ if (!match) return ''
+ return trimUrlTail(match[0])
+}
+
+/**
+ * 校验并规范化链接。
+ *
+ * 无论输入是纯链接还是一整段文字,都先走 extractUrl 截取,
+ * 这样「https://a.com/x.zip,谢谢」里的中文标点不会被编码进 URL。
+ *
+ * @param {unknown} input 用户输入或单个链接
+ * @returns {{ ok: boolean, url: string, reason?: string }}
+ */
+function parseDownloadUrl(input) {
+ const candidate = extractUrl(typeof input === 'string' ? input : '')
+
+ if (!candidate) {
+ return { ok: false, url: '', reason: '没有找到 http/https 链接' }
+ }
+
+ let parsed
+ try {
+ parsed = new URL(candidate)
+ } catch {
+ return { ok: false, url: '', reason: '链接格式不正确' }
+ }
+
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ return { ok: false, url: '', reason: '只支持 http / https 链接' }
+ }
+ if (!parsed.hostname) {
+ return { ok: false, url: '', reason: '链接缺少域名' }
+ }
+
+ return { ok: true, url: parsed.href }
+}
+
+/**
+ * 安全解码 URI 片段,失败时原样返回。
+ * @param {string} value 待解码文本
+ * @returns {string}
+ */
+function decodeSafe(value) {
+ const text = String(value || '')
+ try {
+ return decodeURIComponent(text)
+ } catch {
+ return text
+ }
+}
+
+/**
+ * 把任意字符串清理成 Windows 可用的文件名。
+ * @param {string} name 原始名称
+ * @returns {string} 清理后的名称(可能为空串)
+ */
+function sanitizeFileName(name) {
+ let result = String(name || '')
+ .replace(ILLEGAL_CHARS, '_')
+ .replace(/\s+/g, ' ')
+ .trim()
+
+ // Windows 不允许文件名以点或空格结尾
+ result = result.replace(/[. ]+$/, '')
+
+ if (!result) return ''
+
+ const base = result.split('.')[0].toLowerCase()
+ if (RESERVED_NAMES.has(base)) {
+ result = '_' + result
+ }
+
+ return result
+}
+
+/**
+ * 拆分文件名与扩展名。
+ * @param {string} fileName 文件名
+ * @returns {{ base: string, ext: string }}
+ */
+function splitExtension(fileName) {
+ const text = String(fileName || '')
+ const index = text.lastIndexOf('.')
+ if (index <= 0 || index === text.length - 1) {
+ return { base: text, ext: '' }
+ }
+ const ext = text.slice(index + 1)
+ // 扩展名过长基本不是真扩展名(如 a.b.c.d 里的长串)
+ if (ext.length > 12 || !/^[A-Za-z0-9]+$/.test(ext)) {
+ return { base: text, ext: '' }
+ }
+ return { base: text.slice(0, index), ext }
+}
+
+/**
+ * 截断文件名,保留扩展名。
+ * @param {string} fileName 文件名
+ * @param {number} [maxLength] 最大长度
+ * @returns {string}
+ */
+function truncateFileName(fileName, maxLength = MAX_FILE_NAME_LENGTH) {
+ const text = String(fileName || '')
+ if (text.length <= maxLength) return text
+
+ const { base, ext } = splitExtension(text)
+ const suffix = ext ? '.' + ext : ''
+ const room = maxLength - suffix.length
+ if (room <= 0) {
+ return text.slice(0, maxLength)
+ }
+ return base.slice(0, room) + suffix
+}
+
+/**
+ * 从 content-disposition 头里取文件名。
+ * @param {string} header content-disposition 值
+ * @returns {string} 文件名,取不到返回空串
+ */
+function fileNameFromContentDisposition(header) {
+ const text = String(header || '')
+ if (!text) return ''
+
+ // filename*=UTF-8''xxx 优先
+ const extended = text.match(/filename\*\s*=\s*([^;]+)/i)
+ if (extended) {
+ let value = extended[1].trim()
+ const parts = value.split("''")
+ if (parts.length === 2) {
+ value = parts[1]
+ } else {
+ value = value.replace(/^[^']*'[^']*'/, '')
+ }
+ const decoded = decodeSafe(value.replace(/^"|"$/g, ''))
+ const cleaned = sanitizeFileName(decoded)
+ if (cleaned) return cleaned
+ }
+
+ const plain = text.match(/filename\s*=\s*([^;]+)/i)
+ if (plain) {
+ const decoded = decodeSafe(plain[1].trim().replace(/^"|"$/g, ''))
+ const cleaned = sanitizeFileName(decoded)
+ if (cleaned) return cleaned
+ }
+
+ return ''
+}
+
+/**
+ * 从链接里推断文件名。
+ *
+ * 路径最后一段优先;但如果路径末段没有扩展名(如 /download?filename=setup.exe),
+ * 而查询参数里给出了带扩展名的文件名,则采用查询参数里的名字。
+ *
+ * @param {string} url 已校验的链接
+ * @returns {{ fileName: string, source: 'path' | 'query' | 'none' }}
+ */
+function fileNameFromUrl(url) {
+ let parsed
+ try {
+ parsed = new URL(url)
+ } catch {
+ return { fileName: '', source: 'none' }
+ }
+
+ let pathName = ''
+ const segments = parsed.pathname.split('/').filter(Boolean)
+ if (segments.length > 0) {
+ const raw = decodeSafe(segments[segments.length - 1])
+ pathName = sanitizeFileName(raw)
+ }
+
+ // 路径末段已经是像样的文件名,直接用它
+ if (pathName && looksLikeFileName(pathName)) {
+ return { fileName: truncateFileName(pathName), source: 'path' }
+ }
+
+ // 有些下载站把文件名放在查询参数里
+ for (const key of ['filename', 'file', 'name', 'download', 'fname']) {
+ const value = parsed.searchParams.get(key)
+ if (!value) continue
+ const cleaned = sanitizeFileName(decodeSafe(value))
+ if (cleaned && looksLikeFileName(cleaned)) {
+ return { fileName: truncateFileName(cleaned), source: 'query' }
+ }
+ }
+
+ if (pathName) {
+ return { fileName: truncateFileName(pathName), source: 'path' }
+ }
+
+ return { fileName: '', source: 'none' }
+}
+
+/**
+ * 根据 content-type 猜扩展名。
+ * @param {string} contentType content-type 头
+ * @returns {string} 扩展名(不含点),猜不到返回空串
+ */
+function extensionFromContentType(contentType) {
+ const value = String(contentType || '').split(';')[0].trim().toLowerCase()
+ if (!value) return ''
+ if (Object.prototype.hasOwnProperty.call(CONTENT_TYPE_EXT, value)) {
+ return CONTENT_TYPE_EXT[value]
+ }
+ return ''
+}
+
+/**
+ * 生成默认文件名(时间戳),不猜扩展名。
+ * @param {Date} [now] 当前时间
+ * @returns {string}
+ */
+function buildTimestampFileName(now = new Date()) {
+ const pad = (value) => String(value).padStart(2, '0')
+ const stamp = [
+ now.getFullYear(),
+ pad(now.getMonth() + 1),
+ pad(now.getDate())
+ ].join('') + '_' + [pad(now.getHours()), pad(now.getMinutes()), pad(now.getSeconds())].join('')
+ return 'download_' + stamp
+}
+
+/**
+ * 判断名称是否看起来像文件名(有扩展名)。
+ * @param {string} name 名称
+ * @returns {boolean}
+ */
+function looksLikeFileName(name) {
+ const { base, ext } = splitExtension(String(name || ''))
+ return Boolean(base) && Boolean(ext)
+}
+
+/**
+ * 构造 IDMan.exe 的参数数组。
+ *
+ * 参考 IDM 官方命令行:IDMan.exe /d URL [/p 目录] [/f 文件名] [/q] [/h] [/n] [/a]
+ * 这里固定加 /n(静默),不传 /q(不关闭用户的 IDM)。
+ *
+ * @param {{ url: string, saveDir?: string, fileName?: string, queueOnly?: boolean }} options 参数
+ * @returns {string[]} argv 数组(不含可执行文件本身)
+ * @throws {TypeError} url 为空时抛出
+ */
+function buildIdmArgs(options = {}) {
+ const url = String(options.url || '')
+ if (!url) {
+ throw new TypeError('buildIdmArgs: url 不能为空')
+ }
+
+ const args = ['/d', url]
+
+ const saveDir = String(options.saveDir || '').trim().replace(/\//g, '\\')
+ if (saveDir) {
+ // 去掉末尾反斜杠,但保留盘符根 D:\
+ const normalized = saveDir.length > 3 ? saveDir.replace(/\\+$/, '') : saveDir
+ args.push('/p', normalized)
+ }
+
+ const fileName = String(options.fileName || '').trim()
+ if (fileName) {
+ args.push('/f', fileName)
+ }
+
+ args.push('/n')
+
+ if (options.queueOnly) {
+ args.push('/a')
+ }
+
+ return args
+}
+
+module.exports = {
+ MAX_FILE_NAME_LENGTH,
+ URL_PATTERN,
+ extractUrl,
+ parseDownloadUrl,
+ trimUrlTail,
+ decodeSafe,
+ sanitizeFileName,
+ splitExtension,
+ truncateFileName,
+ fileNameFromContentDisposition,
+ fileNameFromUrl,
+ extensionFromContentType,
+ buildTimestampFileName,
+ looksLikeFileName,
+ buildIdmArgs
+}
diff --git a/plugins/link-to-idm/logo.png b/plugins/link-to-idm/logo.png
new file mode 100644
index 000000000..094eccfc2
Binary files /dev/null and b/plugins/link-to-idm/logo.png differ
diff --git a/plugins/link-to-idm/plugin.json b/plugins/link-to-idm/plugin.json
new file mode 100644
index 000000000..096ec6953
--- /dev/null
+++ b/plugins/link-to-idm/plugin.json
@@ -0,0 +1,36 @@
+{
+ "name": "link-to-idm",
+ "title": "链接转 IDM 下载",
+ "description": "粘贴下载链接,自动识别文件名并交给 Internet Download Manager 下载",
+ "version": "1.0.0",
+ "author": "qixin",
+ "platform": "win32",
+ "main": "index.html",
+ "preload": "preload.js",
+ "logo": "logo.png",
+ "features": [
+ {
+ "code": "send-to-idm",
+ "explain": "用 IDM 下载该链接",
+ "icon": "logo.png",
+ "mainPush": true,
+ "cmds": [
+ {
+ "type": "regex",
+ "label": "用 IDM 下载",
+ "match": "/https?:\\/\\/[^\\s\"'<>`\\u3000-\\u303f\\uff00-\\uffef]+/i",
+ "minLength": 10
+ }
+ ]
+ },
+ {
+ "code": "open-panel",
+ "explain": "打开链接转 IDM 面板",
+ "icon": "logo.png",
+ "cmds": ["链接转IDM", "IDM下载", "link to idm"]
+ }
+ ],
+ "pluginSetting": {
+ "single": true
+ }
+}
diff --git a/plugins/link-to-idm/preload.js b/plugins/link-to-idm/preload.js
new file mode 100644
index 000000000..51e65bc8e
--- /dev/null
+++ b/plugins/link-to-idm/preload.js
@@ -0,0 +1,677 @@
+'use strict'
+
+/**
+ * 链接转 IDM 下载 —— preload
+ *
+ * 运行在插件页面的 preload 上下文(contextIsolation: false / sandbox: false),
+ * 因此可以直接 require Node 模块,并把能力挂到 window 上供 index.js 调用。
+ */
+
+const http = require('node:http')
+const https = require('node:https')
+const fs = require('node:fs')
+
+const urlParse = require('./lib/url-parse')
+const idm = require('./lib/idm')
+
+/** Electron 渲染进程模块,preload 里可直接拿到剪贴板能力 */
+let electronClipboard = null
+try {
+ const electron = require('electron')
+ electronClipboard = electron.clipboard || null
+} catch {
+ electronClipboard = null
+}
+
+const STORAGE_KEY_SETTINGS = 'link-to-idm:settings'
+const STORAGE_KEY_PENDING = 'link-to-idm:pending'
+
+const DEFAULT_SETTINGS = {
+ saveDir: '',
+ autoSend: true,
+ queueOnly: false,
+ probeHeaders: true
+}
+
+const USER_AGENT =
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36'
+
+/** 上一次发送记录,用于 30 秒内重复发送提示 */
+let lastSent = { url: '', fileName: '', at: 0 }
+
+/** 等待处理的项目(由 onPluginEnter 写入,界面读取) */
+let pending = null
+
+/** 界面注册的待处理变更回调 */
+const pendingListeners = new Set()
+
+/**
+ * 取宿主 API,未就绪时返回 null(用于可选能力)。
+ * @returns {object | null}
+ */
+function tryZtools() {
+ return window.ztools || null
+}
+
+/**
+ * 读取设置。
+ * @returns {{ saveDir: string, autoSend: boolean, queueOnly: boolean, probeHeaders: boolean }}
+ */
+function getSettings() {
+ const host = tryZtools()
+ let stored = null
+ try {
+ stored = host ? host.dbStorage.getItem(STORAGE_KEY_SETTINGS) : null
+ } catch {
+ stored = null
+ }
+ if (!stored || typeof stored !== 'object') {
+ return { ...DEFAULT_SETTINGS }
+ }
+ return {
+ saveDir: typeof stored.saveDir === 'string' ? stored.saveDir : DEFAULT_SETTINGS.saveDir,
+ autoSend: typeof stored.autoSend === 'boolean' ? stored.autoSend : DEFAULT_SETTINGS.autoSend,
+ queueOnly: typeof stored.queueOnly === 'boolean' ? stored.queueOnly : DEFAULT_SETTINGS.queueOnly,
+ probeHeaders: typeof stored.probeHeaders === 'boolean'
+ ? stored.probeHeaders
+ : DEFAULT_SETTINGS.probeHeaders
+ }
+}
+
+/**
+ * 保存设置。
+ * @param {Partial} patch 需要修改的字段
+ * @returns {{ saveDir: string, autoSend: boolean, queueOnly: boolean, probeHeaders: boolean }}
+ */
+function saveSettings(patch = {}) {
+ const next = { ...getSettings() }
+ if (typeof patch.saveDir === 'string') next.saveDir = patch.saveDir
+ if (typeof patch.autoSend === 'boolean') next.autoSend = patch.autoSend
+ if (typeof patch.queueOnly === 'boolean') next.queueOnly = patch.queueOnly
+ if (typeof patch.probeHeaders === 'boolean') next.probeHeaders = patch.probeHeaders
+
+ const host = tryZtools()
+ try {
+ if (host) host.dbStorage.setItem(STORAGE_KEY_SETTINGS, next)
+ } catch (error) {
+ console.warn('[link-to-idm] 保存设置失败:', error)
+ }
+ return next
+}
+
+/**
+ * 实际使用的保存目录:用户设置优先,否则取 IDM 默认目录。
+ * @returns {{ saveDir: string, source: 'settings' | 'registry' | 'default' }}
+ */
+function resolveSaveDir() {
+ const settings = getSettings()
+ if (settings.saveDir) {
+ return { saveDir: settings.saveDir, source: 'settings' }
+ }
+ const fallback = idm.resolveDefaultSaveDir()
+ return { saveDir: fallback.saveDir, source: fallback.source }
+}
+
+/**
+ * 通过 HEAD 请求读取 content-disposition / content-type,用于补全文件名。
+ * 只做最多 3 次跳转,5 秒超时;任何失败都静默返回空结果。
+ *
+ * @param {string} url 链接
+ * @returns {Promise<{ fileName: string, contentType: string, contentLength: number }>}
+ */
+function probeHeaders(url, redirectCount = 0) {
+ return new Promise((resolve) => {
+ const empty = { fileName: '', contentType: '', contentLength: 0 }
+ let target
+ try {
+ target = new URL(url)
+ } catch {
+ resolve(empty)
+ return
+ }
+
+ const client = target.protocol === 'http:' ? http : https
+ let request
+ try {
+ request = client.request(
+ target,
+ {
+ method: 'HEAD',
+ timeout: 5000,
+ headers: {
+ 'User-Agent': USER_AGENT,
+ Accept: '*/*'
+ }
+ },
+ (response) => {
+ const status = response.statusCode || 0
+
+ // 跟随跳转
+ if (status >= 300 && status < 400 && response.headers.location && redirectCount < 3) {
+ response.resume()
+ let nextUrl
+ try {
+ nextUrl = new URL(response.headers.location, target).href
+ } catch {
+ resolve(empty)
+ return
+ }
+ probeHeaders(nextUrl, redirectCount + 1).then(resolve)
+ return
+ }
+
+ const headers = response.headers || {}
+ const fileName = urlParse.fileNameFromContentDisposition(headers['content-disposition'])
+ const contentType = String(headers['content-type'] || '')
+ const contentLength = Number(headers['content-length'] || 0)
+
+ response.resume()
+ resolve({
+ fileName,
+ contentType,
+ contentLength: Number.isFinite(contentLength) ? contentLength : 0
+ })
+ }
+ )
+ } catch {
+ resolve(empty)
+ return
+ }
+
+ request.on('timeout', () => {
+ request.destroy()
+ resolve(empty)
+ })
+ request.on('error', () => resolve(empty))
+ request.end()
+ })
+}
+
+/**
+ * 分析一段输入,得到下载信息。
+ *
+ * @param {unknown} input 用户输入
+ * @param {{ probe?: boolean }} [options] probe 是否允许发 HEAD 请求
+ * @returns {Promise<{
+ * ok: boolean,
+ * reason?: string,
+ * url: string,
+ * fileName: string,
+ * extension: string,
+ * nameSource: 'path' | 'query' | 'header' | 'timestamp' | 'none',
+ * contentLength: number,
+ * host: string
+ * }>}
+ */
+async function analyze(input, options = {}) {
+ const parsed = urlParse.parseDownloadUrl(input)
+ if (!parsed.ok) {
+ return {
+ ok: false,
+ reason: parsed.reason,
+ url: '',
+ fileName: '',
+ extension: '',
+ nameSource: 'none',
+ contentLength: 0,
+ host: ''
+ }
+ }
+
+ const url = parsed.url
+ let host = ''
+ try {
+ host = new URL(url).host
+ } catch {
+ host = ''
+ }
+
+ const fromUrl = urlParse.fileNameFromUrl(url)
+ let fileName = fromUrl.fileName
+ let nameSource = fromUrl.source
+ let contentLength = 0
+
+ const needProbe = options.probe !== false && (!fileName || !urlParse.looksLikeFileName(fileName))
+ if (needProbe) {
+ const probe = await probeHeaders(url)
+ contentLength = probe.contentLength
+ if (probe.fileName) {
+ fileName = probe.fileName
+ nameSource = 'header'
+ } else if (fileName && !urlParse.looksLikeFileName(fileName)) {
+ const ext = urlParse.extensionFromContentType(probe.contentType)
+ if (ext) {
+ fileName = fileName + '.' + ext
+ nameSource = fromUrl.source === 'none' ? 'header' : fromUrl.source
+ }
+ }
+ }
+
+ if (!fileName) {
+ fileName = urlParse.buildTimestampFileName()
+ nameSource = 'timestamp'
+ }
+
+ fileName = urlParse.truncateFileName(urlParse.sanitizeFileName(fileName) || fileName)
+ const { ext } = urlParse.splitExtension(fileName)
+
+ return {
+ ok: true,
+ url,
+ fileName,
+ extension: ext,
+ nameSource,
+ contentLength,
+ host
+ }
+}
+
+/**
+ * 把一条下载任务发送给 IDM。
+ *
+ * @param {{ url: string, fileName?: string, saveDir?: string, queueOnly?: boolean }} task 任务
+ * @returns {Promise<{ ok: boolean, error?: string, fileName?: string, saveDir?: string, exePath?: string, duplicate?: boolean }>}
+ */
+async function send(task = {}) {
+ const settings = getSettings()
+ const target = resolveSaveDir()
+ const saveDir = typeof task.saveDir === 'string' && task.saveDir.trim()
+ ? task.saveDir.trim()
+ : target.saveDir
+
+ const parsed = urlParse.parseDownloadUrl(task.url)
+ if (!parsed.ok) {
+ return { ok: false, error: parsed.reason }
+ }
+
+ const fileName = urlParse.truncateFileName(
+ urlParse.sanitizeFileName(task.fileName || '') || urlParse.buildTimestampFileName()
+ )
+
+ if (!saveDir) {
+ return { ok: false, error: '未设置保存目录' }
+ }
+ if (!fs.existsSync(saveDir)) {
+ return { ok: false, error: '保存目录不存在: ' + saveDir }
+ }
+
+ const now = Date.now()
+ if (lastSent.url === parsed.url && lastSent.fileName === fileName && now - lastSent.at < 30000) {
+ return {
+ ok: false,
+ duplicate: true,
+ error: '30 秒内已经发送过同一个任务,请勿重复操作',
+ fileName,
+ saveDir
+ }
+ }
+
+ const queueOnly = typeof task.queueOnly === 'boolean' ? task.queueOnly : settings.queueOnly
+ const result = await idm.sendToIdm({
+ url: parsed.url,
+ saveDir,
+ fileName,
+ queueOnly
+ })
+
+ if (result.ok) {
+ lastSent = { url: parsed.url, fileName, at: now }
+ }
+
+ return {
+ ok: result.ok,
+ error: result.error,
+ unverified: Boolean(result.unverified),
+ fileName,
+ saveDir,
+ exePath: result.exePath
+ }
+}
+
+/**
+ * 记录一条待处理任务并通知界面。
+ * @param {object} item 任务
+ * @returns {void}
+ */
+function setPending(item) {
+ pending = item
+ const host = tryZtools()
+ try {
+ if (host) host.dbStorage.setItem(STORAGE_KEY_PENDING, item)
+ } catch {
+ // 忽略存储失败,内存里仍可用
+ }
+ for (const listener of pendingListeners) {
+ try {
+ listener(item)
+ } catch (error) {
+ console.warn('[link-to-idm] pending 回调异常:', error)
+ }
+ }
+}
+
+/**
+ * 读取待处理任务。
+ * @returns {object | null}
+ */
+function getPending() {
+ if (pending) return pending
+ const host = tryZtools()
+ try {
+ const stored = host ? host.dbStorage.getItem(STORAGE_KEY_PENDING) : null
+ if (stored && typeof stored === 'object') {
+ pending = stored
+ return stored
+ }
+ } catch {
+ // 忽略
+ }
+ return null
+}
+
+/**
+ * 清空待处理任务。
+ * @returns {void}
+ */
+function clearPending() {
+ pending = null
+ const host = tryZtools()
+ try {
+ if (host) host.dbStorage.removeItem(STORAGE_KEY_PENDING)
+ } catch {
+ // 忽略
+ }
+}
+
+/**
+ * 处理一次「进入插件」:解析输入,按设置决定是否立即发送。
+ *
+ * 注意:从搜索栏 mainPush 结果进入时,宿主会把选中项放在 action.option 里,
+ * 并把 from 置为 "main"。此时用户已经在搜索结果里做过选择,不能再自动发送一次,
+ * 否则会重复提交给 IDM。
+ *
+ * @param {{ code?: string, type?: string, payload?: unknown, from?: string, option?: object }} action
+ * 宿主传入的进入参数
+ * @returns {Promise