linux autostart

This commit is contained in:
pompurin404 2024-07-31 15:08:58 +08:00
parent 056f07de00
commit 35a9dcca4f
No known key found for this signature in database

View File

@ -5,7 +5,7 @@ import fs from 'fs'
// 获取应用的可执行文件路径
const exePath = app.getPath('exe')
const taskName = 'mihomo-party'
const appName = 'mihomo-party'
const taskXml = `
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
@ -54,38 +54,71 @@ const taskXml = `
export async function checkAutoRun(): Promise<boolean> {
if (process.platform === 'win32') {
const { stdout } = (await new Promise((resolve) => {
exec(`schtasks /query /tn "${taskName}"`, (_err, stdout, stderr) => {
exec(`schtasks /query /tn "${appName}"`, (_err, stdout, stderr) => {
resolve({ stdout, stderr })
})
})) as { stdout: string; stderr: string }
return stdout.includes(taskName)
} else {
return stdout.includes(appName)
}
if (process.platform === 'darwin') {
return app.getLoginItemSettings().openAtLogin
}
if (process.platform === 'linux') {
return fs.existsSync(`${app.getPath('home')}/.config/autostart/${appName}.desktop`)
}
return false
}
export function enableAutoRun(): void {
if (process.platform === 'win32') {
const taskFilePath = `${app.getPath('userData')}\\${taskName}.xml`
const taskFilePath = `${app.getPath('userData')}\\${appName}.xml`
fs.writeFileSync(taskFilePath, taskXml)
exec(`schtasks /create /tn "${taskName}" /xml "${taskFilePath}" /f`)
} else {
exec(`schtasks /create /tn "${appName}" /xml "${taskFilePath}" /f`)
}
if (process.platform === 'darwin') {
app.setLoginItemSettings({
openAtLogin: true,
path: exePath
})
}
if (process.platform === 'linux') {
let desktop = `
[Desktop Entry]
Name=mihomo-party
Exec=${exePath} %U
Terminal=false
Type=Application
Icon=mihomo-party
StartupWMClass=mihomo-party
Comment=Mihomo Party
Categories=Utility;
`
try {
if (fs.existsSync(`/usr/share/applications/${appName}.desktop`)) {
desktop = fs.readFileSync(`/usr/share/applications/${appName}.desktop`, 'utf8')
}
} catch (e) {
console.error(e)
}
fs.mkdirSync(`${app.getPath('home')}/.config/autostart`, { recursive: true })
const desktopFilePath = `${app.getPath('home')}/.config/autostart/${appName}.desktop`
fs.writeFileSync(desktopFilePath, desktop)
}
}
export function disableAutoRun(): void {
if (process.platform === 'win32') {
exec(`schtasks /delete /tn "${taskName}" /f`)
app.setLoginItemSettings({
openAtLogin: false
})
} else {
exec(`schtasks /delete /tn "${appName}" /f`)
}
if (process.platform === 'darwin') {
app.setLoginItemSettings({
openAtLogin: false
})
}
if (process.platform === 'linux') {
const desktopFilePath = `${app.getPath('home')}/.config/autostart/${appName}.desktop`
fs.rmSync(desktopFilePath)
}
}