Files
planet/client/src/main/protocol.ts
T
linkong b3d2d9e9f1
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.81.0
2026-11-30 19:39:29 +08:00

92 lines
2.9 KiB
TypeScript

import { net, protocol, systemPreferences, type Session } from 'electron'
import { createEarthProtocolHandler } from './protocol-core'
export const EARTH_ORIGIN = 'planet://earth'
export const EARTH_ENTRY_URL = `${EARTH_ORIGIN}/earth/index.html`
function isEarthUrl(url: string): boolean {
return url === EARTH_ORIGIN || url.startsWith(`${EARTH_ORIGIN}/`)
}
export function registerEarthScheme(): void {
protocol.registerSchemesAsPrivileged([
{
scheme: 'planet',
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
stream: true,
allowServiceWorkers: true,
},
},
])
}
export function installEarthSessionHandlers(
targetSession: Session,
options: {
earthBundleRoot: string
getEarthOverlayRoot?: () => string | null
getBackendUrl: () => string
getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise<string | null>
},
): void {
const handler = createEarthProtocolHandler({
earthBundleRoot: options.earthBundleRoot,
getEarthOverlayRoot: options.getEarthOverlayRoot,
getBackendUrl: options.getBackendUrl,
getEarthAuthToken: options.getEarthAuthToken,
fetchImpl: (input, init) => net.fetch(input as string, init),
})
targetSession.protocol.handle('planet', handler)
targetSession.webRequest.onBeforeSendHeaders(
{
urls: ['*://*.youtube.com/*', '*://*.youtube-nocookie.com/*'],
},
(details, callback) => {
const requestHeaders = { ...details.requestHeaders }
if (!requestHeaders.Referer && !requestHeaders.referer) {
requestHeaders.Referer = 'https://earth.planet.local/'
}
callback({ requestHeaders })
},
)
targetSession.setPermissionRequestHandler((webContents, permission, callback, details) => {
if (permission === 'fullscreen') {
callback(isEarthUrl(webContents.getURL()))
return
}
if (permission === 'media' && details.isMainFrame && isEarthUrl(details.requestingUrl)) {
if ('mediaTypes' in details && details.mediaTypes?.includes('audio')) {
callback(false)
return
}
if (process.platform === 'darwin') {
void systemPreferences.askForMediaAccess('camera').then(
(granted) => callback(granted),
() => callback(false),
)
return
}
callback(true)
return
}
callback(false)
})
targetSession.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'fullscreen') return isEarthUrl(webContents?.getURL() || '')
if (permission !== 'media' || details.mediaType === 'audio' || !details.isMainFrame) return false
return (
isEarthUrl(details.requestingUrl || requestingOrigin) &&
(process.platform !== 'darwin' || systemPreferences.getMediaAccessStatus('camera') === 'granted')
)
})
}