-
-
Notifications
You must be signed in to change notification settings - Fork 63
/
general.ts
299 lines (266 loc) · 10.5 KB
/
general.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import { readdirSync, writeFileSync } from 'fs';
import { HOUR, MINUTE } from '@sogebot/ui-helpers/constants';
import { setLocale } from '@sogebot/ui-helpers/dayjsHelper';
import gitCommitInfo from 'git-commit-info';
import {
capitalize,
get, isNil,
} from 'lodash';
import { getConnection, getRepository } from 'typeorm';
import type { Command } from '../d.ts/src/general';
import { menu } from './helpers/panel';
import Core from '~/_interface';
import { PermissionCommands } from '~/database/entity/permissions';
import {
command, default_permission, settings, ui,
} from '~/decorators';
import {
onChange, onLoad, onStartup,
} from '~/decorators/on';
import { isStreamOnline } from '~/helpers/api';
import { refreshCachedCommandPermissions } from '~/helpers/cache';
import { setValue } from '~/helpers/general';
import { setLang } from '~/helpers/locales';
import {
debug, error, warning,
} from '~/helpers/log';
import { socketsConnected } from '~/helpers/panel/index';
import { addUIWarn } from '~/helpers/panel/index';
import { defaultPermissions } from '~/helpers/permissions/index';
import { list } from '~/helpers/register';
import { adminEndpoint } from '~/helpers/socket';
import { getMuteStatus } from '~/helpers/tmi/muteStatus';
import translateLib, { translate } from '~/translate';
import { variables } from '~/watchers';
let threadStartTimestamp = Date.now();
let isInitialLangSet = true;
const gracefulExit = () => {
if (general.gracefulExitEachXHours > 0) {
debug('thread', 'gracefulExit::check');
if (Date.now() - threadStartTimestamp >= general.gracefulExitEachXHours * HOUR) {
if (!isStreamOnline.value && socketsConnected === 0) {
warning('Gracefully exiting sogeBot as planned and configured in UI in settings->general.');
debug('thread', 'gracefulExit::exiting and creating restart file (so we dont have startup logging');
writeFileSync('~/restart.pid', ' ');
process.exit(0);
} else {
debug('thread', 'gracefulExit::Gracefully exiting process skipped, stream online - moved by 15 minutes');
// if stream is online move exit by hour
threadStartTimestamp += 15 * MINUTE;
}
}
} else {
threadStartTimestamp = Date.now();
}
};
class General extends Core {
@settings('graceful_exit')
gracefulExitEachXHours = 0;
@settings('general')
@ui({
type: 'selector', values: () => {
const f = readdirSync('./locales/');
return [...new Set(f.map((o) => o.split('.')[0]))];
},
})
lang = 'en';
@settings('general')
numberFormat = '';
@onStartup()
onStartup() {
this.addMenu({
name: 'index', id: '', this: this,
});
this.addMenu({
category: 'commands', name: 'botcommands', id: 'commands/botcommands', this: this,
});
this.addMenu({
category: 'settings', name: 'modules', id: 'settings/modules', this: null,
});
this.addMenuPublic({ name: 'index', id: '' });
setInterval(gracefulExit, 1000);
}
sockets() {
adminEndpoint('/core/general', 'menu::private', async (cb) => {
cb(menu.map((o) => ({
category: o.category, name: o.name, id: o.id, enabled: o.this ? o.this.enabled : true,
})));
});
adminEndpoint('/core/general', 'generic::getCoreCommands', async (cb) => {
try {
const commands: Command[] = [];
for (const type of ['overlays', 'integrations', 'core', 'systems', 'games', 'services', 'registries']) {
for (const system of list(type)) {
for (const cmd of system._commands) {
const name = typeof cmd === 'string' ? cmd : cmd.name;
commands.push({
id: cmd.id,
defaultValue: name,
command: cmd.command ?? name,
type: capitalize(type),
name: system.__moduleName__,
permission: await new Promise((resolve: (value: string | null) => void) => {
getRepository(PermissionCommands).findOneOrFail({ name })
.then(data => {
resolve(data.permission);
})
.catch(() => {
resolve(cmd.permission ?? null);
});
}),
});
}
}
}
cb(null, commands);
} catch (e: any) {
cb(e, []);
}
});
adminEndpoint('/core/general', 'generic::setCoreCommand', async (commandToSet, cb) => {
// get module
const module = list(commandToSet.type.toLowerCase()).find(item => item.__moduleName__ === commandToSet.name);
if (!module) {
throw new Error(`Module ${commandToSet.name} not found`);
}
const moduleCommand = module._commands.find((o) => o.name === commandToSet.defaultValue);
if (!moduleCommand) {
throw new Error(`Command ${commandToSet.defaultValue} not found in module ${commandToSet.name}`);
}
// handle permission
if (commandToSet.permission === moduleCommand.permission) {
await getRepository(PermissionCommands).delete({ name: moduleCommand.name });
} else {
await getRepository(PermissionCommands).save({
...(await getRepository(PermissionCommands).findOne({ name: moduleCommand.name })),
name: moduleCommand.name,
permission: commandToSet.permission,
});
}
// handle new command value
module.setCommand(commandToSet.defaultValue, commandToSet.command);
refreshCachedCommandPermissions();
cb(null);
});
}
@command('!enable')
@default_permission(defaultPermissions.CASTERS)
public async enable(opts: CommandOptions) {
this.setStatus({ ...opts, enable: true });
}
@command('!disable')
@default_permission(defaultPermissions.CASTERS)
public async disable(opts: CommandOptions) {
this.setStatus({ ...opts, enable: false });
}
@onChange('lang')
@onLoad('lang')
public async onLangUpdate() {
if (!translateLib.isLoaded) {
setTimeout(() => this.onLangUpdate(), 10);
return;
}
if (!(await translateLib.check(this.lang))) {
warning(`Language ${this.lang} not found - fallback to en`);
this.lang = 'en';
} else {
setLocale(this.lang);
setLang(this.lang);
warning(translate('core.lang-selected'));
if (!isInitialLangSet) {
addUIWarn({ name: 'UI', message: translate('core.lang-selected') + '. ' + translate('core.refresh-panel') });
}
isInitialLangSet = false;
}
}
public async onLangLoad() {
await translateLib._load();
}
@command('!_debug')
@default_permission(defaultPermissions.CASTERS)
public async debug(opts: CommandOptions): Promise<CommandResponse[]> {
const connection = await getConnection();
const lang = this.lang;
const enabledSystems: {
systems: string[];
games: string[];
integrations: string[];
} = {
systems: [], games: [], integrations: [],
};
for (const category of ['systems', 'games', 'integrations']) {
for (const system of list(category)) {
const enabled = system.enabled;
const areDependenciesEnabled = system.areDependenciesEnabled;
const isDisabledByEnv = !isNil(process.env.DISABLE) && (process.env.DISABLE.toLowerCase().split(',').includes(system.__moduleName__.toLowerCase()) || process.env.DISABLE === '*');
if (!enabled) {
enabledSystems[category as 'systems' | 'games' | 'integrations'].push('-' + system.__moduleName__);
} else if (!areDependenciesEnabled) {
enabledSystems[category as 'systems' | 'games' | 'integrations'].push('-dep-' + system.__moduleName__);
} else if (isDisabledByEnv) {
enabledSystems[category as 'systems' | 'games' | 'integrations'].push('-env-' + system.__moduleName__);
} else {
enabledSystems[category as 'systems' | 'games' | 'integrations'].push(system.__moduleName__);
}
}
}
const botUsername = variables.get('services.twitch.botUsername') as string;
const broadcasterUsername = variables.get('services.twitch.broadcasterUsername') as string;
const botId = variables.get('services.twitch.botId') as string;
const broadcasterId = variables.get('services.twitch.broadcasterId') as string;
const version = get(process, 'env.npm_package_version', 'x.y.z');
debug('*', '======= COPY DEBUG MESSAGE FROM HERE =======');
debug('*', `GENERAL | OS: ${process.env.npm_config_user_agent}`);
debug('*', ` | Bot version: ${version.replace('SNAPSHOT', gitCommitInfo().shortHash || 'SNAPSHOT')}`);
debug('*', ` | DB: ${connection.options.type}`);
debug('*', ` | HEAP: ${Number(process.memoryUsage().heapUsed / 1048576).toFixed(2)} MB`);
debug('*', ` | Uptime: ${new Date(1000 * process.uptime()).toISOString().substr(11, 8)}`);
debug('*', ` | Language: ${lang}`);
debug('*', ` | Mute: ${getMuteStatus()}`);
debug('*', `SYSTEMS | ${enabledSystems.systems.join(', ')}`);
debug('*', `GAMES | ${enabledSystems.games.join(', ')}`);
debug('*', `INTEGRATIONS | ${enabledSystems.integrations.join(', ')}`);
debug('*', `OAUTH | BOT ${botUsername}#${botId} | BROADCASTER ${broadcasterUsername}#${broadcasterId}`);
debug('*', '======= END OF DEBUG MESSAGE =======');
return [];
}
@command('!ping')
ping(opts: CommandOptions): CommandResponse[] {
if (opts.discord) {
const response = `$sender, Pong! \`${Date.now() - opts.createdAt}ms\``;
return [{ response, ...opts }];
} else {
const response = `$sender, Pong! ${Date.now() - opts.createdAt}ms`;
return [{ response, ...opts }];
}
}
@command('!set')
@default_permission(defaultPermissions.CASTERS)
public async setValue(opts: CommandOptions) {
return setValue(opts);
}
private async setStatus(opts: CommandOptions & { enable: boolean }) {
if (opts.parameters.trim().length === 0) {
return;
}
try {
const [type, name] = opts.parameters.split(' ');
if (type !== 'system' && type !== 'game') {
throw new Error('Not supported');
}
let found = false;
for (const system of list(type + 's')) {
system.status({ state: opts.enable });
found = true;
break;
}
if (!found) {
throw new Error(`Not found - ${type}s - ${name}`);
}
} catch (e: any) {
error(e.stack);
}
}
}
const general = new General();
export default general;