import { exec } from 'child_process'
import { exePath } from '../utils/dirs'
import { app } from 'electron'
import fs from 'fs'
const appName = 'mihomo-party'
const taskXml = `
${new Date().toISOString()}
${process.env.USERNAME}
true
InteractiveToken
HighestAvailable
IgnoreNew
false
false
false
true
false
false
false
true
true
false
false
false
PT0S
7
${exePath()}
`
export async function checkAutoRun(): Promise {
if (process.platform === 'win32') {
const { stdout } = (await new Promise((resolve) => {
exec(`schtasks /query /tn "${appName}"`, (_err, stdout, stderr) => {
resolve({ stdout, stderr })
})
})) as { stdout: string; stderr: string }
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')}\\${appName}.xml`
fs.writeFileSync(taskFilePath, taskXml)
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 "${appName}" /f`)
}
if (process.platform === 'darwin') {
app.setLoginItemSettings({
openAtLogin: false
})
}
if (process.platform === 'linux') {
const desktopFilePath = `${app.getPath('home')}/.config/autostart/${appName}.desktop`
try {
fs.rmSync(desktopFilePath)
} catch (e) {
console.error(e)
}
}
}