58 lines
2.1 KiB
TypeScript
58 lines
2.1 KiB
TypeScript
import { execFile } from 'node:child_process'
|
|
import { mkdir, writeFile } from 'node:fs/promises'
|
|
import { homedir } from 'node:os'
|
|
import path from 'node:path'
|
|
import { promisify } from 'node:util'
|
|
|
|
import { app } from 'electron'
|
|
|
|
const run = promisify(execFile)
|
|
export const DESKTOP_SCHEME = 'planet-earth'
|
|
|
|
export async function registerDesktopLink(): Promise<void> {
|
|
if (!app.isPackaged) return
|
|
|
|
if (process.platform === 'linux') {
|
|
let desktopId = 'planet-client.desktop'
|
|
if (process.env.APPIMAGE) {
|
|
desktopId = 'planet-earth-appimage.desktop'
|
|
const applications = path.join(
|
|
process.env.XDG_DATA_HOME || path.join(homedir(), '.local', 'share'),
|
|
'applications',
|
|
)
|
|
const executable = process.env.APPIMAGE
|
|
if (!path.isAbsolute(executable) || /[\r\n]/.test(executable)) {
|
|
throw new Error('Invalid AppImage path')
|
|
}
|
|
// Escape the Exec argument, then the backslashes in the desktop-entry value.
|
|
const escaped = executable.replace(/%/g, '%%').replace(/["$\x60\\]/g, '\\$&').replace(/\\/g, '\\\\')
|
|
await mkdir(applications, { recursive: true })
|
|
await writeFile(path.join(applications, desktopId), [
|
|
'[Desktop Entry]',
|
|
'Type=Application',
|
|
'Name=Planet Earth',
|
|
'NoDisplay=true',
|
|
'Exec="' + escaped + '" %u',
|
|
'MimeType=x-scheme-handler/' + DESKTOP_SCHEME + ';',
|
|
'',
|
|
].join('\n'))
|
|
}
|
|
const mimeType = 'x-scheme-handler/' + DESKTOP_SCHEME
|
|
try {
|
|
await run('xdg-mime', ['default', desktopId, mimeType], { timeout: 8000 })
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
await run('gio', ['mime', mimeType, desktopId], { timeout: 8000 })
|
|
}
|
|
return
|
|
}
|
|
|
|
const executable = process.platform === 'win32'
|
|
? process.env.PORTABLE_EXECUTABLE_FILE || process.execPath
|
|
: undefined
|
|
if (!app.isDefaultProtocolClient(DESKTOP_SCHEME, executable)
|
|
&& !app.setAsDefaultProtocolClient(DESKTOP_SCHEME, executable)) {
|
|
throw new Error('Could not register the Planet Earth URL handler')
|
|
}
|
|
}
|