| 1 | import React, { useEffect, useRef, useState } from 'react'; |
| 2 | import { Download, ExternalLink, FolderInput, Puzzle, RefreshCw, Trash2, Upload, X } from 'lucide-react'; |
| 3 | import { api, uploadFile } from './api'; |
| 4 | import { assertConnection, getClientContext } from './client-context.mjs'; |
| 5 | import { InlineSelect } from './inline-select'; |
| 6 | |
| 7 | function Permissions({ item, expanded = false }) { |
| 8 | const permissions = [...(item.permissions || []), ...(item.hostPermissions || [])]; |
| 9 | return <details className="extension-permissions" open={expanded || undefined}><summary>权限与网站访问{permissions.length ? `(${permissions.length})` : ''}</summary> |
| 10 | {permissions.length ? <ul>{permissions.map((value, index) => <li key={index}>{value}</li>)}</ul> : <p>未声明额外权限。</p>}</details>; |
| 11 | } |
| 12 | |
| 13 | function LocalExtensionImport({ existing, onUpdated, onClose }) { |
| 14 | const [profiles, setProfiles] = useState(null), [profileID, setProfileID] = useState(''); |
| 15 | const [selected, setSelected] = useState(new Set()), [results, setResults] = useState({}); |
| 16 | const [busy, setBusy] = useState(false), [error, setError] = useState(''); |
| 17 | const alive = useRef(true); |
| 18 | useEffect(() => { |
| 19 | api('/client/browser-extensions').then(data => { if (alive.current) { setProfiles(data.profiles); setProfileID(data.profiles[0]?.id || ''); } }) |
| 20 | .catch(error => { if (alive.current) setError(error.message); }); |
| 21 | return () => { alive.current = false; }; |
| 22 | }, []); |
| 23 | const profile = profiles?.find(item => item.id === profileID); |
| 24 | const installed = new Set(existing.map(item => item.source)); |
| 25 | const completed = Object.values(results).some(value => value.startsWith('已导入')); |
| 26 | const eligible = item => item.compatible && !installed.has(`${profileID}:${item.id}`); |
| 27 | const importCount = profile?.extensions.filter(item => selected.has(item.id) && eligible(item)).length || 0; |
| 28 | const choose = value => { setProfileID(value); setSelected(new Set()); setResults({}); setError(''); }; |
| 29 | const importSelected = async () => { |
| 30 | if (busy || !profile) return; |
| 31 | const connection = getClientContext().connection_id; |
| 32 | setBusy(true); setError(''); |
| 33 | for (const item of profile.extensions.filter(item => selected.has(item.id) && eligible(item))) { |
| 34 | let pending; |
| 35 | try { |
| 36 | assertConnection(connection); |
| 37 | if (!alive.current) break; |
| 38 | setResults(previous => ({ ...previous, [item.id]: '正在导入…' })); |
| 39 | const response = await fetch('/api/client/browser-extensions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ profile: profileID, id: item.id, version: item.version }) }); |
| 40 | if (!response.ok) throw new Error((await response.text()).trim()); |
| 41 | const file = new File([await response.blob()], item.id + '.zip', { type: 'application/zip' }); |
| 42 | assertConnection(connection); |
| 43 | if (!alive.current) break; |
| 44 | pending = await uploadFile('/browser/extensions/upload', file); |
| 45 | assertConnection(connection); |
| 46 | if (!alive.current) throw new Error('导入已停止'); |
| 47 | const next = await api('/browser/extensions', { mode: 'install', session: pending.session, target: `${profileID}:${item.id}`, enabled: item.state_known && item.enabled }); |
| 48 | pending = null; |
| 49 | if (alive.current) { onUpdated(next.items); setResults(previous => ({ ...previous, [item.id]: item.state_known && item.enabled ? '已导入并启用' : '已导入,保持停用' })); } |
| 50 | } catch (error) { |
| 51 | if (pending && getClientContext().connection_id === connection) await api('/browser/extensions', { mode: 'cancel', session: pending.session }).catch(() => {}); |
| 52 | if (alive.current) setResults(previous => ({ ...previous, [item.id]: '导入失败:' + error.message })); |
| 53 | if (getClientContext().connection_id !== connection) break; |
| 54 | } |
| 55 | } |
| 56 | if (alive.current) setBusy(false); |
| 57 | }; |
| 58 | return <section className="extension-import" aria-label="从本机导入扩展"> |
| 59 | <div className="browser-setting-heading"><h3>从本机浏览器导入</h3><button className="icon-button" aria-label="关闭本机导入" disabled={busy} onClick={onClose}><X size={16} /></button></div> |
| 60 | <p>一次复制所选扩展及启停状态。浏览器账户、Cookie 和扩展登录数据保留在本机浏览器中。</p> |
| 61 | {error && <p className="browser-settings-error" role="alert">{error}</p>} |
| 62 | {!profiles && !error && <p role="status">正在查找本机浏览器配置…</p>} |
| 63 | {profiles?.length === 0 && <p>未找到 Edge、Chrome、Brave 或 Chromium 的扩展配置。</p>} |
| 64 | {Boolean(profiles?.length) && <> |
| 65 | <label className="browser-setting-field">本机浏览器配置<InlineSelect aria-label="本机浏览器配置" value={profileID} disabled={busy} onValueChange={choose}> |
| 66 | {profiles.map(item => <option value={item.id} key={item.id}>{item.browser} · {item.name}</option>)} |
| 67 | </InlineSelect></label> |
| 68 | <div className="extension-import-actions"><button disabled={busy} onClick={() => setSelected(new Set(profile?.extensions.filter(eligible).map(item => item.id)))}>选择全部兼容扩展</button> |
| 69 | {completed && !busy && !importCount ? <button className="primary" onClick={onClose}>完成并关闭</button> : <button className="primary" disabled={busy || !importCount} onClick={importSelected}><Download size={15} />{busy ? '正在导入…' : `导入所选扩展(${importCount})`}</button>}</div> |
| 70 | {!profile?.extensions.length && <p>此配置没有可读取的扩展。</p>} |
| 71 | {profile?.extensions.map(item => <article className="extension-import-row" key={item.id}> |
| 72 | <label><input type="checkbox" disabled={busy || !eligible(item)} checked={selected.has(item.id)} onChange={event => setSelected(previous => { const next = new Set(previous); if (event.target.checked) next.add(item.id); else next.delete(item.id); return next; })} /> |
| 73 | <strong>{item.name}</strong><span>{item.version}</span></label> |
| 74 | <p className="extension-import-state" role={results[item.id] ? 'status' : undefined}>{results[item.id] || (!item.compatible ? '不支持此扩展版本,仅支持 Manifest V3' : installed.has(`${profileID}:${item.id}`) ? '已导入' : !item.state_known ? '未能读取启停状态,导入后停用' : item.enabled ? '本机已启用' : '本机已停用')}</p> |
| 75 | {item.compatible && !item.identity_preserved && <p>此扩展的标识可能变化,依赖浏览器身份或授权的功能可能需要重新配置。</p>} |
| 76 | <Permissions item={item} /> |
| 77 | </article>)} |
| 78 | </>} |
| 79 | </section>; |
| 80 | } |
| 81 | |
| 82 | export function BrowserExtensions({ onOpenPage, onInternal, onConfirm }) { |
| 83 | const [items, setItems] = useState(null), [error, setError] = useState(''), [busy, setBusy] = useState(''); |
| 84 | const [preview, setPreview] = useState(null), [importing, setImporting] = useState(false); |
| 85 | const file = useRef(), alive = useRef(true), pending = useRef(null); |
| 86 | const connection = useRef(getClientContext().connection_id); |
| 87 | const load = async () => { |
| 88 | setError(''); |
| 89 | try { const result = await api('/browser/extensions', { mode: 'list' }); if (alive.current) setItems(result.items); } |
| 90 | catch (error) { if (alive.current) setError(error.message); } |
| 91 | }; |
| 92 | useEffect(() => { |
| 93 | void load(); |
| 94 | return () => { alive.current = false; if (pending.current && getClientContext().connection_id === connection.current) void api('/browser/extensions', { mode: 'cancel', session: pending.current }).catch(() => {}); }; |
| 95 | }, []); |
| 96 | const select = async event => { |
| 97 | const selected = event.target.files?.[0]; event.target.value = ''; |
| 98 | if (!selected) return; |
| 99 | if (selected.size > 32 << 20) { setError('扩展 ZIP 不能超过 32 MB'); return; } |
| 100 | setBusy('upload'); setError(''); |
| 101 | try { |
| 102 | const result = await uploadFile('/browser/extensions/upload', selected); |
| 103 | if (!alive.current) { if (getClientContext().connection_id === connection.current) await api('/browser/extensions', { mode: 'cancel', session: result.session }); return; } |
| 104 | pending.current = result.session; setPreview(result); |
| 105 | } catch (error) { if (alive.current) setError(error.message); } |
| 106 | finally { if (alive.current) setBusy(''); } |
| 107 | }; |
| 108 | const act = async (mode, id) => { |
| 109 | if (busy) return; |
| 110 | if (mode === 'remove' && !(await onConfirm({ title: '移除此扩展?', body: '扩展将从 Cage 浏览器中移除。本机 Edge 或 Chrome 中的扩展保持原状。', confirm: '移除扩展' }))) return; |
| 111 | setBusy(id || mode); setError(''); |
| 112 | try { |
| 113 | const result = await api('/browser/extensions', { mode, id, ...(mode === 'install' ? { session: preview.session } : {}) }); |
| 114 | if (mode === 'install' || mode === 'cancel') { pending.current = null; setPreview(null); } |
| 115 | if (result.native) await onInternal('extensions', result.id); |
| 116 | else if (result.id && result.url) await onOpenPage(result); |
| 117 | else if (result.items) setItems(result.items); |
| 118 | } catch (error) { setError(error.message); } |
| 119 | finally { setBusy(''); } |
| 120 | }; |
| 121 | const cancel = async () => { |
| 122 | setBusy('cancel'); setError(''); |
| 123 | try { await api('/browser/extensions', { mode: 'cancel', session: preview.session }); pending.current = null; setPreview(null); } |
| 124 | catch (error) { setError(error.message); } |
| 125 | finally { setBusy(''); } |
| 126 | }; |
| 127 | return <div className="browser-extensions"> |
| 128 | <div className="browser-setting-actions"> |
| 129 | <button className="primary" disabled={Boolean(busy || preview)} onClick={() => file.current?.click()}><Upload size={15} />添加 ZIP 扩展</button> |
| 130 | <button disabled={Boolean(busy || preview)} onClick={() => setImporting(true)}><FolderInput size={15} />从本机导入</button> |
| 131 | <button aria-label="刷新扩展" disabled={Boolean(busy)} onClick={load}><RefreshCw size={15} /></button> |
| 132 | </div> |
| 133 | <input ref={file} type="file" accept=".zip,application/zip" hidden onChange={select} aria-label="选择扩展 ZIP" /> |
| 134 | <p>支持 Chromium Manifest V3 扩展。扩展运行在 Cage 环境中,并按声明的权限访问网站。</p> |
| 135 | {error && <p className="browser-settings-error" role="alert">{error}</p>} |
| 136 | {busy === 'upload' && <p role="status">正在读取扩展包…</p>} |
| 137 | {preview && <section className="extension-install-preview" aria-label="确认扩展安装"> |
| 138 | <h3>确认安装 {preview.name}</h3><p>版本 {preview.version}</p><p>{preview.description}</p> |
| 139 | <Permissions item={preview} expanded /> |
| 140 | <div className="browser-setting-actions"><button className="primary" disabled={Boolean(busy)} onClick={() => act('install')}>安装扩展</button><button disabled={Boolean(busy)} onClick={cancel}>取消</button></div> |
| 141 | </section>} |
| 142 | {importing && <LocalExtensionImport existing={items || []} onUpdated={setItems} onClose={() => setImporting(false)} />} |
| 143 | <div className="browser-setting-heading"><h3>已安装的扩展{items ? `(${items.length})` : ''}</h3></div> |
| 144 | {items === null && !error ? <p role="status">正在读取扩展…</p> : items?.length === 0 ? <div className="extension-empty"><Puzzle size={28} /><strong>让浏览器更合用</strong><p>添加扩展,或从本机浏览器导入已有扩展。</p></div> : items?.map(item => <article className="extension-item" key={item.id}> |
| 145 | <div className="browser-setting-heading"><div><strong>{item.name}</strong><span className="extension-version">{item.version}</span></div> |
| 146 | <label className="extension-enable"><input type="checkbox" aria-label={`启用 ${item.name}`} checked={Boolean(item.enabled)} disabled={Boolean(busy) || item.mayDisable === false} onChange={() => act(item.enabled ? 'disable' : 'enable', item.id)} />{item.enabled ? '已启用' : '已停用'}</label></div> |
| 147 | {item.description && <p>{item.description}</p>}{item.error && <p role="alert" className="browser-settings-error">{item.error}</p>} |
| 148 | <Permissions item={item} /> |
| 149 | <div className="extension-item-footer"><span>{item.id}</span><div className="browser-setting-actions"> |
| 150 | {item.optionsUrl && <button disabled={Boolean(busy) || !item.enabled} onClick={() => act('options', item.id)}>扩展选项</button>} |
| 151 | <button disabled={Boolean(busy) || item.mayDisable === false} onClick={() => act('remove', item.id)}><Trash2 size={14} />{item.managed ? '移除' : '管理'}</button> |
| 152 | </div></div> |
| 153 | </article>)} |
| 154 | <div className="browser-settings-links"><button onClick={() => onInternal('extensions')}><ExternalLink size={15} />Chromium 扩展管理</button> |
| 155 | <button onClick={() => onOpenPage({ url: 'https://chromewebstore.google.com/', kind: 'web' })}><ExternalLink size={15} />打开扩展商店</button></div> |
| 156 | </div>; |
| 157 | } |