Skip to content

Commit

Permalink
Merge pull request #1555 from spacemeshos/fix-1403-autostart
Browse files Browse the repository at this point in the history
Fix autostart
  • Loading branch information
brusherru authored Oct 11, 2023
2 parents 2a2ad82 + 33beaed commit dc9ba3c
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 78 deletions.
137 changes: 64 additions & 73 deletions desktop/AutoStartManager.ts
Original file line number Diff line number Diff line change
@@ -1,118 +1,109 @@
import { ipcMain } from 'electron';
import AutoLaunch from 'auto-launch';
import { captureException } from '@sentry/electron';
import { ipcConsts } from '../app/vars';
import { isLinuxAppImage } from '../shared/utils';

import { isMacOS } from './osSystem';
import Logger from './logger';
import { captureMainException } from './sentry';

export const IS_AUTO_START_ENABLED = 'isAutoStartEnabled';
// Results

type ToggleResult = {
status: boolean;
error?: string;
};

const handleFailure = (err: unknown): ToggleResult => {
if (
isMacOS() &&
err instanceof Error &&
err.message &&
/System Events/.test(err.message)
) {
return {
status: false,
error:
'Can not setup auto start: you need to provide permissions.\nGo to Settings -> Security & Privacy -> Privacy -> Automation and mark the checkbox next to "System Events" for the Spacemesh app.\nAnd then try again.',
};
}

err instanceof Error && captureMainException(err);

return {
status: false,
error: `Can not setup auto launch: ${err}`,
};
};

// Utils

const logger = Logger({ className: 'AutoStartManager' });

// Singletone class
class AutoStartManager {
private manager: AutoLaunch;
static service: AutoLaunch;

constructor() {
const options: { name: string; isHidden: boolean; path?: string } = {
static init() {
logger.debug('init() called...');
AutoStartManager.service = new AutoLaunch({
name: 'Spacemesh',
isHidden: true,
};

// Linux issue with path to the application
if (isLinuxAppImage()) {
options.path = process.env.APPIMAGE;
}

this.manager = new AutoLaunch(options);
this.checkStatusAndEnable();
path: isLinuxAppImage() ? process.env.APPIMAGE : process.execPath,
});

ipcMain.removeAllListeners(ipcConsts.TOGGLE_AUTO_START);
ipcMain.handle(ipcConsts.TOGGLE_AUTO_START, async () =>
this.toggleAutoStart()
ipcMain.handle(ipcConsts.TOGGLE_AUTO_START, () =>
AutoStartManager.toggleAutoStart()
);

ipcMain.removeHandler(ipcConsts.IS_AUTO_START_ENABLED_REQUEST);
ipcMain.handle(ipcConsts.IS_AUTO_START_ENABLED_REQUEST, () =>
this.manager.isEnabled()
AutoStartManager.isEnabled()
);
}

toggleAutoStart = async () => {
const status = await this.manager.isEnabled();
static isEnabled = () => AutoStartManager.service.isEnabled();

return status ? this.disable() : this.enable();
};
static toggleAutoStart = async () =>
(await AutoStartManager.isEnabled())
? AutoStartManager.disable()
: AutoStartManager.enable();

disable = async (): Promise<ToggleResult> => {
static disable = async (n = 0): Promise<ToggleResult> => {
try {
const isEnabled = await this.manager.isEnabled();
if (isEnabled) {
await this.manager.disable();
return await this.disable();
const isEnabled = await AutoStartManager.service.isEnabled();
if (isEnabled && n === 0) {
await AutoStartManager.service.disable();
return await AutoStartManager.disable(n + 1);
} else if (isEnabled) {
throw new Error('Cannot disable auto-launch for unknown reason');
} else {
return {
status: false,
};
}
} catch (err) {
if (
isMacOS() &&
err instanceof Error &&
err.message &&
/System Events/.test(err.message)
) {
// Since User disables the feature it does not matter
// do we have permissions or not — just "turn it off"
return { status: false };
}

captureException(err);
return {
status: false,
error: `Can not setup auto launch: ${err}`,
};
}
};

checkStatusAndEnable = async () => {
const status = await this.manager.isEnabled();

if (status) {
await this.manager.enable();
logger.error('disable()', err);
return handleFailure(err);
}
};

enable = async (): Promise<ToggleResult> => {
static enable = async (n = 0): Promise<ToggleResult> => {
try {
const isEnabled = await this.manager.isEnabled();
if (!isEnabled) {
await this.manager.enable();
return await this.enable();
const isEnabled = await AutoStartManager.service.isEnabled();
if (!isEnabled && n === 0) {
await AutoStartManager.service.enable();
return await AutoStartManager.enable(n + 1);
} else if (!isEnabled) {
throw new Error(
'Cannot enable auto-launch. Probably you already have another Spacemesh application in auto-launch'
);
} else {
return { status: true };
}
} catch (err) {
if (
isMacOS() &&
err instanceof Error &&
err.message &&
/System Events/.test(err.message)
) {
return {
status: false,
error:
'Can not setup auto start: you need to provide permissions.\nGo to Settings -> Security & Privacy -> Privacy -> Automation and mark the checkbox next to "System Events" for the Spacemesh app.\nAnd then try again.',
};
}
captureException(err);
return {
status: false,
error: `Can not setup auto launch: ${err}`,
};
logger.error('enable()', err);
return handleFailure(err);
}
};
}
Expand Down
3 changes: 2 additions & 1 deletion desktop/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ const Logger = ({ className }: { className: string }) => ({
logger.info?.(msg);
},
error: (fn: string, err: any, args?: any) => {
const msg = formatErrorMessage(className, fn, err, args);
const e = err instanceof Error ? String(err) : err;
const msg = formatErrorMessage(className, fn, e, args);
logger.error?.(msg);
// @todo clean up error invocation because of GRPC connection and streams and add sentry capture after it
},
Expand Down
3 changes: 1 addition & 2 deletions desktop/main.dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,11 @@ if (
);
process.exit(1);
}

// Run
app
.whenReady()
.then(installDevTools)
.then(() => new AutoStartManager())
.then(() => AutoStartManager.init())
.then(() => subscribeIPC(context))
.then(() => Wallet.subscribe())
.then(() => {
Expand Down
4 changes: 2 additions & 2 deletions desktop/main/startApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
import { shallowEq } from '../../shared/utils';
import Warning from '../../shared/warning';
import StoreService from '../storeService';
import { IS_AUTO_START_ENABLED } from '../AutoStartManager';
import AutoStartManager from '../AutoStartManager';
import createMainWindow from './createMainWindow';
import observeStoreService from './sources/storeService';
import {
Expand Down Expand Up @@ -148,7 +148,7 @@ const startApp = (): AppStore => {
const $warnings = new $.Subject<Warning>();
const startNodeAfterUpdate = StoreService.get('startNodeOnNextLaunch');
const $runNodeBeforeLogin = new $.BehaviorSubject<boolean>(
StoreService.get(IS_AUTO_START_ENABLED) || startNodeAfterUpdate
AutoStartManager.isEnabled() || startNodeAfterUpdate
);

const {
Expand Down

0 comments on commit dc9ba3c

Please sign in to comment.