diff --git a/plugins/s3-downloader/.npmrc b/plugins/s3-downloader/.npmrc new file mode 100644 index 000000000..214c29d13 --- /dev/null +++ b/plugins/s3-downloader/.npmrc @@ -0,0 +1 @@ +registry=https://registry.npmjs.org/ diff --git a/plugins/s3-downloader/CHANGELOG.md b/plugins/s3-downloader/CHANGELOG.md new file mode 100644 index 000000000..75420af1a --- /dev/null +++ b/plugins/s3-downloader/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +## 0.1.1 - 2026-12-02 + +- 首次上架插件市场 +- 支持凭证管理、桶管理、object key 前缀 +- 支持下载进度、速度、取消和最近下载记录 +- 首发适配 macOS Apple Silicon + +## 0.1.0 - 2026-11-30 + +- 初始实现 S3 / S3 兼容对象存储下载 diff --git a/plugins/s3-downloader/README.md b/plugins/s3-downloader/README.md new file mode 100644 index 000000000..6d6698a32 --- /dev/null +++ b/plugins/s3-downloader/README.md @@ -0,0 +1,38 @@ +# S3 下载 + +管理 S3 凭证与桶,下载时只需要选择凭证、桶并填写 object key。 + +![S3 下载](./screenshot.png) + +## 功能 + +- 凭证管理:Endpoint、Region、Access Key、Secret Key、Session Token、匿名桶、Path Style +- 桶管理:常用 bucket 和可选 object key 前缀 +- 下载时只需选择凭证和桶,填写 object key +- 大文件流式下载、进度、速度、取消 +- 重名文件自动追加序号 +- 下载完成后打开所在文件夹 +- 最近下载记录 + +## 使用 + +1. 在 ZTools 输入 `S3管理` +2. 添加凭证和桶 +3. 输入 `S3下载` +4. 选择凭证和桶,填写 object key,点击下载 + +桶配置里的前缀会自动拼到 object key 前面。例如前缀是 `docs`,输入 `report.pdf`,实际下载 `docs/report.pdf`。 + +## 支持平台 + +当前版本仅支持 **macOS Apple Silicon(arm64)**。 + +Intel Mac 和 Windows 版本需要分别构建对应的原生下载组件,后续会单独发布。 + +## 凭证安全 + +凭证保存在 ZTools 的本地插件数据库中,当前版本未加密。请不要在共用电脑上保存生产密钥。 + +## 源码 + +https://github.com/fagao-ai/ztools-s3-downloader diff --git a/plugins/s3-downloader/app.js b/plugins/s3-downloader/app.js new file mode 100644 index 000000000..e39974ade --- /dev/null +++ b/plugins/s3-downloader/app.js @@ -0,0 +1,1264 @@ +'use strict' + +const STORAGE_KEY = 's3-downloader.profiles.v1' +const MAX_RECENT = 6 + +const ztools = window.ztools || { + getPath: () => 'Downloads', + showOpenDialog: () => undefined, + shellShowItemInFolder: () => undefined, + copyText: () => false, + onPluginEnter: () => undefined, + onPluginOut: () => undefined +} + +const storage = + ztools.dbStorage || + { + getItem(key) { + try { + const value = localStorage.getItem(key) + return value ? JSON.parse(value) : null + } catch { + return null + } + }, + setItem(key, value) { + localStorage.setItem(key, JSON.stringify(value)) + }, + removeItem(key) { + localStorage.removeItem(key) + } + } + +const $ = (id) => document.getElementById(id) +const els = { + runtimeSummary: $('runtime-summary'), + setupWarning: $('setup-warning'), + setupWarningText: $('setup-warning-text'), + goManage: $('go-manage'), + credentialSelect: $('credential-select'), + bucketSelect: $('bucket-select'), + selectionSummary: $('selection-summary'), + objectKey: $('object-key'), + keyPreview: $('key-preview'), + downloadBtn: $('download-btn'), + testBtn: $('test-btn'), + downloadError: $('download-error'), + progressCard: $('progress-card'), + progressName: $('progress-name'), + progressPhase: $('progress-phase'), + progressTrack: $('progress-track'), + progressBar: $('progress-bar'), + progressBytes: $('progress-bytes'), + progressPercent: $('progress-percent'), + cancelBtn: $('cancel-btn'), + resultCard: $('result-card'), + resultTitle: $('result-title'), + resultMeta: $('result-meta'), + resultPath: $('result-path'), + openFolderBtn: $('open-folder-btn'), + copyPathBtn: $('copy-path-btn'), + recentCard: $('recent-card'), + recentList: $('recent-list'), + clearRecentBtn: $('clear-recent-btn'), + credentialCount: $('credential-count'), + bucketCount: $('bucket-count'), + manageCredentials: $('manage-credentials'), + manageBuckets: $('manage-buckets'), + credentialList: $('credential-list'), + bucketList: $('bucket-list'), + credentialEmpty: $('credential-empty'), + bucketEmpty: $('bucket-empty'), + addCredentialBtn: $('add-credential-btn'), + addBucketBtn: $('add-bucket-btn'), + downloadDir: $('download-dir'), + chooseDirBtn: $('choose-dir-btn'), + resetDirBtn: $('reset-dir-btn'), + toast: $('toast'), + modal: $('modal'), + modalTitle: $('modal-title'), + modalClose: $('modal-close'), + credentialForm: $('credential-form'), + credentialId: $('credential-id'), + credentialName: $('credential-name'), + credentialEndpoint: $('credential-endpoint'), + credentialRegion: $('credential-region'), + credentialAccessKey: $('credential-access-key'), + credentialSecretKey: $('credential-secret-key'), + credentialSessionToken: $('credential-session-token'), + credentialAnonymous: $('credential-anonymous'), + credentialPathStyle: $('credential-path-style'), + credentialFormError: $('credential-form-error'), + toggleSecretBtn: $('toggle-secret-btn'), + bucketForm: $('bucket-form'), + bucketId: $('bucket-id'), + bucketName: $('bucket-name'), + bucketValue: $('bucket-value'), + bucketPrefix: $('bucket-prefix'), + bucketFormError: $('bucket-form-error') +} + +const state = { + store: loadStore(), + runtime: getRuntime(), + downloading: false, + cancelled: false, + editingCredentialId: null, + editingBucketId: null, + pathStyleTouched: false, + lastResult: null, + toastTimer: null +} + +function createDefaultStore() { + return { + version: 1, + credentials: [], + buckets: [], + downloadDir: '', + lastCredentialId: '', + lastBucketId: '', + recent: [] + } +} + +function normalizeStore(raw) { + const input = raw && typeof raw === 'object' ? raw : {} + const store = createDefaultStore() + store.downloadDir = typeof input.downloadDir === 'string' ? input.downloadDir : '' + store.lastCredentialId = typeof input.lastCredentialId === 'string' ? input.lastCredentialId : '' + store.lastBucketId = typeof input.lastBucketId === 'string' ? input.lastBucketId : '' + + if (Array.isArray(input.credentials)) { + store.credentials = input.credentials + .filter((item) => item && typeof item === 'object') + .map((item) => ({ + id: String(item.id || uid()), + name: String(item.name || '未命名凭证'), + endpoint: String(item.endpoint || ''), + region: String(item.region || 'us-east-1'), + accessKeyId: String(item.accessKeyId || ''), + secretAccessKey: String(item.secretAccessKey || ''), + sessionToken: String(item.sessionToken || ''), + anonymous: Boolean(item.anonymous), + forcePathStyle: item.forcePathStyle !== false, + createdAt: item.createdAt || null, + updatedAt: item.updatedAt || null + })) + } + + if (Array.isArray(input.buckets)) { + store.buckets = input.buckets + .filter((item) => item && typeof item === 'object') + .map((item) => ({ + id: String(item.id || uid()), + name: String(item.name || item.bucket || '未命名桶'), + bucket: String(item.bucket || ''), + prefix: normalizePrefix(item.prefix), + createdAt: item.createdAt || null, + updatedAt: item.updatedAt || null + })) + .filter((item) => item.bucket) + } + + if (Array.isArray(input.recent)) { + store.recent = input.recent + .filter((item) => item && typeof item === 'object' && item.path) + .slice(0, MAX_RECENT) + .map((item) => ({ + path: String(item.path), + filename: String(item.filename || filenameFromPath(item.path)), + key: String(item.key || ''), + bucketName: String(item.bucketName || ''), + credentialName: String(item.credentialName || ''), + bytes: Number(item.bytes) || 0, + at: Number(item.at) || Date.now() + })) + } + + return store +} + +function loadStore() { + try { + return normalizeStore(storage.getItem(STORAGE_KEY)) + } catch (error) { + console.error('[S3 Downloader] load store failed:', error) + return createDefaultStore() + } +} + +function saveStore() { + try { + storage.setItem(STORAGE_KEY, state.store) + } catch (error) { + console.error('[S3 Downloader] save store failed:', error) + showToast(`配置保存失败:${error.message}`, true) + } +} + +function getRuntime() { + try { + if (!window.s3Downloader || typeof window.s3Downloader.runtime !== 'function') { + return { + available: false, + error: 'preload.js 未注入,下载组件无法加载。', + platform: 'unknown', + arch: 'unknown' + } + } + return window.s3Downloader.runtime() + } catch (error) { + return { + available: false, + error: error instanceof Error ? error.message : String(error), + platform: 'unknown', + arch: 'unknown' + } + } +} + +function uid() { + if (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function') { + return globalThis.crypto.randomUUID() + } + return `id-${Date.now()}-${Math.random().toString(16).slice(2)}` +} + +function init() { + bindEvents() + renderAll() + + if (typeof ztools.onPluginEnter === 'function') { + ztools.onPluginEnter((action) => { + if (action && action.code === 'manage') { + switchView('manage') + } else { + switchView('download') + } + renderAll() + }) + } + + window.addEventListener('beforeunload', () => { + if (state.downloading) window.s3Downloader?.cancel?.() + }) + + if (!state.runtime.available) { + console.error('[S3 Downloader] runtime unavailable:', state.runtime.error) + showToast('下载组件加载失败,请重新安装插件', true) + } + + setTimeout(() => els.objectKey.focus(), 60) +} + +function bindEvents() { + document.querySelectorAll('[data-view]').forEach((button) => { + button.addEventListener('click', () => switchView(button.dataset.view)) + }) + + document.querySelectorAll('[data-manage]').forEach((button) => { + button.addEventListener('click', () => setManageTab(button.dataset.manage)) + }) + + els.goManage.addEventListener('click', () => switchView('manage')) + els.addCredentialBtn.addEventListener('click', () => openCredentialModal()) + els.addBucketBtn.addEventListener('click', () => openBucketModal()) + document.querySelectorAll('[data-open-credential]').forEach((button) => { + button.addEventListener('click', () => openCredentialModal()) + }) + document.querySelectorAll('[data-open-bucket]').forEach((button) => { + button.addEventListener('click', () => openBucketModal()) + }) + + els.credentialForm.addEventListener('submit', submitCredential) + els.bucketForm.addEventListener('submit', submitBucket) + els.modalClose.addEventListener('click', closeModal) + document.querySelectorAll('[data-close-modal]').forEach((node) => { + node.addEventListener('click', closeModal) + }) + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape' && !els.modal.classList.contains('hidden')) closeModal() + }) + + els.credentialAnonymous.addEventListener('change', updateCredentialAuthFields) + els.toggleSecretBtn.addEventListener('click', () => { + const showing = els.credentialSecretKey.type === 'text' + els.credentialSecretKey.type = showing ? 'password' : 'text' + els.toggleSecretBtn.textContent = showing ? '显示' : '隐藏' + }) + els.credentialPathStyle.addEventListener('change', () => { + state.pathStyleTouched = true + }) + els.credentialEndpoint.addEventListener('input', () => { + if (state.editingCredentialId || state.pathStyleTouched) return + const endpoint = els.credentialEndpoint.value.trim() + if (!endpoint) return + els.credentialPathStyle.checked = !/amazonaws\.com/i.test(endpoint) + }) + + els.credentialList.addEventListener('click', (event) => { + const button = event.target.closest('button[data-action]') + if (!button) return + if (button.dataset.action === 'edit-credential') openCredentialModal(button.dataset.id) + if (button.dataset.action === 'delete-credential') deleteCredential(button.dataset.id) + }) + + els.bucketList.addEventListener('click', (event) => { + const button = event.target.closest('button[data-action]') + if (!button) return + if (button.dataset.action === 'edit-bucket') openBucketModal(button.dataset.id) + if (button.dataset.action === 'delete-bucket') deleteBucket(button.dataset.id) + }) + + els.credentialSelect.addEventListener('change', () => { + state.store.lastCredentialId = els.credentialSelect.value + saveStore() + updateSelectionSummary() + }) + els.bucketSelect.addEventListener('change', () => { + state.store.lastBucketId = els.bucketSelect.value + saveStore() + updateSelectionSummary() + }) + + els.objectKey.addEventListener('input', updateKeyPreview) + els.objectKey.addEventListener('keydown', (event) => { + if (event.key === 'Enter' && !els.downloadBtn.disabled) { + event.preventDefault() + startDownload() + } + }) + + els.downloadBtn.addEventListener('click', startDownload) + els.cancelBtn.addEventListener('click', cancelDownload) + els.testBtn.addEventListener('click', testConnection) + els.openFolderBtn.addEventListener('click', () => { + if (state.lastResult) openFolder(state.lastResult.path) + }) + els.copyPathBtn.addEventListener('click', () => { + if (!state.lastResult) return + try { + ztools.copyText(state.lastResult.path) + showToast('路径已复制') + } catch (error) { + showToast(`复制失败:${error.message}`, true) + } + }) + + els.chooseDirBtn.addEventListener('click', chooseDownloadDir) + els.resetDirBtn.addEventListener('click', () => { + state.store.downloadDir = '' + saveStore() + renderDownloadDir() + showToast('已恢复系统下载目录') + }) + + els.clearRecentBtn.addEventListener('click', () => { + state.store.recent = [] + saveStore() + renderRecent() + showToast('已清空最近下载') + }) +} + +function switchView(view) { + document.querySelectorAll('.view').forEach((node) => { + node.classList.toggle('is-active', node.id === `view-${view}`) + }) + document.querySelectorAll('[data-view]').forEach((button) => { + button.classList.toggle('is-active', button.dataset.view === view) + }) + if (view === 'manage') renderManage() + if (view === 'download') setTimeout(() => els.objectKey.focus(), 30) +} + +function setManageTab(tab) { + document.querySelectorAll('[data-manage]').forEach((button) => { + const active = button.dataset.manage === tab + button.classList.toggle('is-active', active) + button.setAttribute('aria-selected', String(active)) + }) + els.manageCredentials.classList.toggle('hidden', tab !== 'credentials') + els.manageBuckets.classList.toggle('hidden', tab !== 'buckets') +} + +function renderAll() { + renderRuntimeSummary() + renderSelectors() + renderManage() + renderDownloadDir() + renderRecent() + updateDownloadState() +} + +function renderManage() { + renderCredentialList() + renderBucketList() + renderDownloadDir() +} + +function renderRuntimeSummary() { + els.runtimeSummary.textContent = state.runtime.available + ? 'S3 / S3 兼容存储下载器' + : '下载组件不可用' +} + +function renderSelectors() { + let changed = false + const credentialResult = setSelectOptions( + els.credentialSelect, + state.store.credentials, + '暂无凭证', + state.store.lastCredentialId, + (credential) => `${credential.name} · ${credentialEndpointLabel(credential)}` + ) + if (credentialResult.changed) { + state.store.lastCredentialId = credentialResult.selectedId + changed = true + } + + const bucketResult = setSelectOptions( + els.bucketSelect, + state.store.buckets, + '暂无桶', + state.store.lastBucketId, + (bucket) => + `${bucket.name}${bucket.name === bucket.bucket ? '' : ` · ${bucket.bucket}`}${ + bucket.prefix ? ` · ${bucket.prefix}/` : '' + }` + ) + if (bucketResult.changed) { + state.store.lastBucketId = bucketResult.selectedId + changed = true + } + + if (changed) saveStore() + updateSelectionSummary() + updateKeyPreview() +} + +function setSelectOptions(select, items, placeholder, selectedId, label) { + select.textContent = '' + if (!items.length) { + const option = document.createElement('option') + option.value = '' + option.textContent = placeholder + option.disabled = true + option.selected = true + select.append(option) + return { selectedId: '', changed: Boolean(selectedId) } + } + + const hasSelected = items.some((item) => item.id === selectedId) + const nextSelectedId = hasSelected ? selectedId : items[0].id + + for (const item of items) { + const option = document.createElement('option') + option.value = item.id + option.textContent = label(item) + option.selected = item.id === nextSelectedId + select.append(option) + } + + return { selectedId: nextSelectedId, changed: nextSelectedId !== selectedId } +} + +function getSelectedCredential() { + return ( + state.store.credentials.find((item) => item.id === state.store.lastCredentialId) || + state.store.credentials[0] || + null + ) +} + +function getSelectedBucket() { + return ( + state.store.buckets.find((item) => item.id === state.store.lastBucketId) || + state.store.buckets[0] || + null + ) +} + +function updateSelectionSummary() { + const credential = getSelectedCredential() + const bucket = getSelectedBucket() + els.selectionSummary.textContent = '' + + if (!credential || !bucket) { + appendSummaryChip('状态', '请先添加凭证和桶') + return + } + + appendSummaryChip('Endpoint', credential.endpoint || `AWS 默认 · ${credential.region}`) + appendSummaryChip('Region', credential.region) + appendSummaryChip('Bucket', bucket.bucket) + appendSummaryChip('前缀', bucket.prefix ? `${bucket.prefix}/` : '根目录') + if (credential.anonymous) appendSummaryChip('认证', '匿名') +} + +function appendSummaryChip(label, value) { + const chip = document.createElement('span') + chip.className = 'summary-chip' + const strong = document.createElement('strong') + strong.textContent = label + const text = document.createElement('span') + text.textContent = value + chip.append(strong, text) + els.selectionSummary.append(chip) +} + +function updateKeyPreview() { + const bucket = getSelectedBucket() + const rawKey = els.objectKey.value.trim().replace(/\\/g, '/').replace(/^\/+/, '') + if (!bucket) { + els.keyPreview.textContent = '等待选择桶' + return + } + + const prefix = bucket.prefix ? `${bucket.prefix}/` : '' + if (!rawKey) { + els.keyPreview.textContent = prefix ? `${prefix}…` : '等待填写' + return + } + const alreadyPrefixed = + bucket.prefix && (rawKey === bucket.prefix || rawKey.startsWith(`${bucket.prefix}/`)) + els.keyPreview.textContent = alreadyPrefixed ? rawKey : `${prefix}${rawKey}` +} + +function updateDownloadState() { + const hasCredentials = state.store.credentials.length > 0 + const hasBuckets = state.store.buckets.length > 0 + const ready = state.runtime.available && hasCredentials && hasBuckets + const canDownload = ready && !state.downloading + + els.credentialSelect.disabled = state.downloading || !hasCredentials + els.bucketSelect.disabled = state.downloading || !hasBuckets + els.objectKey.disabled = !ready || state.downloading + els.downloadBtn.disabled = !canDownload + els.testBtn.disabled = !ready || state.downloading + els.downloadBtn.textContent = state.downloading ? '下载中…' : '下载' + els.cancelBtn.disabled = !state.downloading + + if (ready) { + els.setupWarning.classList.add('hidden') + return + } + + els.setupWarning.classList.remove('hidden') + if (!state.runtime.available) { + els.setupWarningText.textContent = '下载组件加载失败,请重新安装插件。' + } else if (!hasCredentials && !hasBuckets) { + els.setupWarningText.textContent = '先添加至少一个凭证和一个桶,再开始下载。' + } else if (!hasCredentials) { + els.setupWarningText.textContent = '还缺一个凭证,请先配置 Endpoint、Region 和访问密钥。' + } else { + els.setupWarningText.textContent = '还缺一个桶,请先把常用 bucket 保存下来。' + } +} + +function renderCredentialList() { + els.credentialList.textContent = '' + els.credentialCount.textContent = String(state.store.credentials.length) + const empty = state.store.credentials.length === 0 + els.credentialEmpty.classList.toggle('hidden', !empty) + if (empty) return + + for (const credential of state.store.credentials) { + const card = document.createElement('article') + card.className = 'profile-card' + + const main = document.createElement('div') + main.className = 'profile-main' + + const title = document.createElement('div') + title.className = 'profile-title' + const heading = document.createElement('h3') + heading.textContent = credential.name + title.append(heading) + if (credential.anonymous) title.append(createBadge('匿名')) + if (credential.sessionToken) title.append(createBadge('STS')) + + const endpoint = document.createElement('p') + endpoint.className = 'profile-sub' + endpoint.textContent = `${credential.endpoint || 'AWS 默认 Endpoint'} · ${credential.region}` + endpoint.title = endpoint.textContent + + const meta = document.createElement('div') + meta.className = 'profile-meta' + meta.append( + createMeta(`AK ${maskAccessKey(credential.accessKeyId)}`), + createMeta(credential.secretAccessKey ? 'Secret 已保存' : 'Secret 未保存'), + createMeta(credential.forcePathStyle ? 'Path Style' : 'Virtual Host') + ) + + main.append(title, endpoint, meta) + + const actions = document.createElement('div') + actions.className = 'profile-actions' + actions.append( + createActionButton('编辑', 'edit-credential', credential.id, 'btn btn-ghost btn-small'), + createActionButton('删除', 'delete-credential', credential.id, 'btn btn-danger-ghost btn-small') + ) + + card.append(main, actions) + els.credentialList.append(card) + } +} + +function renderBucketList() { + els.bucketList.textContent = '' + els.bucketCount.textContent = String(state.store.buckets.length) + const empty = state.store.buckets.length === 0 + els.bucketEmpty.classList.toggle('hidden', !empty) + if (empty) return + + for (const bucket of state.store.buckets) { + const card = document.createElement('article') + card.className = 'profile-card' + + const main = document.createElement('div') + main.className = 'profile-main' + + const title = document.createElement('div') + title.className = 'profile-title' + const heading = document.createElement('h3') + heading.textContent = bucket.name + title.append(heading) + if (bucket.prefix) title.append(createBadge('带前缀')) + + const bucketName = document.createElement('p') + bucketName.className = 'profile-sub' + bucketName.textContent = bucket.bucket + + const meta = document.createElement('div') + meta.className = 'profile-meta' + meta.append(createMeta(`前缀:${bucket.prefix ? `${bucket.prefix}/` : '根目录'}`)) + + main.append(title, bucketName, meta) + + const actions = document.createElement('div') + actions.className = 'profile-actions' + actions.append( + createActionButton('编辑', 'edit-bucket', bucket.id, 'btn btn-ghost btn-small'), + createActionButton('删除', 'delete-bucket', bucket.id, 'btn btn-danger-ghost btn-small') + ) + + card.append(main, actions) + els.bucketList.append(card) + } +} + +function createBadge(text) { + const badge = document.createElement('span') + badge.className = 'badge' + badge.textContent = text + return badge +} + +function createMeta(text) { + const node = document.createElement('span') + node.textContent = text + return node +} + +function createActionButton(label, action, id, className) { + const button = document.createElement('button') + button.type = 'button' + button.className = className + button.dataset.action = action + button.dataset.id = id + button.textContent = label + return button +} + +function renderRecent() { + els.recentList.textContent = '' + const recent = state.store.recent + els.recentCard.classList.toggle('hidden', recent.length === 0) + if (!recent.length) return + + for (const item of recent) { + const row = document.createElement('div') + row.className = 'recent-item' + row.title = item.path + row.tabIndex = 0 + row.setAttribute('role', 'button') + + const icon = document.createElement('div') + icon.className = 'recent-icon' + icon.textContent = '↓' + + const copy = document.createElement('div') + copy.className = 'recent-copy' + const name = document.createElement('strong') + name.textContent = item.filename + const meta = document.createElement('span') + meta.textContent = [item.bucketName, formatBytes(item.bytes), formatTime(item.at)] + .filter(Boolean) + .join(' · ') + copy.append(name, meta) + + const open = document.createElement('span') + open.className = 'recent-open' + open.textContent = '↗' + + row.append(icon, copy, open) + row.addEventListener('click', () => openFolder(item.path)) + row.addEventListener('keydown', (event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + openFolder(item.path) + } + }) + els.recentList.append(row) + } +} + +function renderDownloadDir() { + let defaultDir = '' + try { + defaultDir = ztools.getPath?.('downloads') || '' + } catch { + defaultDir = '' + } + els.downloadDir.value = state.store.downloadDir || defaultDir + els.downloadDir.title = state.store.downloadDir ? '自定义下载目录' : '系统下载目录(默认)' + els.resetDirBtn.disabled = !state.store.downloadDir +} + +function openCredentialModal(id) { + state.editingCredentialId = id || null + state.pathStyleTouched = false + els.credentialForm.reset() + els.credentialFormError.classList.add('hidden') + els.credentialFormError.textContent = '' + els.credentialSecretKey.type = 'password' + els.toggleSecretBtn.textContent = '显示' + + if (id) { + const credential = state.store.credentials.find((item) => item.id === id) + if (!credential) return + els.credentialId.value = credential.id + els.credentialName.value = credential.name + els.credentialEndpoint.value = credential.endpoint + els.credentialRegion.value = credential.region + els.credentialAccessKey.value = credential.accessKeyId + els.credentialSecretKey.value = credential.secretAccessKey + els.credentialSessionToken.value = credential.sessionToken + els.credentialAnonymous.checked = credential.anonymous + els.credentialPathStyle.checked = credential.forcePathStyle + els.modalTitle.textContent = '编辑凭证' + } else { + els.credentialId.value = '' + els.credentialName.value = '' + els.credentialEndpoint.value = 'https://s3.us-east-1.amazonaws.com' + els.credentialRegion.value = 'us-east-1' + els.credentialAccessKey.value = '' + els.credentialSecretKey.value = '' + els.credentialSessionToken.value = '' + els.credentialAnonymous.checked = false + els.credentialPathStyle.checked = false + els.modalTitle.textContent = '新增凭证' + } + + updateCredentialAuthFields() + showModal(els.credentialForm) + setTimeout(() => els.credentialName.focus(), 30) +} + +function openBucketModal(id) { + state.editingBucketId = id || null + els.bucketForm.reset() + els.bucketFormError.classList.add('hidden') + els.bucketFormError.textContent = '' + + if (id) { + const bucket = state.store.buckets.find((item) => item.id === id) + if (!bucket) return + els.bucketId.value = bucket.id + els.bucketName.value = bucket.name + els.bucketValue.value = bucket.bucket + els.bucketPrefix.value = bucket.prefix + els.modalTitle.textContent = '编辑桶' + } else { + els.bucketId.value = '' + els.bucketName.value = '' + els.bucketValue.value = '' + els.bucketPrefix.value = '' + els.modalTitle.textContent = '新增桶' + } + + showModal(els.bucketForm) + setTimeout(() => els.bucketName.focus(), 30) +} + +function showModal(form) { + els.credentialForm.classList.toggle('hidden', form !== els.credentialForm) + els.bucketForm.classList.toggle('hidden', form !== els.bucketForm) + els.modal.classList.remove('hidden') +} + +function closeModal() { + els.modal.classList.add('hidden') + state.editingCredentialId = null + state.editingBucketId = null +} + +function updateCredentialAuthFields() { + const anonymous = els.credentialAnonymous.checked + els.credentialAccessKey.disabled = anonymous + els.credentialSecretKey.disabled = anonymous + els.credentialSessionToken.disabled = anonymous + els.toggleSecretBtn.disabled = anonymous +} + +function submitCredential(event) { + event.preventDefault() + try { + const editingId = els.credentialId.value || null + const existing = editingId + ? state.store.credentials.find((item) => item.id === editingId) + : null + const name = els.credentialName.value.trim() + const region = els.credentialRegion.value.trim() || 'us-east-1' + let endpoint = els.credentialEndpoint.value.trim().replace(/\/+$/, '') + const anonymous = els.credentialAnonymous.checked + const accessKeyId = els.credentialAccessKey.value.trim() + const secretInput = els.credentialSecretKey.value.trim() + const secretAccessKey = secretInput || (existing ? existing.secretAccessKey : '') + const sessionToken = els.credentialSessionToken.value.trim() + + if (!name) throw new Error('请填写凭证显示名称') + const duplicate = state.store.credentials.some( + (item) => item.id !== editingId && item.name.toLowerCase() === name.toLowerCase() + ) + if (duplicate) throw new Error('已经有同名凭证了') + + if (endpoint && !/^[a-z][a-z0-9+.-]*:\/\//i.test(endpoint)) { + endpoint = `https://${endpoint}` + } + if (endpoint) { + let parsed + try { + parsed = new URL(endpoint) + } catch { + throw new Error('Endpoint 格式不正确') + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + throw new Error('Endpoint 只支持 http:// 或 https://') + } + } + + if (!anonymous && !accessKeyId) throw new Error('请填写 Access Key ID') + if (!anonymous && !secretAccessKey) throw new Error('请填写 Secret Access Key') + + const now = new Date().toISOString() + const credential = { + id: editingId || uid(), + name, + endpoint, + region, + accessKeyId, + secretAccessKey, + sessionToken, + anonymous, + forcePathStyle: els.credentialPathStyle.checked, + createdAt: existing?.createdAt || now, + updatedAt: now + } + + if (editingId) { + const index = state.store.credentials.findIndex((item) => item.id === editingId) + state.store.credentials[index] = credential + } else { + state.store.credentials.push(credential) + } + + state.store.lastCredentialId = credential.id + saveStore() + renderAll() + closeModal() + showToast(editingId ? '凭证已更新' : '凭证已添加') + } catch (error) { + showFormError(els.credentialFormError, error.message) + } +} + +function submitBucket(event) { + event.preventDefault() + try { + const editingId = els.bucketId.value || null + const existing = editingId ? state.store.buckets.find((item) => item.id === editingId) : null + const bucketValue = els.bucketValue.value.trim() + const name = els.bucketName.value.trim() || bucketValue + const prefix = normalizePrefix(els.bucketPrefix.value) + + if (!name) throw new Error('请填写显示名称') + if (!bucketValue) throw new Error('请填写 Bucket 名称') + if (/[\s/]/.test(bucketValue)) throw new Error('Bucket 名称不能包含空格或斜杠') + + const duplicate = state.store.buckets.some( + (item) => item.id !== editingId && item.name.toLowerCase() === name.toLowerCase() + ) + if (duplicate) throw new Error('已经有同名桶了') + + const now = new Date().toISOString() + const bucket = { + id: editingId || uid(), + name, + bucket: bucketValue, + prefix, + createdAt: existing?.createdAt || now, + updatedAt: now + } + + if (editingId) { + const index = state.store.buckets.findIndex((item) => item.id === editingId) + state.store.buckets[index] = bucket + } else { + state.store.buckets.push(bucket) + } + + state.store.lastBucketId = bucket.id + saveStore() + renderAll() + closeModal() + showToast(editingId ? '桶已更新' : '桶已添加') + } catch (error) { + showFormError(els.bucketFormError, error.message) + } +} + +function deleteCredential(id) { + const credential = state.store.credentials.find((item) => item.id === id) + if (!credential) return + if (!window.confirm(`删除凭证“${credential.name}”?已保存的密钥会一并删除。`)) return + + state.store.credentials = state.store.credentials.filter((item) => item.id !== id) + if (state.store.lastCredentialId === id) { + state.store.lastCredentialId = state.store.credentials[0]?.id || '' + } + saveStore() + renderAll() + showToast('凭证已删除') +} + +function deleteBucket(id) { + const bucket = state.store.buckets.find((item) => item.id === id) + if (!bucket) return + if (!window.confirm(`删除桶“${bucket.name}”?`)) return + + state.store.buckets = state.store.buckets.filter((item) => item.id !== id) + if (state.store.lastBucketId === id) { + state.store.lastBucketId = state.store.buckets[0]?.id || '' + } + saveStore() + renderAll() + showToast('桶已删除') +} + +async function startDownload() { + if (state.downloading) return + if (!state.runtime.available) { + showToast('下载组件不可用,无法下载', true) + return + } + + const credential = getSelectedCredential() + const bucket = getSelectedBucket() + const key = els.objectKey.value.trim() + + if (!credential || !bucket) { + showToast('请先配置凭证和桶', true) + switchView('manage') + return + } + if (!key) { + showToast('请填写 object key', true) + els.objectKey.focus() + return + } + + state.downloading = true + state.cancelled = false + state.lastResult = null + els.downloadError.classList.add('hidden') + els.downloadError.textContent = '' + els.resultCard.classList.add('hidden') + els.progressCard.classList.remove('hidden') + els.progressName.textContent = key.split('/').pop() || key + els.progressPhase.textContent = '正在读取对象信息…' + els.progressTrack.classList.add('is-indeterminate') + els.progressBar.style.width = '0%' + els.progressBytes.textContent = '已下载 0 B' + els.progressPercent.textContent = '—' + updateDownloadState() + els.progressCard.scrollIntoView({ block: 'nearest', behavior: 'smooth' }) + + try { + const result = await window.s3Downloader.download( + { + credential, + bucket, + key, + downloadDir: state.store.downloadDir + }, + setProgress + ) + + if (state.cancelled) return + state.lastResult = result + els.progressCard.classList.add('hidden') + showResult(result, credential, bucket) + addRecent(result, credential, bucket) + els.objectKey.value = '' + updateKeyPreview() + showToast('下载完成') + } catch (error) { + els.progressCard.classList.add('hidden') + if (state.cancelled || /已取消/.test(error.message)) { + showToast('已取消下载') + } else { + showDownloadError(error.message) + } + } finally { + state.downloading = false + state.cancelled = false + updateDownloadState() + } +} + +function setProgress(progress) { + if (!state.downloading) return + + const phase = progress.phase + const loaded = Number(progress.loaded) || 0 + const total = progress.total == null ? null : Number(progress.total) + const percent = + progress.percent == null + ? total + ? Math.min(100, (loaded / total) * 100) + : null + : Number(progress.percent) + + if (phase === 'stat') { + els.progressPhase.textContent = '正在读取对象信息…' + els.progressTrack.classList.add('is-indeterminate') + } else if (phase === 'done') { + els.progressPhase.textContent = '下载完成' + els.progressTrack.classList.remove('is-indeterminate') + els.progressBar.style.width = '100%' + } else { + els.progressPhase.textContent = '正在下载' + if (percent == null) { + els.progressTrack.classList.add('is-indeterminate') + } else { + els.progressTrack.classList.remove('is-indeterminate') + els.progressBar.style.width = `${percent}%` + } + } + + if (total && total > 0) { + els.progressBytes.textContent = `已下载 ${formatBytes(loaded)} / ${formatBytes(total)}` + } else { + els.progressBytes.textContent = `已下载 ${formatBytes(loaded)}` + } + + const rate = Number(progress.bytesPerSecond) > 0 ? formatRate(progress.bytesPerSecond) : '' + if (percent == null) { + els.progressPercent.textContent = rate || '—' + } else { + els.progressPercent.textContent = `${Math.round(percent)}%${rate ? ` · ${rate}` : ''}` + } +} + +function cancelDownload() { + if (!state.downloading) return + state.cancelled = true + els.cancelBtn.disabled = true + els.progressPhase.textContent = '正在取消…' + window.s3Downloader?.cancel?.() +} + +async function testConnection() { + const credential = getSelectedCredential() + const bucket = getSelectedBucket() + if (!credential || !bucket) { + showToast('请先配置凭证和桶', true) + return + } + if (!state.runtime.available) { + showToast('下载组件不可用', true) + return + } + + const originalText = els.testBtn.textContent + els.testBtn.disabled = true + els.testBtn.textContent = '测试中…' + els.downloadError.classList.add('hidden') + try { + const result = await window.s3Downloader.testConnection( + credential, + bucket, + els.objectKey.value.trim() + ) + if (result.mode === 'stat') { + showToast(`对象存在 · ${formatBytes(result.size)}`) + } else { + showToast('连接成功,List 权限正常') + } + } catch (error) { + showDownloadError(error.message) + } finally { + els.testBtn.disabled = state.downloading || !state.runtime.available + els.testBtn.textContent = originalText + } +} + +function showResult(result, credential, bucket) { + els.resultCard.classList.remove('hidden', 'is-error') + els.resultTitle.textContent = '下载完成' + els.resultMeta.textContent = `${formatBytes(result.bytes)} · ${credential.name} / ${bucket.name} · ${formatTime( + Date.now() + )}` + els.resultPath.textContent = result.path + els.resultPath.title = result.path +} + +function showDownloadError(message) { + els.downloadError.textContent = message || '下载失败' + els.downloadError.classList.remove('hidden') + els.downloadError.scrollIntoView({ block: 'nearest', behavior: 'smooth' }) +} + +function addRecent(result, credential, bucket) { + const item = { + path: result.path, + filename: result.filename, + key: result.key, + bucketName: bucket.name, + credentialName: credential.name, + bytes: result.bytes, + at: Date.now() + } + state.store.recent = [item, ...state.store.recent.filter((entry) => entry.path !== item.path)].slice( + 0, + MAX_RECENT + ) + saveStore() + renderRecent() +} + +function chooseDownloadDir() { + try { + const selected = ztools.showOpenDialog?.({ + title: '选择 S3 下载目录', + properties: ['openDirectory', 'createDirectory'] + }) + const directory = Array.isArray(selected) ? selected[0] : selected + if (!directory) return + state.store.downloadDir = directory + saveStore() + renderDownloadDir() + showToast('下载目录已更新') + } catch (error) { + showToast(`选择目录失败:${error.message}`, true) + } +} + +function openFolder(filePath) { + if (!filePath) return + try { + const result = ztools.shellShowItemInFolder?.(filePath) + if (result && result.success === false) { + showToast(result.error || '无法打开文件夹', true) + } + } catch (error) { + showToast(`无法打开文件夹:${error.message}`, true) + } +} + +function showFormError(element, message) { + element.textContent = message + element.classList.remove('hidden') +} + +function showToast(message, isError = false) { + if (!message) return + clearTimeout(state.toastTimer) + els.toast.textContent = message + els.toast.classList.toggle('is-error', isError) + els.toast.classList.remove('hidden') + state.toastTimer = setTimeout(() => { + els.toast.classList.add('hidden') + }, 2800) +} + +function normalizePrefix(value) { + return String(value || '') + .trim() + .replace(/\\/g, '/') + .replace(/^\/+|\/+$/g, '') +} + +function credentialEndpointLabel(credential) { + if (!credential.endpoint) return `AWS · ${credential.region}` + try { + return new URL(credential.endpoint).host + } catch { + return credential.endpoint + } +} + +function maskAccessKey(value) { + const key = String(value || '') + if (!key) return '未填写' + if (key.length <= 8) return '••••••••' + return `${key.slice(0, 4)}…${key.slice(-4)}` +} + +function filenameFromPath(filePath) { + return String(filePath || '').split(/[\\/]/).pop() || 'download' +} + +function formatBytes(value) { + const bytes = Number(value) + if (!Number.isFinite(bytes) || bytes < 0) return '—' + if (bytes === 0) return '0 B' + const units = ['B', 'KB', 'MB', 'GB', 'TB'] + let size = bytes + let index = 0 + while (size >= 1024 && index < units.length - 1) { + size /= 1024 + index += 1 + } + const rounded = index === 0 ? Math.round(size) : size >= 100 ? size.toFixed(0) : size.toFixed(1) + return `${rounded} ${units[index]}` +} + +function formatRate(value) { + const rate = Number(value) + if (!Number.isFinite(rate) || rate <= 0) return '' + return `${formatBytes(rate)}/s` +} + +function formatTime(value) { + try { + return new Intl.DateTimeFormat('zh-CN', { + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit' + }).format(new Date(value)) + } catch { + return '' + } +} + +if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', init, { once: true }) +} else { + init() +} diff --git a/plugins/s3-downloader/build-plugin.sh b/plugins/s3-downloader/build-plugin.sh new file mode 100755 index 000000000..dcf9ed004 --- /dev/null +++ b/plugins/s3-downloader/build-plugin.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -euo pipefail + +npm ci --omit=dev --no-audit --no-fund + +node - <<'NODE' +if (process.platform !== 'darwin' || process.arch !== 'arm64') { + throw new Error(`This release targets macOS Apple Silicon, got ${process.platform}/${process.arch}`) +} + +const { Operator } = require('opendal') +if (typeof Operator !== 'function') { + throw new Error('Native download binding is unavailable') +} + +console.log('Native download binding OK:', process.platform, process.arch) +NODE diff --git a/plugins/s3-downloader/index.html b/plugins/s3-downloader/index.html new file mode 100644 index 000000000..214a77a5b --- /dev/null +++ b/plugins/s3-downloader/index.html @@ -0,0 +1,303 @@ + + + + + + S3 下载 + + + +
+
+
+ +
+

