Files
XHChat/Desktop/src/browser.ts
T

388 lines
16 KiB
TypeScript

import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, session, shell, WebContentsView } from 'electron'
import type { DownloadItem, Session } from 'electron'
import { randomUUID } from 'node:crypto'
import { join } from 'node:path'
import { clearDownloads, clearHistory, library, recordDownload, removeBookmark, toggleBookmark, visit } from './browser-library'
import { clearGrants, configurePermissions, grants, setGrant } from './browser-permissions'
const browserURL = 'xhchat://app/browser'
const height = 102
const maximumTabs = 16
type Tab = { id: string; view: WebContentsView; error: string }
type BrowserWindowState = {
window: BrowserWindow
sites: Session
privateMode: boolean
tabs: Tab[]
active?: Tab
libraryMode: boolean
}
const windows = new Map<number, BrowserWindowState>()
const downloads = new Map<string, DownloadItem>()
export function website(value: string): URL | undefined {
try {
const url = new URL(value)
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) return
if (url.protocol === 'http:' && !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)) return
return url
} catch {
return undefined
}
}
function address(value: string): URL | undefined {
const input = value.trim()
if (!input || input.length > 4096) return
if (/^[a-z][a-z0-9+.-]*:/i.test(input)) return website(input)
if (!/\s/.test(input) && input.includes('.')) return website('https://' + input)
return website('https://www.bing.com/search?' + new URLSearchParams({ q: input }))
}
function state(browser: BrowserWindowState) {
const contents = browser.active?.view.webContents
const collection = browser.privateMode ? { bookmarks: [], history: [], downloads: [] } : library()
const origin = website(contents?.getURL() ?? '')?.origin ?? ''
return {
privateMode: browser.privateMode,
active: browser.active?.id,
tabs: browser.tabs.map(({ id, view }) => ({ id, title: view.webContents.getTitle() || '新标签页' })),
url: contents?.getURL() ?? '',
back: contents?.navigationHistory.canGoBack() ?? false,
forward: contents?.navigationHistory.canGoForward() ?? false,
loading: contents?.isLoading() ?? false,
error: browser.active?.error ?? '',
libraryMode: browser.libraryMode,
origin,
grants: browser.privateMode || !origin ? {} : grants(origin),
bookmarked: collection.bookmarks.some((item) => item.url === contents?.getURL()),
...collection,
downloads: browser.privateMode ? [] : [
...[...downloads].map(([id, item]) => ({
id, name: item.getFilename(), state: item.isPaused() ? 'paused' : item.getState(),
received: item.getReceivedBytes(), total: item.getTotalBytes(), resumable: item.canResume(),
})),
...collection.downloads,
],
}
}
function update(browser: BrowserWindowState) {
if (!browser.window.isDestroyed()) browser.window.webContents.send('browser:state', state(browser))
}
function resize(browser: BrowserWindowState) {
const [width, total] = browser.window.getContentSize()
const top = browser.window.isFullScreen() ? 0 : height
browser.active?.view.setBounds({ x: 0, y: top, width, height: Math.max(0, total - top) })
browser.active?.view.setVisible(!browser.libraryMode)
}
function activate(browser: BrowserWindowState, tab?: Tab) {
if (browser.active) browser.window.contentView.removeChildView(browser.active.view)
browser.active = tab
if (tab) {
browser.window.contentView.addChildView(tab.view)
resize(browser)
}
update(browser)
}
function updateNormalWindows() {
for (const browser of windows.values()) if (!browser.privateMode) update(browser)
}
async function navigate(tab: Tab, url: URL) {
tab.error = ''
try {
await tab.view.webContents.loadURL(url.href)
} catch {
// The navigation events carry details for the toolbar.
}
}
function addTab(browser: BrowserWindowState, url?: URL) {
if (browser.tabs.length >= maximumTabs) return
const view = new WebContentsView({ webPreferences: {
session: browser.sites, sandbox: true, contextIsolation: true, nodeIntegration: false,
webSecurity: true, webviewTag: false, allowRunningInsecureContent: false,
} })
const tab = { id: randomUUID(), view, error: '' }
const contents = view.webContents
contents.setWindowOpenHandler(({ url }) => {
const target = website(url)
if (target) setImmediate(() => {
if (!browser.window.isDestroyed()) addTab(browser, target)
})
return { action: 'deny' }
})
contents.on('will-frame-navigate', (event) => {
if (!website(event.url)) event.preventDefault()
})
contents.on('will-redirect', (event) => {
if (!website(event.url)) event.preventDefault()
})
contents.on('will-attach-webview', (event) => event.preventDefault())
contents.on('did-fail-load', (_event, code, _description, _url, mainFrame) => {
if (mainFrame && code !== -3) tab.error = '网页加载失败,请检查地址或网络。'
update(browser)
})
function remember() {
const current = website(contents.getURL())
if (!browser.privateMode && current && current.href.length <= 4096) {
try {
visit(current.href, contents.getTitle())
updateNormalWindows()
} catch {
tab.error = '无法保存浏览历史'
}
}
update(browser)
}
contents.on('did-navigate', () => { tab.error = ''; update(browser) })
contents.on('did-navigate-in-page', (_event, _url, mainFrame) => { if (mainFrame) remember() })
contents.on('page-title-updated', () => update(browser))
contents.on('did-start-loading', () => update(browser))
contents.on('did-stop-loading', remember)
contents.on('enter-html-full-screen', () => resize(browser))
contents.on('leave-html-full-screen', () => resize(browser))
contents.on('before-input-event', (event, input) => {
if (input.type === 'keyDown' && input.key === 'F11') {
event.preventDefault()
browser.window.setFullScreen(!browser.window.isFullScreen())
}
})
contents.on('context-menu', (_event, info) => {
const link = website(info.linkURL)
const current = website(contents.getURL())
Menu.buildFromTemplate([
{ label: '在新标签页打开链接', enabled: Boolean(link), click: () => { if (link) addTab(browser, link) } },
{ label: '复制链接', enabled: Boolean(link ?? current), click: () => clipboard.writeText((link ?? current)?.href ?? '') },
{ label: '复制选中文字', enabled: Boolean(info.selectionText), click: () => contents.copy() },
{ label: '在系统浏览器打开', enabled: Boolean(current), click: () => { if (current) void shell.openExternal(current.href).catch(() => {}) } },
]).popup({ window: browser.window })
})
browser.tabs.push(tab)
activate(browser, tab)
if (url) void navigate(tab, url)
}
function closeTab(browser: BrowserWindowState, tab: Tab) {
const index = browser.tabs.indexOf(tab)
browser.tabs.splice(index, 1)
if (browser.active === tab) activate(browser, browser.tabs[Math.min(index, browser.tabs.length - 1)])
tab.view.webContents.close()
if (!browser.tabs.length) addTab(browser)
update(browser)
}
const configured = new WeakSet<Session>()
function configureSites(sites: Session, privateMode: boolean) {
if (configured.has(sites)) return
configured.add(sites)
configurePermissions(sites, privateMode, (contents) => [...windows.values()].some((browser) =>
!browser.libraryMode && browser.active?.view.webContents === contents && browser.window.isVisible()))
const defaultUA = sites.getUserAgent()
.replace(/\sElectron\/\S+/g, '')
.replace(/\s(?:XHChat|xhchat)\/\S+/g, '')
sites.setUserAgent(defaultUA + ' XHChat/' + app.getVersion())
sites.webRequest.onBeforeRequest((details, callback) => {
const scheme = new URL(details.url).protocol
callback({ cancel: !['https:', 'http:', 'wss:', 'ws:', 'data:', 'blob:', 'about:'].includes(scheme) })
})
sites.on('will-download', (event, item, contents) => {
const browser = [...windows.values()].find((window) => window.tabs.some((tab) => tab.view.webContents === contents))
if (!browser || privateMode || !item.getURLChain().every(website)) {
event.preventDefault()
return
}
item.setSaveDialogOptions({ title: '保存网页下载', buttonLabel: '保存' })
const id = randomUUID()
downloads.set(id, item)
item.on('updated', updateNormalWindows)
item.once('done', (_event, result) => {
downloads.delete(id)
if (result === 'completed' || result === 'cancelled' || result === 'interrupted') {
try {
recordDownload({ id, name: item.getFilename(), path: item.getSavePath(), state: result, time: Date.now() })
} catch {
if (browser.active) browser.active.error = '无法保存下载记录'
}
}
updateNormalWindows()
})
updateNormalWindows()
})
}
export function openBrowser(trusted: Session, privateMode = false) {
const sites = session.fromPartition(privateMode ? 'xhchat-private-' + randomUUID() : 'persist:xhchat-sites')
configureSites(sites, privateMode)
const window = new BrowserWindow({
title: privateMode ? 'XHChat 浏览器 · 隐私窗口' : 'XHChat 浏览器',
width: 1050, height: 720, minWidth: 620, minHeight: 430,
webPreferences: {
session: trusted, preload: join(__dirname, 'browser-preload.js'),
sandbox: true, contextIsolation: true, nodeIntegration: false, webviewTag: false,
},
})
const browser: BrowserWindowState = { window, sites, privateMode, tabs: [], libraryMode: false }
const id = window.webContents.id
windows.set(id, browser)
window.setMenuBarVisibility(false)
window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
window.webContents.on('will-navigate', (event) => event.preventDefault())
window.webContents.on('will-attach-webview', (event) => event.preventDefault())
window.on('resize', () => resize(browser))
window.on('enter-full-screen', () => resize(browser))
window.on('leave-full-screen', () => resize(browser))
window.on('closed', () => {
windows.delete(id)
for (const tab of browser.tabs) tab.view.webContents.close()
if (privateMode) void sites.clearData().catch(() => {})
})
window.webContents.on('did-finish-load', () => addTab(browser))
void window.loadURL(browserURL).catch(() => {
if (!window.isDestroyed()) window.close()
})
}
export function registerBrowserHandlers(trusted: Session) {
ipcMain.handle('browser:command', async (event, action: unknown, value: unknown) => {
const browser = windows.get(event.sender.id)
if (!browser || event.senderFrame !== event.sender.mainFrame || event.senderFrame?.url !== browserURL) {
throw new Error('浏览器命令来源无效')
}
const tab = browser.active
const contents = tab?.view.webContents
const current = website(contents?.getURL() ?? '')
switch (action) {
case 'new': addTab(browser); break
case 'private': openBrowser(trusted, true); break
case 'activate': {
const selected = browser.tabs.find(({ id }) => id === value)
if (selected) activate(browser, selected)
break
}
case 'close': {
const selected = browser.tabs.find(({ id }) => id === value)
if (selected) closeTab(browser, selected)
break
}
case 'go': {
const target = typeof value === 'string' ? address(value) : undefined
if (!target) throw new Error('请输入 HTTPS 地址或搜索关键词。')
browser.libraryMode = false
resize(browser)
if (tab) void navigate(tab, target)
break
}
case 'back': contents?.navigationHistory.goBack(); break
case 'forward': contents?.navigationHistory.goForward(); break
case 'reload': contents?.reload(); break
case 'stop': contents?.stop(); break
case 'copy': if (current) clipboard.writeText(current.href); break
case 'external': if (current) await shell.openExternal(current.href); break
case 'zoomIn': if (contents) contents.setZoomLevel(Math.min(4, contents.getZoomLevel() + 1)); break
case 'zoomOut': if (contents) contents.setZoomLevel(Math.max(-3, contents.getZoomLevel() - 1)); break
case 'fullscreen': browser.window.setFullScreen(!browser.window.isFullScreen()); break
case 'library': {
if (browser.privateMode) throw new Error('隐私窗口不记录浏览历史')
browser.libraryMode = !browser.libraryMode
resize(browser)
break
}
case 'bookmark': {
if (browser.privateMode || !current || current.href.length > 4096) throw new Error('此页面无法添加书签')
toggleBookmark(current.href, contents?.getTitle() ?? '')
updateNormalWindows()
break
}
case 'removeBookmark': {
if (browser.privateMode || typeof value !== 'string') break
removeBookmark(value)
updateNormalWindows()
break
}
case 'downloadPause':
case 'downloadResume':
case 'downloadCancel': {
if (browser.privateMode || typeof value !== 'string') break
const item = downloads.get(value)
if (action === 'downloadPause' && item?.getState() === 'progressing') item.pause()
if (action === 'downloadResume' && item?.canResume()) item.resume()
if (action === 'downloadCancel') item?.cancel()
updateNormalWindows()
break
}
case 'showDownload': {
if (browser.privateMode || typeof value !== 'string') break
const item = library().downloads.find((entry) => entry.id === value && entry.state === 'completed')
if (item?.path) shell.showItemInFolder(item.path)
break
}
case 'siteGrant': {
if (browser.privateMode || !browser.libraryMode || !current || typeof value !== 'string') break
const [origin, permission, desired, ...rest] = value.split('\n')
if (origin !== current.origin || rest.length || !['allow', 'block'].includes(desired)) {
throw new Error('网页已切换,请重新检查网站权限')
}
setGrant(origin, permission, desired === 'allow')
if (desired === 'block') {
for (const candidate of windows.values()) {
if (candidate.sites !== browser.sites) continue
for (const tab of candidate.tabs) {
const page = tab.view.webContents
if (website(page.getURL())?.origin === origin) page.reload()
}
}
}
updateNormalWindows()
break
}
case 'clearDownloads': {
if (browser.privateMode) break
clearDownloads()
updateNormalWindows()
break
}
case 'openEntry': {
if (browser.privateMode || typeof value !== 'string') break
const { bookmarks, history } = library()
const entry = [...bookmarks, ...history].find((item) => item.id === value)
const target = entry ? website(entry.url) : undefined
if (!target) throw new Error('该网址不可用')
browser.libraryMode = false
resize(browser)
if (tab) void navigate(tab, target)
break
}
case 'clear': {
const answer = await dialog.showMessageBox(browser.window, {
type: 'question', message: '清除浏览器 Cookie、缓存和网站数据?',
buttons: ['取消', '清除'], defaultId: 0, cancelId: 0,
})
if (answer.response === 1) {
await browser.sites.clearData()
if (!browser.privateMode) {
clearHistory()
clearGrants()
}
for (const candidate of windows.values()) {
if (candidate.sites !== browser.sites) continue
for (const tab of candidate.tabs) tab.view.webContents.navigationHistory.clear()
update(candidate)
}
}
break
}
case 'state': break
default: throw new Error('未知浏览器命令')
}
return state(browser)
})
}