-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
796 lines (738 loc) · 29.8 KB
/
main.js
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
const { ChromaApp, Color, Key, BcaAnimation, DeviceType } = require('@chroma-cloud/chromajs')
const { app, Menu, Tray, BrowserWindow, ipcMain, shell } = require('electron')
const autoUpdater = require('electron-updater').autoUpdater
autoUpdater.logger = require('electron-log')
autoUpdater.logger.transports.file.level = "info"
const path = require('path')
var fs = require('fs')
const WindowsToaster = require('node-notifier').WindowsToaster
var log = require('electron-log')
var childProcess = require('child_process')
const DiscordRPC = require('discord-rpc')
const processExists = require('process-exists')
const express = require('express')
const axios = require('axios').default
const querystring = require('querystring')
const webserver = express()
const port = 1608
let client
var DiscordRP = null;
let isClosing = false
let win = null;
let tray = null;
var debugerror = 0;
var error1 = 0;
var warn1 = 0;
var urError = 0;
var ECONNRESET = 0;
var color_var = 16777215;
const discordProcessNames = [
'Discord.exe',
'DiscordPTB.exe',
'DiscordCanary.exe',
'DiscordDevelopment.exe',
]
var spamProtection = false;
//make sure that userdata folder is present
if (!fs.existsSync(app.getPath(`userData`))) {
fs.mkdirSync(app.getPath(`userData`))
}
//save icon to userData for later reference
if (!fs.existsSync(path.join(app.getPath(`userData`), 'logo.png'))) {
fs.writeFileSync(path.join(app.getPath(`userData`), 'logo.png'), fs.readFileSync(path.join(__dirname, 'img/logo.png')))
}
//save config to userData for later reference
var config;
if (!fs.existsSync(path.join(app.getPath(`userData`), 'config.json'))) {
config = {
autoStart: false,
}
fs.writeFileSync(path.join(app.getPath(`userData`), 'config.json'), JSON.stringify(config))
} else {
config = JSON.parse(fs.readFileSync(path.join(app.getPath(`userData`), 'config.json')));
}
function saveConfig(_config) {
fs.writeFileSync(path.join(app.getPath(`userData`), 'config.json'), JSON.stringify(_config ? _config : config))
}
//initiate log.txt
log.transports.file.appName = 'DiscordChroma';
log.transports.file.level = 'info';
log.transports.file.format = '[{h}:{i}:{s}:{ms}] [{level}] {text}';
log.transports.file.maxSize = 5 * 1024 * 1024;
log.transports.file.file = path.join(app.getPath(`userData`), 'log.txt');
log.transports.file.streamConfig = { flags: 'w' };
log.transports.file.stream = fs.createWriteStream(path.join(app.getPath(`userData`), 'log.txt'));
// Register the app
const chroma = new ChromaApp(
'DiscordChroma', // app name
'discord integration for razer chroma (unofficial)', // description
'DELUUXE', // author
'https://deluuxe.dev/discordchroma', // email
[
DeviceType.ChromaLink,
DeviceType.Headset,
DeviceType.Keypad,
DeviceType.Keyboard,
DeviceType.Mouse,
DeviceType.Mousepad
],
'application',
true, // secure
true // ws
)
/*chroma.Instance().then((instance) => {
//instance.playAnimation(new BcaAnimation("BcaAnimations/animation.bca"));
instance.setAll(new Color(255, 255, 255));
instance.send();
setTimeout(function() {
instance.destroy();
}, 5000);
});*/
//set sleep function for async
function sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
// ------------------------------- define repeating windows ----------------------------- \\
function openSettingsWin() {
DiscordRPsettings = childProcess.fork(path.join(__dirname, '/discord-rich-presence/DiscordRP-settings.js'))
let settingswin = new BrowserWindow({
width: 1000,
height: 600,
frame: false,
resizable: true,
minHeight: 600,
minWidth: 1000,
webPreferences: {
preload: path.join(__dirname, '/settings-preload.js')
}
})
settingswin.loadURL(path.join('file://', __dirname, '/settings.html'))
settingswin.on('closed', () => {
DiscordRPsettings.kill()
if (!isClosing) {
var notifier = new WindowsToaster({
withFallback: false, // Fallback to Growl or Balloons?
})
notifier.notify({
title: 'Running in the background',
message: 'To open the settings, click on the taskbar icon',
icon: path.join(app.getPath(`userData`), 'logo.png'),
sound: false, // Bool | String (as defined by http://msdn.microsoft.com/en-us/library/windows/apps/hh761492.aspx)
wait: true, // Bool. Wait for User Action against Notification or times out
appID: "com.deluuxe.DiscordChroma",
})
}
})
}
// ------------------------------------ start program ----------------------------------- \\
//when the program is successfully started
app.on('ready', function () {
//force single instance
let isSingleInstance = app.requestSingleInstanceLock()
if (!isSingleInstance) {
let alreadyrunningwin = new BrowserWindow({ width: 1000, height: 600, frame: false });
alreadyrunningwin.loadURL(path.join('file://', __dirname, '/alreadyrunning.html'));
log.info('DiscordChroma was already running.');
setTimeout(function () {
app.quit();
return;
}, 5000);
} else {
log.info("checking for updates");
autoUpdater.checkForUpdatesAndNotify();
autoUpdater.on('update-downloaded', () => {
let updatewin = new BrowserWindow({ width: 1000, height: 600, frame: false });
updatewin.loadURL(path.join('file://', __dirname, '/update.html'));
log.info("updated downloaded");
setTimeout(function () {
log.info("restarting to install update");
autoUpdater.quitAndInstall();
}, 4000);
});
log.info("starting DiscordChroma");
//show discordchroma rich presence
/*var invoked = false;*/
DiscordRP = childProcess.fork(path.join(__dirname, '/discord-rich-presence/DiscordRP-start.js'))
//show splash/loading screen
win = new BrowserWindow({ width: 1000, height: 600, frame: false, show: false });
win.loadURL(path.join('file://', __dirname, '/main.html'));
//makes tray icon for closing and managing the program
tray = new Tray(path.join(__dirname, '/img/icon.ico'))
const openSettingsTrayClickHandler = () => {
openSettingsWin()
}
const restartTrayClickHandler = () => {
log.info("restart requested")
isClosing = true
app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) })
log.info("closing DiscordChroma")
//show thx window
let thxwin = new BrowserWindow({ width: 1000, height: 600, frame: false })
thxwin.loadURL(path.join('file://', __dirname, '/thx.html'))
tray.destroy()
//plays shutdown animation and exit's app at ending
shutdownAnimation()
}
const exitTrayClickHandler = () => {
isClosing = true
setTimeout(() => {
log.info("closing DiscordChroma")
const DiscordRPend = childProcess.fork(path.join(__dirname, '/discord-rich-presence/DiscordRP-end.js'))
//show thx window
let thxwin = new BrowserWindow({ width: 1000, height: 600, frame: false });
thxwin.loadURL(path.join('file://', __dirname, '/thx.html'));
tray.destroy();
//plays shutdown animation and exit's app at ending
shutdownAnimation(DiscordRPend);
}, 500)
}
const contextMenu = Menu.buildFromTemplate([
{ label: 'Settings', click: openSettingsTrayClickHandler },
{ label: 'Restart', click: restartTrayClickHandler },
{ label: 'Exit', click: exitTrayClickHandler },
])
tray.setToolTip('DiscordChroma (click to open settings)')
tray.setContextMenu(contextMenu)
tray.on('click', () => {
openSettingsWin()
})
const { powerMonitor } = require('electron')
// pause app when pc is suspended
powerMonitor.on('suspend', () => {
console.log('The system is going to sleep')
if (client) {
client.destroy()
client = null
}
})
// resume app (reconnect to discord) when pc is resumed
powerMonitor.on('resume', () => {
console.log('The system is resuming from sleep')
if (isDiscordRunning && !waitingForDiscordStart && !client) {
initDiscord()
}
})
powerMonitor.on('lock-screen', () => {
console.log('The system is getting locked')
if (client) {
client.destroy()
client = null
}
})
powerMonitor.on('unlock-screen', () => {
console.log('The system is getting unlocked')
if (isDiscordRunning && !waitingForDiscordStart && !client) {
initDiscord()
}
})
win.on("ready-to-show", () => {
win.show();
//show startup animation on razer chroma
startupAnimation();
setTimeout(function () {
//hide loading/splash window
DiscordRP.kill('SIGINT')
win.hide()
if (config.clientID && config.clientSecret) {
//start discord init process
initDiscord()
} else {
let login = new BrowserWindow({
width: 1000,
height: 700,
show: false,
frame: false,
resizable: false,
webPreferences: {
nodeIntegration: true
}
})
login.loadURL(path.join('file://', __dirname, '/login.html'))
login.show()
login.on('closed', () => {
if (config.clientID && config.clientSecret) {
if (!isClosing) {
initDiscord()
}
} else {
if (!isClosing) {
login = new BrowserWindow({
width: 1000,
height: 700,
show: false,
frame: false,
resizable: false,
webPreferences: {
nodeIntegration: true
}
})
login.loadURL(path.join('file://', __dirname, '/login.html'))
login.show()
}
}
})
}
}, 6000);
});
}
});
let isDiscordRunning = true
let waitingForDiscordStart = true
setInterval(async () => {
if (!waitingForDiscordStart) {
let processes = await processExists.filterExists(discordProcessNames).catch((err) => {
log.error(err)
let errorwin = new BrowserWindow({ width: 1000, height: 600, frame: false })
errorwin.loadURL(path.join('file://', __dirname, '/error.html'))
errorwin.on('closed', function () {
app.exit()
})
})
isDiscordRunning = processes.length > 0 ? true : false
if (isDiscordRunning == false && client) {
console.log('discord got closed')
if (client) {
client.destroy()
client = null
}
} else if (isDiscordRunning && !waitingForDiscordStart && !client) {
console.log('discord got opened again after it was closed')
initDiscord()
}
}
}, 5000)
// initDiscord function
async function initDiscord() {
if (!isDiscordRunning && waitingForDiscordStart) { return }
waitingForDiscordStart = true
let processes = await processExists.filterExists(discordProcessNames).catch((err) => {
log.error(err)
let errorwin = new BrowserWindow({ width: 1000, height: 600, frame: false })
errorwin.loadURL(path.join('file://', __dirname, '/error.html'))
errorwin.on('closed', function () {
app.exit()
})
})
while (processes.length == 0) {
isDiscordRunning = false
waitingForDiscordStart = true
await sleep(2000)
processes = await processExists.filterExists(discordProcessNames).catch((err) => {
log.error(err)
let errorwin = new BrowserWindow({ width: 1000, height: 600, frame: false })
errorwin.loadURL(path.join('file://', __dirname, '/error.html'))
errorwin.on('closed', function () {
app.exit()
})
})
}
console.log('discord is running')
isDiscordRunning = true
waitingForDiscordStart = false
client = new DiscordRPC.Client({ transport: "ipc" })
client.on('ready', () => {
log.info(`Logged in as ${client.user.username}#${client.user.discriminator}`);
var notifier = new WindowsToaster({
withFallback: false, // Fallback to Growl or Balloons?
});
//show running notification / connected to discord notification
notifier.notify(
{
title: 'Connected to discord',
message: 'To open the main menu click here or on the tray icon in the taskbar',
icon: path.join(app.getPath(`userData`), 'logo.png'),
sound: false, // Bool | String (as defined by http://msdn.microsoft.com/en-us/library/windows/apps/hh761492.aspx)
wait: true, // Bool. Wait for User Action against Notification or times out
appID: "com.deluuxe.DiscordChroma",
},
function (error, response) {
if (response == "the user clicked on the toast.") {
openSettingsWin()
}
}
)
//RPC notification event
client.subscribe('NOTIFICATION_CREATE', (message) => {
const regex = /\((\#\S+), ?([\S\s]+)\)/g
if (regex.test(message.title)) { //guild message
if (spamProtection == false) {
log.info('NEW MESSAGE, title: ' + message.title + ".");
spamProtection = true;
messageAnimation();
} else {
log.info('NEW MESSAGE, title: ' + message.title + ", but ignored due to spam protection.");
}
} else {
if (spamProtection == false) {
log.info('NEW DM');
spamProtection = true;
dmAnimation();
} else {
log.info('NEW DM, but ignored due to spam protection.');
}
}
// console.log('new message', message)
})
})
// ---------------------------------- discord.js ERROR section --------------------------------- \\
client.on('error', err => {
error1 = error1 + 1;
if (error1 == 1) {
log.info("There has been an error!");
log.error(err);
//show error window
let errorwin = new BrowserWindow({ width: 1000, height: 600, frame: false });
errorwin.loadURL(path.join('file://', __dirname, '/error.html'));
errorwin.on('closed', function () {
app.exit();
});
}
})
client.on('disconnected', (e) => {
log.info('discord disconnected', e)
isDiscordRunning = false
if (client) {
client.destroy()
client = null
}
})
client.on('warn', () => {
warn1 = warn1 + 1;
if (warn1 == 1) {
log.warn("There has been a warning/error!");
//show error window
let errorwin = new BrowserWindow({ width: 1000, height: 600, frame: false });
errorwin.loadURL(path.join('file://', __dirname, '/error.html'));
errorwin.on('closed', function () {
app.exit();
});
}
})
// ---------------------------------------- END discord.js ERROR section -------------------------------- \\
authDiscord()
}
function fullAuthDiscord() {
// client.login({ clientId: config.clientID, scopes: ['identify', 'messages.read', 'rpc', 'rpc.notifications.read'], clientSecret: config.clientSecret }).catch(async (e) => {
client.login({ clientId: config.clientID, scopes: ['identify', 'rpc.notifications.read', 'rpc'], clientSecret: config.clientSecret, redirectUri: 'http://localhost:1608/rzr-discord-chroma-callback' }).catch(async (e) => {
log.error(e)
if (e.message.includes('access_denied')) {
var notifier = new WindowsToaster({
withFallback: false, // Fallback to Growl or Balloons?
})
//show error notification
notifier.notify({
title: 'Unable to connect to discord',
message: 'click here to try again\nOr check if your client id and secret are still correct in the DiscordChroma settings',
icon: path.join(app.getPath(`userData`), 'logo.png'),
sound: true, // Bool | String (as defined by http://msdn.microsoft.com/en-us/library/windows/apps/hh761492.aspx)
wait: true, // Bool. Wait for User Action against Notification or times out
appID: "com.deluuxe.DiscordChroma",
}, (err, response) => {
if (err) {
let errorwin = new BrowserWindow({ width: 1000, height: 600, frame: false });
errorwin.loadURL(path.join('file://', __dirname, '/error.html'));
errorwin.on('closed', function () {
app.exit()
})
return
}
if (response == 'the user clicked on the toast.') {
authDiscord()
}
})
} else if (e.message.includes('Unknown error occurred')) {
log.warn('Discord has returned Error: 1000 "Unknown error occurred", attempting web login.')
shell.openExternal(`https://discordapp.com/api/oauth2/authorize?client_id=${config.clientID}&redirect_uri=http%3A%2F%2Flocalhost%3A1608%2Frzr-discord-chroma-callback&response_type=code&scope=rpc.notifications.read%20rpc%20identify`)
webserver.get('/rzr-discord-chroma-callback', (req, res) => {
if (req.query.code) {
const data = {
code: req.query.code,
'client_id': config.clientID,
'grant_type': 'access_token',
'redirect_uri': 'http%3A%2F%2Flocalhost%3A1608%2Frzr-discord-chroma-callback'
}
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: querystring.stringify(data),
url: 'https://discordapp.com/api/oauth2/token'
}
axios(options)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
} else if (req.query['access_token']) {
config.accessToken = req.query['access_token']
saveConfig()
authDiscord()
} else {
log.warn('Request didn\'t contain access-token or auth code, ignoring...')
}
res.send('OK')
webserver.destroy()
})
webserver.listen(port, () => log.info(`webserver listening on port ${port}`))
return
} else if (e.message.includes('Could not connect')) {
log.warn('Discord was not yet loaded or was not running, atempting again in 2 seconds')
await sleep(2000)
initDiscord()
return
} else {
let errorwin = new BrowserWindow({ width: 1000, height: 600, frame: false });
errorwin.loadURL(path.join('file://', __dirname, '/error.html'));
errorwin.on('closed', function () {
app.exit()
})
}
}).then(clientInfo => {
if (clientInfo && clientInfo.accessToken) {
config.accessToken = clientInfo.accessToken
saveConfig()
} else {
if (client && client.clientId) return
log.warn('no client info received, cannot login, there is likely more logging above')
}
})
}
function authDiscord() {
const prevAccessToken = config.accessToken
if (prevAccessToken) {
client.login({ clientId: config.clientID, scopes: ['identify', 'rpc.notifications.read', 'rpc'], clientSecret: config.clientSecret, redirectUri: 'http://localhost:1608/rzr-discord-chroma-callback', accessToken: prevAccessToken }).catch(async e => {
if (e && e.message) {
log.error(e)
if (e.message.includes('Invalid access token')) {
console.error('accesstoken invalid, performing a full auth')
fullAuthDiscord()
} else if (e.message.includes('Could not connect')) {
log.warn('Discord was not yet loaded or was not running, atempting again in 2 seconds')
await sleep(2000)
initDiscord()
return
} else if (e.message.includes('access_denied')) {
var notifier = new WindowsToaster({
withFallback: false, // Fallback to Growl or Balloons?
})
//show error notification
notifier.notify({
title: 'Unable to connect to discord',
message: 'click here to try again\nOr check if your client id and secret are still correct in the DiscordChroma settings',
icon: path.join(app.getPath(`userData`), 'logo.png'),
sound: true, // Bool | String (as defined by http://msdn.microsoft.com/en-us/library/windows/apps/hh761492.aspx)
wait: true, // Bool. Wait for User Action against Notification or times out
appID: "com.deluuxe.DiscordChroma",
}, (err, response) => {
if (err) {
let errorwin = new BrowserWindow({ width: 1000, height: 600, frame: false });
errorwin.loadURL(path.join('file://', __dirname, '/error.html'));
errorwin.on('closed', function () {
app.exit()
})
return
}
if (response == 'the user clicked on the toast.') {
authDiscord()
}
})
} else {
let errorwin = new BrowserWindow({ width: 1000, height: 600, frame: false });
errorwin.loadURL(path.join('file://', __dirname, '/error.html'));
errorwin.on('closed', function () {
app.exit()
})
}
} else {
log.warn('A discord login error occurred, but there is no error message, attempting again in 2 seconds')
await sleep(2000)
initDiscord()
return
}
})
} else {
fullAuthDiscord()
}
}
ipcMain.handle('settings-win-init', async (event) => {
return JSON.stringify(config)
})
ipcMain.on('asynchronous-message', (event, arg, arg1) => {
//functions
if (arg == "msgcolor") {
log.info("changed messagecolor to " + arg1);
} else if (arg == "restart") {
log.info("restart requested");
app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) })
log.info("closing DiscordChroma");
//show thx window
let thxwin = new BrowserWindow({ width: 1000, height: 600, frame: false });
thxwin.loadURL(path.join('file://', __dirname, '/thx.html'));
tray.destroy();
//plays shutdown animation and exit's app at ending
shutdownAnimation();
} else if (arg == "setting-client-id") {
log.info("changed client id to " + arg1)
config.clientID = arg1
saveConfig()
} else if (arg == "setting-client-secret") {
log.info("changed client secret")
config.clientSecret = arg1
saveConfig()
} else if (arg == "setAutoLaunchState") {
if (arg1) {
app.setLoginItemSettings({
openAtLogin: true,
args: [
'--process-start-args', `"--hidden"`
]
})
config.autoStart = true
saveConfig()
} else {
app.setLoginItemSettings({
openAtLogin: false,
})
config.autoStart = false
saveConfig()
}
} else if (arg == "exitapp") {
isClosing = true
setTimeout(() => {
log.info("closing DiscordChroma")
const DiscordRPend = childProcess.fork(path.join(__dirname, '/discord-rich-presence/DiscordRP-end.js'))
//show thx window
let thxwin = new BrowserWindow({ width: 1000, height: 600, frame: false });
thxwin.loadURL(path.join('file://', __dirname, '/thx.html'));
tray.destroy();
//plays shutdown animation and exit's app at ending
shutdownAnimation(DiscordRPend);
}, 500)
}
});
async function shutdownAnimation(DiscordRPend) {
let instance = await chroma.Instance();
var b = 0;
for (g = 255; g > 125; g--) {
instance.setAll(new Color(0, g, b));
await instance.send();
b++;
await sleep(8);
}
for (b; b > 0; b--) {
instance.setAll(new Color(0, g, b));
await instance.send();
if (!g <= 0) {
g--;
}
await sleep(8);
}
setTimeout(function () {
if (DiscordRPend) {
DiscordRPend.kill('SIGINT')
}
instance.destroy();
app.exit();
}, 2300);
}
async function startupAnimation() {
let instance = await chroma.Instance();
var b = 0;
var r = 0;
for (g = 255; g > 125; g--) {
instance.setAll(new Color(r, g, b));
await instance.send();
b++;
await sleep(8);
}
for (r; r < 125; r++) {
instance.setAll(new Color(r, g, b));
await instance.send();
if (!g <= 0) {
g--;
}
await sleep(8);
}
instance.setAll(new Color(0, 0, 0))
await instance.send()
instance.destroy();
}
async function dmAnimation() {
let instance = await chroma.Instance()
var r = 0
var i = 0
for (i; i < 2; i++) {
for (r; r < 255; r++) {
instance.setAll(new Color(r, 0, 0))
instance.send()
await sleep(2)
}
for (r; r > 0; r--) {
instance.setAll(new Color(r, 0, 0))
instance.send()
await sleep(2)
}
}
instance.setAll(new Color(0, 0, 0))
await instance.send()
await instance.destroy()
await sleep(250)
spamProtection = false
}
async function messageAnimation() {
let instance = await chroma.Instance();
instance.playAnimation(new BcaAnimation(path.join(__dirname, '/BcaAnimations/message.bca')));
var r = 0;
var i = 0;
for (i; i < 3; i++) {
for (r; r < 255; r++) {
if (r % 10 === 0) {
instance.Mouse.setAll(new Color(0, 0, r));
instance.Mousepad.setAll(new Color(0, 0, r));
instance.ChromaLink.setAll(new Color(0, 0, r));
instance.Headset.setAll(new Color(0, 0, r));
instance.Keypad.setAll(new Color(0, 0, r));
instance.send();
}
await sleep(1);
}
for (r; r > 0; r--) {
if (r % 10 === 0) {
instance.Mouse.setAll(new Color(0, 0, r));
instance.Mousepad.setAll(new Color(0, 0, r));
instance.ChromaLink.setAll(new Color(0, 0, r));
instance.Headset.setAll(new Color(0, 0, r));
instance.Keypad.setAll(new Color(0, 0, r));
instance.send();
}
await sleep(1);
}
}
instance.setAll(new Color(0, 0, 0))
await instance.send()
await sleep(10)
await instance.destroy()
await sleep(250)
spamProtection = false
}
//when a "global" error occurs
process.on('unhandledRejection', err => {
var errorcode = err.toString();
if (!errorcode.includes("chromasdk/heartbeat failed")) {
urError = urError + 1;
if (urError == 1) {
log.info("There has been an error!");
log.error(err);
//show succesfully started window
let errorwin = new BrowserWindow({ width: 1000, height: 600, frame: false });
errorwin.loadURL(path.join('file://', __dirname, '/error.html'));
errorwin.on('closed', function () {
app.exit();
});
}
} else {
log.info(err);
log.info("but continued as this is error is not a problem");
}
});