S3 下载

+

S3 / S3 兼容存储下载器

+
+
+ +
+ +
+
+ + +
+
+
+

下载对象

+

选择凭证和桶,输入 object key 后直接保存到本地。

+
+
+ +
+ + +
+ +
+ +
+ + +
+ +
+

最终 key:等待填写

+ +
+ +
+ + + + + + +
+ +
+
+ + +
+ +
+
+
+

凭证

+

保存 Endpoint、Region 和访问密钥,下载时直接选择。

+
+ +
+
+ +
+ + + +
+
+
+

下载设置

+

不设置时保存到系统下载目录,重名文件会自动追加序号。

+
+
+
+ + + +
+

+ 凭证保存在 ZTools 的本地插件数据库中,当前版本未加密。请勿在共用电脑上保存生产密钥。 +

+
+ +
+
+ + +
+ + + + + + diff --git a/plugins/s3-downloader/lib/opendal-service.js b/plugins/s3-downloader/lib/opendal-service.js new file mode 100644 index 000000000..efeae34b9 --- /dev/null +++ b/plugins/s3-downloader/lib/opendal-service.js @@ -0,0 +1,416 @@ +'use strict' + +const fs = require('node:fs') +const fsp = require('node:fs/promises') +const os = require('node:os') +const path = require('node:path') +const { pipeline } = require('node:stream/promises') + +let Operator = null +let opendalVersion = null +let loadError = null + +try { + const opendal = require('opendal') + Operator = opendal.Operator + try { + opendalVersion = require('opendal/package.json').version + } catch { + opendalVersion = null + } +} catch (error) { + loadError = error +} + +function getRuntimeInfo() { + return { + available: Boolean(Operator), + version: opendalVersion, + error: loadError ? shortError(loadError) : null, + platform: process.platform, + arch: process.arch, + node: process.versions.node, + electron: process.versions.electron || null, + napi: process.versions.napi || null + } +} + +function shortError(error) { + const message = error instanceof Error ? error.message : String(error) + return message.length > 600 ? `${message.slice(0, 600)}…` : message +} + +function expandHome(input) { + const value = String(input || '').trim() + if (!value) return value + if (value === '~') return os.homedir() + if (value.startsWith('~/') || value.startsWith('~\\')) { + return path.join(os.homedir(), value.slice(2)) + } + return path.resolve(value) +} + +function normalizeObjectKey(prefix, key) { + const rawKey = String(key || '').trim() + if (!rawKey) throw new Error('请填写 object key') + if (/[\r\n]/.test(rawKey)) throw new Error('object key 不能包含换行符') + if (rawKey.endsWith('/')) throw new Error('object key 不能以 / 结尾,请填写具体文件') + + const cleanKey = rawKey.replace(/\\/g, '/').replace(/^\/+/, '') + const cleanPrefix = String(prefix || '') + .trim() + .replace(/\\/g, '/') + .replace(/^\/+|\/+$/g, '') + + if (!cleanPrefix) return cleanKey + if (cleanKey === cleanPrefix || cleanKey.startsWith(`${cleanPrefix}/`)) return cleanKey + return `${cleanPrefix}/${cleanKey}` +} + +function truncateUtf8(value, maxBytes) { + let output = '' + for (const char of value) { + if (Buffer.byteLength(output + char, 'utf8') > maxBytes) break + output += char + } + return output +} + +function sanitizeFilename(input) { + let name = String(input || '') + .replace(/\\/g, '/') + .split('/') + .pop() + .trim() + + name = name + .replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_') + .replace(/\s+/g, ' ') + .replace(/[. ]+$/g, '') + + if (!name || name === '.' || name === '..') name = 'download.bin' + if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(name)) { + name = `_${name}` + } + + if (Buffer.byteLength(name, 'utf8') > 200) { + const extension = path.extname(name) + const stem = extension ? name.slice(0, -extension.length) : name + const safeExtension = truncateUtf8(extension, 24) + name = `${truncateUtf8(stem, 200 - Buffer.byteLength(safeExtension, 'utf8'))}${safeExtension}` + } + + return name || 'download.bin' +} + +function filenameFromKey(objectKey) { + const normalized = String(objectKey || '').replace(/\\/g, '/') + const base = normalized.split('/').pop() + if (!base) throw new Error('无法从 object key 推断文件名') + return sanitizeFilename(base) +} + +async function exists(filePath) { + try { + await fsp.access(filePath) + return true + } catch { + return false + } +} + +async function resolveTargetPath(directory, filename) { + const targetDirectory = expandHome(directory) || path.join(os.homedir(), 'Downloads') + await fsp.mkdir(targetDirectory, { recursive: true }) + + const extension = path.extname(filename) + const stem = extension ? filename.slice(0, -extension.length) : filename + let candidate = path.join(targetDirectory, filename) + let index = 1 + + while (await exists(candidate)) { + candidate = path.join(targetDirectory, `${stem} (${index})${extension}`) + index += 1 + } + + return candidate +} + +function friendlyError(error, context = {}) { + const original = error instanceof Error ? error.message : String(error) + const message = original.toLowerCase() + + if (error && error.cancelled) return new Error('已取消下载') + if (message.includes('cancelled') || message.includes('canceled')) return new Error('已取消下载') + + if (message.includes('notfound') || message.includes('not found')) { + return new Error(context.objectKey ? `对象不存在:${context.objectKey}` : '对象不存在') + } + if ( + message.includes('permissiondenied') || + message.includes('accessdenied') || + message.includes('forbidden') || + message.includes('403') + ) { + return new Error('没有权限读取该对象,请检查凭证、桶名和 object key') + } + if ( + message.includes('invalidaccesskeyid') || + message.includes('signaturedoesnotmatch') || + message.includes('configinvalid') + ) { + return new Error('凭证、Region 或 Endpoint 不匹配') + } + if (message.includes('econnrefused')) { + return new Error('无法连接 Endpoint,请确认地址、端口和服务状态') + } + if (message.includes('enotfound') || message.includes('eai_again')) { + return new Error('Endpoint 域名解析失败,请检查网络或地址') + } + if (message.includes('timeout') || message.includes('timed out') || message.includes('etimedout')) { + return new Error('连接超时,请检查 Endpoint 和网络') + } + if (message.includes('certificate') || message.includes('ssl') || message.includes('tls')) { + return new Error('TLS 证书校验失败,请检查 Endpoint 协议') + } + if (message.includes('unsupported')) { + return new Error(`当前存储不支持该操作:${original}`) + } + + return new Error(`下载失败:${shortError(error)}`) +} + +class S3Downloader { + constructor() { + this._active = null + this._operatorCache = null + } + + _getOperator(credential, bucket) { + if (!Operator) { + throw new Error( + `OpenDAL 原生模块加载失败(${process.platform}/${process.arch}):${ + loadError ? shortError(loadError) : '未知错误' + }` + ) + } + + const bucketName = String(bucket && bucket.bucket ? bucket.bucket : '') + .trim() + .replace(/^\/+|\/+$/g, '') + if (!bucketName) throw new Error('请选择或配置桶') + if (!credential || !credential.name) throw new Error('请选择或配置凭证') + + const endpoint = String(credential.endpoint || '').trim().replace(/\/+$/, '') + if (endpoint) { + let parsed + try { + parsed = new URL(endpoint) + } catch { + throw new Error('Endpoint 格式不正确,需要包含 http:// 或 https://') + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + throw new Error('Endpoint 只支持 http:// 或 https://') + } + } + + const accessKeyId = String(credential.accessKeyId || '').trim() + const secretAccessKey = String(credential.secretAccessKey || '') + const sessionToken = String(credential.sessionToken || '').trim() + const anonymous = Boolean(credential.anonymous) + + if (!anonymous && (!accessKeyId || !secretAccessKey)) { + throw new Error('该凭证缺少 Access Key ID 或 Secret Access Key') + } + + const region = String(credential.region || 'us-east-1').trim() || 'us-east-1' + const forcePathStyle = credential.forcePathStyle !== false + const cacheKey = JSON.stringify({ + bucketName, + endpoint, + region, + accessKeyId, + secretAccessKey, + sessionToken, + anonymous, + forcePathStyle + }) + + if (this._operatorCache && this._operatorCache.key === cacheKey) { + return this._operatorCache.operator + } + + const options = { + bucket: bucketName, + region, + disable_config_load: 'true', + enable_virtual_host_style: forcePathStyle ? 'false' : 'true' + } + + if (endpoint) options.endpoint = endpoint + + if (anonymous) { + options.allow_anonymous = 'true' + options.skip_signature = 'true' + } else { + options.access_key_id = accessKeyId + options.secret_access_key = secretAccessKey + if (sessionToken) options.session_token = sessionToken + } + + const operator = new Operator('s3', options) + this._operatorCache = { key: cacheKey, operator } + return operator + } + + async testConnection(credential, bucket, key) { + try { + const operator = this._getOperator(credential, bucket) + const rawKey = String(key || '').trim() + + if (rawKey) { + const objectKey = normalizeObjectKey(bucket.prefix, rawKey) + const metadata = await operator.stat(objectKey) + return { + ok: true, + mode: 'stat', + key: objectKey, + size: metadata.contentLength == null ? null : Number(metadata.contentLength), + lastModified: metadata.lastModified || null + } + } + + await operator.check() + return { ok: true, mode: 'list' } + } catch (error) { + console.error('[S3 Downloader] testConnection failed:', error) + throw friendlyError(error, { objectKey: key }) + } + } + + async download(options, onProgress) { + if (this._active) throw new Error('已有下载任务正在进行') + + const { credential, bucket, key, downloadDir, defaultDir } = options || {} + const objectKey = normalizeObjectKey(bucket && bucket.prefix, key) + const filename = filenameFromKey(objectKey) + const targetPath = await resolveTargetPath(downloadDir || defaultDir, filename) + const tempPath = `${targetPath}.part-${process.pid}-${Date.now()}` + const task = { cancelled: false, source: null, output: null, tempPath, targetPath } + const emit = (payload) => { + if (typeof onProgress !== 'function') return + try { + onProgress(payload) + } catch (error) { + console.warn('[S3 Downloader] progress callback failed:', error) + } + } + + this._active = task + let committed = false + + try { + const operator = this._getOperator(credential, bucket) + emit({ phase: 'stat', loaded: 0, total: null, percent: null }) + + let total = null + try { + const metadata = await operator.stat(objectKey) + if (metadata.isDirectory()) { + throw new Error('该 object key 指向目录,请填写具体文件') + } + total = metadata.contentLength == null ? null : Number(metadata.contentLength) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + if (/notfound|not found/i.test(message)) throw error + console.warn('[S3 Downloader] stat failed, continue with reader:', error) + } + + if (task.cancelled) throw Object.assign(new Error('已取消下载'), { cancelled: true }) + + const reader = await operator.reader(objectKey) + if (task.cancelled) throw Object.assign(new Error('已取消下载'), { cancelled: true }) + + const source = reader.createReadStream() + const output = fs.createWriteStream(tempPath) + task.source = source + task.output = output + + let loaded = 0 + let lastEmitAt = 0 + const startedAt = Date.now() + + source.on('data', (chunk) => { + loaded += chunk.length + const now = Date.now() + if (now - lastEmitAt < 100) return + lastEmitAt = now + const elapsed = Math.max((now - startedAt) / 1000, 0.001) + emit({ + phase: 'download', + loaded, + total, + percent: total ? Math.min(100, (loaded / total) * 100) : null, + bytesPerSecond: loaded / elapsed + }) + }) + + await pipeline(source, output) + if (task.cancelled) throw Object.assign(new Error('已取消下载'), { cancelled: true }) + + await fsp.rename(tempPath, targetPath) + committed = true + emit({ + phase: 'done', + loaded, + total: total || loaded, + percent: 100, + bytesPerSecond: loaded / Math.max((Date.now() - startedAt) / 1000, 0.001) + }) + + return { + ok: true, + path: targetPath, + key: objectKey, + filename, + bytes: loaded + } + } catch (error) { + if (task.cancelled) throw new Error('已取消下载') + console.error('[S3 Downloader] download failed:', error) + throw friendlyError(error, { objectKey }) + } finally { + if (!committed) { + await fsp.unlink(tempPath).catch(() => {}) + } + if (this._active === task) this._active = null + } + } + + cancel() { + const task = this._active + if (!task) return false + + task.cancelled = true + try { + task.source?.destroy(Object.assign(new Error('已取消下载'), { cancelled: true })) + } catch (error) { + console.warn('[S3 Downloader] destroy source failed:', error) + } + try { + task.output?.destroy() + } catch (error) { + console.warn('[S3 Downloader] destroy output failed:', error) + } + return true + } +} + +module.exports = { + S3Downloader, + getRuntimeInfo, + normalizeObjectKey, + filenameFromKey, + sanitizeFilename, + friendlyError +} diff --git a/plugins/s3-downloader/logo.png b/plugins/s3-downloader/logo.png new file mode 100644 index 000000000..81042beba Binary files /dev/null and b/plugins/s3-downloader/logo.png differ diff --git a/plugins/s3-downloader/package-lock.json b/plugins/s3-downloader/package-lock.json new file mode 100644 index 000000000..c2373d38c --- /dev/null +++ b/plugins/s3-downloader/package-lock.json @@ -0,0 +1,174 @@ +{ + "name": "ztools-s3-downloader", + "version": "0.1.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ztools-s3-downloader", + "version": "0.1.1", + "dependencies": { + "opendal": "0.49.13" + } + }, + "node_modules/@opendal/lib-darwin-arm64": { + "version": "0.49.13", + "resolved": "https://registry.npmjs.org/@opendal/lib-darwin-arm64/-/lib-darwin-arm64-0.49.13.tgz", + "integrity": "sha512-G1RN7gSRq3giZ2sovG48p2zG1fECkicyw9QkWKNBWXtDHfqPM4Z1nLrVvKTxQAFZdhKzdyQyU5jgPVCirbHW4g==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@opendal/lib-darwin-x64": { + "version": "0.49.13", + "resolved": "https://registry.npmjs.org/@opendal/lib-darwin-x64/-/lib-darwin-x64-0.49.13.tgz", + "integrity": "sha512-2HbefZ/laVZlfwJceKhCBlM6GOTVjm6zjsgITIZE6xzJeUbRET0lTJeoTsTrzTwB2LRuLOlZ/uelm4aIZLtHqA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@opendal/lib-linux-arm64-gnu": { + "version": "0.49.13", + "resolved": "https://registry.npmjs.org/@opendal/lib-linux-arm64-gnu/-/lib-linux-arm64-gnu-0.49.13.tgz", + "integrity": "sha512-uTabu3o+c0+gbQD1AOy9YQfMBb65YOhxKVCHF1Ve3CEzud/nM4+izVZx5+JWmt1qsk4zu1mVsMVNk8kKY4DQ7A==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@opendal/lib-linux-arm64-musl": { + "version": "0.49.13", + "resolved": "https://registry.npmjs.org/@opendal/lib-linux-arm64-musl/-/lib-linux-arm64-musl-0.49.13.tgz", + "integrity": "sha512-tmK/tLW/aSFTwE6YPKlhri9LOnJafvxM4dDsevLVmZUnoOrBJae9LATLcim1nx1a2PaagcZYj0nrL0NSPRWMBA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@opendal/lib-linux-x64-gnu": { + "version": "0.49.13", + "resolved": "https://registry.npmjs.org/@opendal/lib-linux-x64-gnu/-/lib-linux-x64-gnu-0.49.13.tgz", + "integrity": "sha512-Q/+079Q8tSyIW5S9iCrwSr56NRMScHeio6HsioGbmiksb41HnUxdHXzDuSUz9b/jufxyFEiNh3ifMVLpa4Gfwg==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@opendal/lib-linux-x64-musl": { + "version": "0.49.13", + "resolved": "https://registry.npmjs.org/@opendal/lib-linux-x64-musl/-/lib-linux-x64-musl-0.49.13.tgz", + "integrity": "sha512-QK9NioYu8rXsw1ILpm/+S/FkSq9IK5IomE7SA9sP09OLHvJNydHKIhx+avVQMTIb4E40d+12Cq9F3FL3qo9wPw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@opendal/lib-win32-arm64-msvc": { + "version": "0.49.13", + "resolved": "https://registry.npmjs.org/@opendal/lib-win32-arm64-msvc/-/lib-win32-arm64-msvc-0.49.13.tgz", + "integrity": "sha512-eNV1I76iaJAvl8VUY3z+LxYMhkJT904wc2VCVP0OHMc3xUD+Ugp/50RNsWTzOnNd5W+oZv5eKGtm0GCggeDtrA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@opendal/lib-win32-x64-msvc": { + "version": "0.49.13", + "resolved": "https://registry.npmjs.org/@opendal/lib-win32-x64-msvc/-/lib-win32-x64-msvc-0.49.13.tgz", + "integrity": "sha512-AzBzm4xwraXOrnRY+oGhgy6/97xPoHTBAMsqUlXbsCFmPXW4sv6NKm6NTm6vQZuNw3wWrADOoPFJ+NKj5k/MQg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/opendal": { + "version": "0.49.13", + "resolved": "https://registry.npmjs.org/opendal/-/opendal-0.49.13.tgz", + "integrity": "sha512-9aqgQ4pGKP3ESPAxfKDk5JUE4X/la8SzQXSOZxBMSIIDleJOhT4jgOwjNGVLZ0TtJ/PQpGmVpm7LCncTiAlTHg==", + "license": "Apache-2.0", + "engines": { + "node": ">= 10" + }, + "optionalDependencies": { + "@opendal/lib-darwin-arm64": "0.49.13", + "@opendal/lib-darwin-x64": "0.49.13", + "@opendal/lib-linux-arm64-gnu": "0.49.13", + "@opendal/lib-linux-arm64-musl": "0.49.13", + "@opendal/lib-linux-x64-gnu": "0.49.13", + "@opendal/lib-linux-x64-musl": "0.49.13", + "@opendal/lib-win32-arm64-msvc": "0.49.13", + "@opendal/lib-win32-x64-msvc": "0.49.13" + } + } + } +} diff --git a/plugins/s3-downloader/package.json b/plugins/s3-downloader/package.json new file mode 100644 index 000000000..67ce5ceea --- /dev/null +++ b/plugins/s3-downloader/package.json @@ -0,0 +1,10 @@ +{ + "name": "ztools-s3-downloader", + "version": "0.1.1", + "private": true, + "description": "ZTools plugin: download objects from S3-compatible storage", + "type": "commonjs", + "dependencies": { + "opendal": "0.49.13" + } +} diff --git a/plugins/s3-downloader/plugin.json b/plugins/s3-downloader/plugin.json new file mode 100644 index 000000000..87ed54842 --- /dev/null +++ b/plugins/s3-downloader/plugin.json @@ -0,0 +1,27 @@ +{ + "name": "s3-downloader", + "title": "S3 下载", + "description": "管理 S3 凭证与桶,输入 object key 即可下载到本地(macOS Apple Silicon)", + "version": "0.1.1", + "author": "fagao-ai", + "homepage": "https://github.com/fagao-ai/ztools-s3-downloader", + "platform": ["darwin"], + "categories": ["development"], + "main": "index.html", + "preload": "preload.js", + "logo": "logo.png", + "features": [ + { + "code": "download", + "explain": "选择凭证和桶,输入 object key 下载文件", + "icon": "logo.png", + "cmds": ["s3", "S3下载", "s3下载", "S3 下载", "对象下载"] + }, + { + "code": "manage", + "explain": "管理 S3 凭证、桶与下载目录", + "icon": "logo.png", + "cmds": ["S3管理", "S3 管理", "s3设置", "S3设置", "S3 设置"] + } + ] +} diff --git a/plugins/s3-downloader/preload.js b/plugins/s3-downloader/preload.js new file mode 100644 index 000000000..a5385b6c4 --- /dev/null +++ b/plugins/s3-downloader/preload.js @@ -0,0 +1,17 @@ +'use strict' + +const os = require('node:os') +const { S3Downloader, getRuntimeInfo } = require('./lib/opendal-service') + +const downloader = new S3Downloader() + +window.s3Downloader = { + runtime: () => getRuntimeInfo(), + homeDir: () => os.homedir(), + download: (options, onProgress) => { + const downloads = window.ztools.getPath('downloads') + return downloader.download({ ...options, defaultDir: downloads }, onProgress) + }, + cancel: () => downloader.cancel(), + testConnection: (credential, bucket, key) => downloader.testConnection(credential, bucket, key) +} diff --git a/plugins/s3-downloader/screenshot.png b/plugins/s3-downloader/screenshot.png new file mode 100644 index 000000000..7f5cb2327 Binary files /dev/null and b/plugins/s3-downloader/screenshot.png differ diff --git a/plugins/s3-downloader/styles.css b/plugins/s3-downloader/styles.css new file mode 100644 index 000000000..82b65a4e3 --- /dev/null +++ b/plugins/s3-downloader/styles.css @@ -0,0 +1,1118 @@ +:root { + --bg: #f3f5f8; + --panel: #ffffff; + --panel-soft: #f8fafc; + --text: #172033; + --muted: #697386; + --line: #e3e8ef; + --line-strong: #cdd5df; + --accent: #f59e0b; + --accent-strong: #d97706; + --accent-soft: #fff7e6; + --primary: #1f2937; + --primary-hover: #111827; + --danger: #dc2626; + --danger-soft: #fef2f2; + --success: #059669; + --success-soft: #ecfdf5; + --shadow: 0 18px 50px rgba(23, 32, 51, 0.08); + --radius: 16px; + --radius-sm: 10px; + --font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", + "Microsoft YaHei", sans-serif; + --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #11151d; + --panel: #1a202b; + --panel-soft: #202836; + --text: #edf1f7; + --muted: #98a4b7; + --line: #2c3545; + --line-strong: #3d485b; + --accent: #fbbf24; + --accent-strong: #f59e0b; + --accent-soft: #332a16; + --primary: #f8fafc; + --primary-hover: #e2e8f0; + --danger: #f87171; + --danger-soft: #3a1d20; + --success: #34d399; + --success-soft: #122c24; + --shadow: 0 22px 60px rgba(0, 0, 0, 0.36); + } +} + +* { + box-sizing: border-box; +} + +html, +body { + width: 100%; + height: 100%; + margin: 0; +} + +body { + overflow: hidden; + color: var(--text); + background: + radial-gradient(circle at 12% -5%, rgba(245, 158, 11, 0.12), transparent 32%), + var(--bg); + font-family: var(--font); + font-size: 14px; + -webkit-font-smoothing: antialiased; +} + +button, +input, +select { + font: inherit; +} + +button { + color: inherit; +} + +.app { + display: flex; + flex-direction: column; + width: 100%; + height: 100%; +} + +.app-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 24px; + padding: 20px 30px 16px; + flex: 0 0 auto; +} + +.brand { + display: flex; + align-items: center; + gap: 13px; + min-width: 0; +} + +.brand-logo { + width: 46px; + height: 46px; + border-radius: 13px; + box-shadow: 0 8px 20px rgba(245, 158, 11, 0.22); +} + +.brand-copy { + min-width: 0; +} + +.brand-copy h1 { + margin: 0; + font-size: 19px; + line-height: 1.25; + letter-spacing: -0.02em; +} + +.brand-copy p { + margin: 4px 0 0; + color: var(--muted); + font-size: 12px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.main-nav { + display: flex; + gap: 4px; + padding: 4px; + border: 1px solid var(--line); + border-radius: 12px; + background: color-mix(in srgb, var(--panel) 82%, transparent); +} + +.nav-btn { + padding: 8px 15px; + border: 0; + border-radius: 8px; + background: transparent; + color: var(--muted); + cursor: pointer; + transition: + background 0.16s ease, + color 0.16s ease; +} + +.nav-btn:hover { + color: var(--text); + background: var(--panel-soft); +} + +.nav-btn.is-active { + color: var(--text); + background: var(--panel); + box-shadow: 0 1px 4px rgba(16, 24, 40, 0.12); +} + +.app-main { + flex: 1 1 auto; + min-height: 0; + overflow-y: auto; + padding: 0 30px 34px; + scrollbar-width: thin; +} + +.view { + display: none; + width: 100%; + max-width: 920px; + margin: 0 auto; + animation: view-in 0.18s ease both; +} + +.view.is-active { + display: block; +} + +@keyframes view-in { + from { + opacity: 0; + transform: translateY(4px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +.card { + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--panel); + box-shadow: var(--shadow); +} + +.download-card { + padding: 24px; +} + +.card-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 20px; +} + +.card-head h2, +.section-head h2 { + margin: 0; + font-size: 17px; + line-height: 1.35; + letter-spacing: -0.01em; +} + +.card-head p, +.section-head p { + margin: 5px 0 0; + color: var(--muted); + font-size: 12.5px; + line-height: 1.5; +} + +.badge { + display: inline-flex; + align-items: center; + flex: 0 0 auto; + min-height: 25px; + padding: 2px 9px; + border: 1px solid color-mix(in srgb, var(--accent) 34%, var(--line)); + border-radius: 999px; + background: var(--accent-soft); + color: var(--accent-strong); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.01em; +} + +.selector-grid { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + gap: 14px; +} + +.field { + display: flex; + flex-direction: column; + gap: 7px; + min-width: 0; +} + +.field-label { + color: var(--muted); + font-size: 11.5px; + font-weight: 600; + letter-spacing: 0.02em; +} + +select, +input { + width: 100%; + min-height: 42px; + padding: 9px 12px; + border: 1px solid var(--line-strong); + border-radius: var(--radius-sm); + outline: none; + background: var(--panel-soft); + color: var(--text); + transition: + border-color 0.16s ease, + box-shadow 0.16s ease, + background 0.16s ease; +} + +select { + cursor: pointer; +} + +input::placeholder { + color: color-mix(in srgb, var(--muted) 68%, transparent); +} + +select:focus, +input:focus { + border-color: var(--accent); + background: var(--panel); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 17%, transparent); +} + +input:disabled, +select:disabled { + cursor: not-allowed; + opacity: 0.56; +} + +.selection-summary { + display: flex; + flex-wrap: wrap; + gap: 7px; + min-height: 24px; + margin: 14px 0 18px; +} + +.summary-chip { + display: inline-flex; + align-items: center; + gap: 5px; + max-width: 100%; + padding: 4px 8px; + border: 1px solid var(--line); + border-radius: 7px; + background: var(--panel-soft); + color: var(--muted); + font-size: 11.5px; +} + +.summary-chip strong { + color: var(--text); + font-weight: 600; +} + +.summary-chip span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.key-row { + display: grid; + grid-template-columns: minmax(0, 1fr) 112px; + align-items: end; + gap: 12px; +} + +.key-field input { + min-height: 48px; + font-family: var(--mono); + font-size: 13px; +} + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + min-height: 38px; + padding: 8px 15px; + border: 1px solid transparent; + border-radius: 9px; + background: transparent; + cursor: pointer; + font-weight: 600; + white-space: nowrap; + transition: + transform 0.12s ease, + background 0.16s ease, + border-color 0.16s ease, + opacity 0.16s ease; +} + +.btn:active:not(:disabled) { + transform: translateY(1px); +} + +.btn:disabled { + cursor: not-allowed; + opacity: 0.48; +} + +.btn-primary { + background: var(--primary); + color: var(--panel); +} + +.btn-primary:hover:not(:disabled) { + background: var(--primary-hover); +} + +@media (prefers-color-scheme: dark) { + .btn-primary { + color: #11151d; + } +} + +.btn-download { + min-height: 48px; + background: linear-gradient(180deg, #f7ad2a, var(--accent-strong)); + color: #271500; + box-shadow: 0 8px 18px rgba(217, 119, 6, 0.22); +} + +.btn-download:hover:not(:disabled) { + filter: brightness(1.03); +} + +.btn-ghost { + border-color: var(--line-strong); + background: var(--panel); + color: var(--text); +} + +.btn-ghost:hover:not(:disabled) { + background: var(--panel-soft); +} + +.btn-warn { + border-color: color-mix(in srgb, var(--accent) 42%, var(--line)); + background: var(--accent-soft); + color: var(--accent-strong); +} + +.btn-danger-ghost { + border-color: color-mix(in srgb, var(--danger) 32%, var(--line)); + color: var(--danger); + background: transparent; +} + +.btn-danger-ghost:hover:not(:disabled) { + background: var(--danger-soft); +} + +.btn-small { + min-height: 32px; + padding: 5px 11px; + font-size: 12px; +} + +.text-btn { + flex: 0 0 auto; + padding: 0; + border: 0; + background: none; + color: var(--accent-strong); + font-size: 12px; + font-weight: 600; + cursor: pointer; + white-space: nowrap; +} + +.text-btn:hover { + text-decoration: underline; +} + +.text-btn:disabled { + cursor: not-allowed; + opacity: 0.45; + text-decoration: none; +} + +.text-btn.danger { + color: var(--danger); +} + +.hint { + margin: 0; + color: var(--muted); + font-size: 11.5px; + line-height: 1.55; +} + +code { + font-family: var(--mono); +} + +.key-hint-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + margin-top: 9px; +} + +.key-hint-row code { + color: var(--text); + font-size: 11px; + word-break: break-all; +} + +.notice { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + padding: 12px 14px; + border: 1px solid transparent; + border-radius: 11px; + font-size: 12.5px; + line-height: 1.5; +} + +.notice + .card, +.notice + .progress-card, +.notice + .result-card { + margin-top: 14px; +} + +.notice-warn { + margin-bottom: 14px; + border-color: color-mix(in srgb, var(--accent) 32%, var(--line)); + background: var(--accent-soft); + color: var(--accent-strong); +} + +.notice-error { + margin-top: 14px; + border-color: color-mix(in srgb, var(--danger) 28%, var(--line)); + background: var(--danger-soft); + color: var(--danger); +} + +.progress-card { + margin-top: 14px; + padding: 18px 20px; +} + +.progress-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 18px; +} + +.progress-copy { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; +} + +.progress-copy strong { + font-size: 13.5px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.muted { + color: var(--muted); +} + +.progress-track { + position: relative; + height: 8px; + margin-top: 16px; + overflow: hidden; + border-radius: 999px; + background: color-mix(in srgb, var(--line) 72%, transparent); +} + +.progress-bar { + width: 0%; + height: 100%; + border-radius: inherit; + background: linear-gradient(90deg, var(--accent), var(--accent-strong)); + transition: width 0.18s ease; +} + +.progress-track.is-indeterminate .progress-bar { + width: 36% !important; + animation: indeterminate 1.2s ease-in-out infinite; +} + +@keyframes indeterminate { + 0% { + transform: translateX(-115%); + } + 100% { + transform: translateX(310%); + } +} + +.progress-stats { + display: flex; + justify-content: space-between; + gap: 16px; + margin-top: 8px; + color: var(--muted); + font-size: 11.5px; +} + +.result-card { + display: flex; + align-items: center; + gap: 14px; + margin-top: 14px; + padding: 18px 20px; + border-color: color-mix(in srgb, var(--success) 28%, var(--line)); + background: linear-gradient(135deg, var(--success-soft), var(--panel) 55%); +} + +.result-card.is-error { + border-color: color-mix(in srgb, var(--danger) 28%, var(--line)); + background: linear-gradient(135deg, var(--danger-soft), var(--panel) 55%); +} + +.result-icon { + display: grid; + flex: 0 0 auto; + place-items: center; + width: 36px; + height: 36px; + border-radius: 50%; + background: var(--success); + color: #fff; + font-size: 18px; + font-weight: 700; +} + +.result-card.is-error .result-icon { + background: var(--danger); +} + +.result-body { + min-width: 0; + flex: 1 1 auto; +} + +.result-body h3 { + margin: 0; + font-size: 14px; +} + +.result-body p { + margin: 3px 0 0; + font-size: 11.5px; +} + +.result-path { + display: block; + margin-top: 6px; + color: var(--muted); + font-size: 11px; + line-height: 1.45; + word-break: break-all; +} + +.result-actions { + display: flex; + flex: 0 0 auto; + flex-wrap: wrap; + gap: 7px; +} + +.recent-card { + margin-top: 14px; + padding: 20px; +} + +.section-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; +} + +.recent-list { + display: flex; + flex-direction: column; + gap: 2px; + margin-top: 12px; +} + +.recent-item { + display: flex; + align-items: center; + gap: 12px; + padding: 9px 8px; + border-radius: 9px; + cursor: pointer; +} + +.recent-item:hover { + background: var(--panel-soft); +} + +.recent-icon { + display: grid; + flex: 0 0 auto; + place-items: center; + width: 32px; + height: 32px; + border: 1px solid var(--line); + border-radius: 8px; + background: var(--panel-soft); + color: var(--accent-strong); + font-size: 14px; +} + +.recent-copy { + min-width: 0; + flex: 1 1 auto; +} + +.recent-copy strong, +.recent-copy span { + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.recent-copy strong { + font-size: 12.5px; + font-weight: 600; +} + +.recent-copy span { + margin-top: 2px; + color: var(--muted); + font-size: 11px; +} + +.recent-open { + flex: 0 0 auto; + color: var(--muted); + font-size: 15px; +} + +.manage-tabs { + display: inline-flex; + gap: 4px; + margin-bottom: 20px; + padding: 4px; + border: 1px solid var(--line); + border-radius: 11px; + background: var(--panel); +} + +.manage-tab { + display: inline-flex; + align-items: center; + gap: 7px; + padding: 8px 15px; + border: 0; + border-radius: 8px; + background: transparent; + color: var(--muted); + cursor: pointer; + font-weight: 600; +} + +.manage-tab.is-active { + background: var(--panel-soft); + color: var(--text); +} + +.count { + display: inline-grid; + place-items: center; + min-width: 19px; + height: 19px; + padding: 0 5px; + border-radius: 999px; + background: color-mix(in srgb, var(--muted) 13%, transparent); + color: var(--muted); + font-size: 10.5px; +} + +.manage-panel { + margin-bottom: 18px; +} + +.profile-list { + display: grid; + gap: 10px; + margin-top: 14px; +} + +.profile-card { + display: flex; + align-items: center; + gap: 18px; + padding: 16px 18px; + border: 1px solid var(--line); + border-radius: 13px; + background: var(--panel); +} + +.profile-main { + min-width: 0; + flex: 1 1 auto; +} + +.profile-title { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 7px; +} + +.profile-title h3 { + margin: 0; + font-size: 14px; +} + +.profile-sub { + margin: 5px 0 0; + color: var(--muted); + font-family: var(--mono); + font-size: 11.5px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.profile-meta { + display: flex; + flex-wrap: wrap; + gap: 12px; + margin: 7px 0 0; + color: var(--muted); + font-size: 11px; +} + +.profile-meta code { + color: var(--text); +} + +.profile-actions { + display: flex; + flex: 0 0 auto; + gap: 6px; +} + +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + padding: 42px 20px; + border: 1px dashed var(--line-strong); + border-radius: var(--radius); + background: color-mix(in srgb, var(--panel) 72%, transparent); + text-align: center; +} + +.empty-icon { + font-size: 30px; + line-height: 1; +} + +.empty-state h3 { + margin: 14px 0 0; + font-size: 15px; +} + +.empty-state p { + max-width: 420px; + margin: 7px 0 16px; + color: var(--muted); + font-size: 12.5px; + line-height: 1.55; +} + +.settings-card { + margin-top: 14px; + padding: 20px; +} + +.directory-row { + display: flex; + align-items: center; + gap: 8px; + margin-top: 14px; +} + +.directory-row input { + flex: 1 1 auto; + font-family: var(--mono); + font-size: 11.5px; +} + +.settings-card .hint { + margin-top: 11px; +} + +.toast { + position: fixed; + left: 50%; + bottom: 26px; + z-index: 60; + max-width: min(560px, calc(100vw - 40px)); + padding: 10px 16px; + border: 1px solid var(--line); + border-radius: 10px; + background: color-mix(in srgb, var(--text) 92%, transparent); + color: var(--panel); + box-shadow: 0 12px 34px rgba(0, 0, 0, 0.22); + font-size: 12.5px; + transform: translateX(-50%); + animation: toast-in 0.18s ease both; +} + +.toast.is-error { + background: var(--danger); + color: #fff; +} + +@keyframes toast-in { + from { + opacity: 0; + transform: translate(-50%, 6px); + } + to { + opacity: 1; + transform: translate(-50%, 0); + } +} + +.modal { + position: fixed; + inset: 0; + z-index: 70; + display: grid; + place-items: center; + padding: 24px; +} + +.modal-backdrop { + position: absolute; + inset: 0; + background: rgba(8, 12, 20, 0.52); + backdrop-filter: blur(3px); +} + +.modal-card { + position: relative; + z-index: 1; + width: min(620px, 100%); + max-height: min(720px, calc(100vh - 48px)); + overflow-y: auto; + padding: 22px; + border: 1px solid var(--line); + border-radius: 18px; + background: var(--panel); + box-shadow: 0 30px 90px rgba(0, 0, 0, 0.32); + animation: modal-in 0.18s ease both; +} + +@keyframes modal-in { + from { + opacity: 0; + transform: translateY(8px) scale(0.99); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +.modal-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + margin-bottom: 18px; +} + +.modal-head h2 { + margin: 0; + font-size: 17px; +} + +.icon-btn { + display: grid; + place-items: center; + width: 32px; + height: 32px; + border: 0; + border-radius: 8px; + background: transparent; + color: var(--muted); + cursor: pointer; + font-size: 22px; + line-height: 1; +} + +.icon-btn:hover { + background: var(--panel-soft); + color: var(--text); +} + +.form { + display: flex; + flex-direction: column; + gap: 14px; +} + +.form-grid { + display: grid; + grid-template-columns: minmax(0, 1.5fr) minmax(120px, 0.8fr); + gap: 12px; +} + +.password-wrap { + position: relative; + display: flex; + align-items: center; +} + +.password-wrap input { + padding-right: 58px; +} + +.password-wrap .text-btn { + position: absolute; + right: 11px; +} + +.check-row { + display: flex; + flex-wrap: wrap; + gap: 18px; + padding: 3px 0; +} + +.checkbox { + display: inline-flex; + align-items: center; + gap: 8px; + color: var(--text); + font-size: 12.5px; + cursor: pointer; +} + +.checkbox input { + width: 16px; + min-height: 16px; + margin: 0; + accent-color: var(--accent-strong); +} + +.form-error { + margin: 0; + padding: 9px 11px; + border-radius: 8px; + background: var(--danger-soft); + color: var(--danger); + font-size: 12px; + line-height: 1.5; +} + +.form-actions { + display: flex; + justify-content: flex-end; + gap: 9px; + padding-top: 4px; +} + +.hidden { + display: none !important; +} + +@media (max-width: 720px) { + .app-header { + align-items: flex-start; + padding: 18px 18px 14px; + } + + .brand-logo { + width: 40px; + height: 40px; + } + + .brand-copy h1 { + font-size: 17px; + } + + .app-main { + padding: 0 18px 26px; + } + + .download-card { + padding: 18px; + } + + .selector-grid, + .key-row, + .form-grid { + grid-template-columns: 1fr; + } + + .btn-download { + width: 100%; + } + + .result-card { + align-items: flex-start; + flex-wrap: wrap; + } + + .result-actions { + width: 100%; + padding-left: 50px; + } + + .profile-card { + align-items: flex-start; + flex-wrap: wrap; + } + + .profile-actions { + width: 100%; + padding-left: 0; + } + + .directory-row { + align-items: stretch; + flex-wrap: wrap; + } + + .directory-row input { + flex-basis: 100%; + } +}