Skip to content

Commit

Permalink
feat(interface): add onStartup to ensure everything is loaded (#2418)
Browse files Browse the repository at this point in the history
* feat(interface): add onStartup to ensure everything is loaded

before enabled variable is accounted

Fixes #2408

* remove incorrect definition
  • Loading branch information
sogehige committed Jul 10, 2019
1 parent bd9fadf commit 7d2d596
Show file tree
Hide file tree
Showing 9 changed files with 61 additions and 45 deletions.
1 change: 1 addition & 0 deletions d.ts/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ declare namespace InterfaceSettings {
}

interface On {
startup?: string[];
message?: (message: onEventMessage) => void;
sub?: (syb: onEventSub) => void;
follow?: (follow: onEventFollow) => void;
Expand Down
25 changes: 21 additions & 4 deletions src/bot/_interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { isMainThread } from 'worker_threads';
import { permission } from './permissions';
import { flatten, unflatten } from './commons';
import * as Parser from './parser';
import { getFunctionList } from './decorators/on';
import { loadingInProgress } from './decorators';

class Module {
public dependsOn: string[] = [];
Expand Down Expand Up @@ -78,10 +80,25 @@ class Module {
// prepare proxies for variables
this._sockets();
this._indexDbs();
this.loadVariableValue('enabled').then((value) => {
this._enabled = typeof value === 'undefined' ? this._enabled : value;
this.status({ state: this._enabled, quiet: !isMainThread });
});
setTimeout(() => {
this.loadVariableValue('enabled').then((value) => {
const onStartup = () => {
if (loadingInProgress.length > 0) {
// wait until all settings are loaded
return setTimeout(() => onStartup(), 100);
}
this._enabled = typeof value === 'undefined' ? this._enabled : value;
this.status({ state: this._enabled, quiet: !isMainThread });
if (isMainThread) {
const path = this._name === 'core' ? this.constructor.name.toLowerCase() : `${this._name}.${this.constructor.name.toLowerCase()}`;
for (const fnc of getFunctionList('startup', path)) {
this[fnc]('enabled', value);
}
};
};
onStartup();
});
}, 5000); // slow down little bit to have everything preloaded or in progress of loading
}

public sockets() {
Expand Down
7 changes: 7 additions & 0 deletions src/bot/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import * as _ from 'lodash';
import { parse, sep as separator } from 'path';
import { VariableWatcher } from './watchers';

export let loadingInProgress: string[] = [];

function getNameAndTypeFromStackTrace() {
const _prepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = (_s, s) => s;
Expand Down Expand Up @@ -55,6 +57,10 @@ export function settings(category?: string, isReadOnly: boolean = false) {
const { name, type } = getNameAndTypeFromStackTrace();

return (target: object, key: string) => {
if (!isReadOnly) {
loadingInProgress.push(`${type}.${name}.${key}`);
}

const registerSettings = () => {
const isAvailableModule = type !== 'core' && typeof global[type] !== 'undefined' && typeof global[type][name] !== 'undefined';
const isAvailableLibrary = type === 'core' && typeof global[name] !== 'undefined';
Expand All @@ -76,6 +82,7 @@ export function settings(category?: string, isReadOnly: boolean = false) {
VariableWatcher.add(`${type}.${name}.${key}`, value, isReadOnly); // rewrite value on var load
_.set(self, key, value);
}
loadingInProgress = loadingInProgress.filter(o => o !== `${type}.${name}.${key}`);
});
};
setTimeout(() => loadVariableValue(), 5000);
Expand Down
22 changes: 22 additions & 0 deletions src/bot/decorators/on.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
import { set, get } from 'lodash';
import { parse, sep as separator } from 'path';

const on: {
startup: {
path: string;
fName: string;
}[];
} = {
startup: [],
};

export function getFunctionList(type: 'startup', path: string): string[] {
return on[type].filter(o => o.path === path).map(o => o.fName);
}

export function onChange(variableArg: string) {
const { name, type } = getNameAndTypeFromStackTrace();

Expand Down Expand Up @@ -49,6 +62,15 @@ export function onLoad(variableArg: string) {
};
}

export function onStartup() {
const { name, type } = getNameAndTypeFromStackTrace();

return (target: object, fName: string) => {
const path = type === 'core' ? name : `${type}.${name.toLowerCase()}`;
on.startup.push({ path, fName });
};
}

export function onMessage() {
const { name, type } = getNameAndTypeFromStackTrace();

Expand Down
8 changes: 2 additions & 6 deletions src/bot/integrations/donationalerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import constants from '../constants.js';
import { isMainThread } from 'worker_threads';

import Integration from './_interface';
import { onChange } from '../decorators/on.js';
import { onChange, onStartup } from '../decorators/on.js';
import { settings } from '../decorators';
import { ui } from '../decorators.js';

Expand All @@ -19,15 +19,11 @@ class Donationalerts extends Integration {
super();

if (isMainThread) {
setTimeout(() => {
this.isEnabled().then(value => {
this.onStateChange('enabled', value);
});
}, 10000);
setInterval(() => this.connect(), constants.HOUR); // restart socket each hour
}
}

@onStartup()
@onChange('enabled')
onStateChange (key: string, val: boolean) {
if (val) {this.connect();}
Expand Down
11 changes: 2 additions & 9 deletions src/bot/integrations/phillipsHue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { isMainThread } from 'worker_threads';

import { sendMessage } from '../commons';
import { command, default_permission, settings } from '../decorators';
import { onChange } from '../decorators/on';
import { onChange, onStartup } from '../decorators/on';
import { permission } from '../permissions';
import Integration from './_interface';

Expand Down Expand Up @@ -45,14 +45,6 @@ class PhillipsHue extends Integration {
constructor () {
super();

if (isMainThread) {
setTimeout(() => {
this.isEnabled().then(value => {
this.onStateChange('enabled', value);
});
}, 10000);
}

setInterval(() => {
if (!this.isEnabled()) {return;}
for (let index = 0, length = this.states.length; index < length; index++) {
Expand Down Expand Up @@ -93,6 +85,7 @@ class PhillipsHue extends Integration {
}, 20);
}

@onStartup()
@onChange('enabled')
onStateChange (key: string, value: boolean) {
if (value) {
Expand Down
8 changes: 2 additions & 6 deletions src/bot/integrations/spotify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { isMainThread } from 'worker_threads';

import { prepare, sendMessage } from '../commons';
import { command, default_permission, settings, shared, ui } from '../decorators';
import { onChange } from '../decorators/on';
import { onChange, onStartup } from '../decorators/on';
import Expects from '../expects';
import Integration from './_interface';

Expand Down Expand Up @@ -115,11 +115,6 @@ class Spotify extends Integration {
this.timeouts.ICurrentSong = global.setTimeout(() => this.ICurrentSong(), 10000);
this.timeouts.getMe = global.setTimeout(() => this.getMe(), 10000);
setInterval(() => this.sendSongs(), 500);
setTimeout(() => {
this.isEnabled().then(value => {
this.onStateChange('enabled', value);
});
}, 10000);
}
}

Expand All @@ -128,6 +123,7 @@ class Spotify extends Integration {
if (value.length > 0) {global.log.info(chalk.yellow('SPOTIFY: ') + `Access to account ${value} granted`);}
}

@onStartup()
@onChange('enabled')
onStateChange (key: string, value: boolean) {
this.currentSong = JSON.stringify({});
Expand Down
16 changes: 2 additions & 14 deletions src/bot/integrations/streamlabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import chalk from 'chalk';

import Integration from './_interface';
import { settings, ui } from '../decorators';
import { onChange } from '../decorators/on';
import { isMainThread } from 'worker_threads';
import { onChange, onStartup } from '../decorators/on';

class Streamlabs extends Integration {
socket: SocketIOClient.Socket | null = null;
Expand All @@ -14,18 +13,7 @@ class Streamlabs extends Integration {
@ui({ type: 'text-input', secret: true })
socketToken: string = '';

constructor () {
super();

if (isMainThread) {
setTimeout(() => {
this.isEnabled().then(value => {
this.onStateChange('enabled', value);
});
}, 10000);
}
}

@onStartup()
@onChange('enabled')
onStateChange (key: string, val: boolean) {
if (val) {this.connect();}
Expand Down
8 changes: 2 additions & 6 deletions src/bot/integrations/twitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { getOwner } from '../commons';
import Message from '../message';
import Integration from './_interface';
import { settings, ui } from '../decorators';
import { onChange } from '../decorators/on';
import { onChange, onStartup } from '../decorators/on';

class Twitter extends Integration {
public watchedStreams: {
Expand Down Expand Up @@ -39,11 +39,6 @@ class Twitter extends Integration {
setInterval(() => {
this.updateStreams();
}, 10000);
setTimeout(() => {
this.isEnabled().then(value => {
this.onStateChange('enabled', value);
});
}, 10000);
}
}

Expand Down Expand Up @@ -125,6 +120,7 @@ class Twitter extends Integration {
global.log.info(chalk.yellow('TWITTER: ') + 'Stream for ' + hash + ' was ended.');
}

@onStartup()
@onChange('enabled')
public onStateChange(key: string, value: boolean) {
if (value) {
Expand Down

0 comments on commit 7d2d596

Please sign in to comment.