-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathindex.js
2455 lines (2076 loc) · 72.3 KB
/
index.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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fs = require('fs');
const os = require('os');
const mp3Duration = require('mp3-duration');
const path = require('path');
const GTTS = require('gtts'); // Import the gtts library
const config = require('nconf')
const winston = require('winston')
const Spotify = require('./spotify')
const utils = require('./utils')
const process = require('process')
const parseString = require('xml2js').parseString
const http = require('http')
const gongMessage = fs.readFileSync('gong.txt', 'utf8').split('\n').filter(Boolean);
const voteMessage = fs.readFileSync('vote.txt', 'utf8').split('\n').filter(Boolean);
const ttsMessage = fs.readFileSync('tts.txt', 'utf8').split('\n').filter(Boolean);
const buildNumber = Number(fs.readFileSync('build.txt', 'utf8').split('\n').filter(Boolean)[0]);
const { execSync } = require('child_process');
const gongBannedTracks = {};
const SLACK_API_URL_LIST = 'https://slack.com/api/conversations.list';
const userActionsFile = path.join(__dirname, 'config/userActions.json');
config.argv()
.env()
.file({
file: 'config/config.json'
})
.defaults({
adminChannel: 'music-admin',
standardChannel: 'music',
gongLimit: 3,
voteImmuneLimit: 3,
voteLimit: 3,
flushVoteLimit: 6,
maxVolume: '75',
market: 'US',
blacklist: [],
searchLimit: 7,
webPort: 8181,
logLevel: 'info'
})
// const adminChannel = config.get('adminChannel');
const gongLimit = config.get('gongLimit')
const voteImmuneLimit = config.get('voteImmuneLimit')
const voteLimit = config.get('voteLimit')
const flushVoteLimit = config.get('flushVoteLimit')
const token = config.get('token')
const maxVolume = config.get('maxVolume')
const market = config.get('market')
const voteTimeLimitMinutes = config.get('voteTimeLimitMinutes')
const clientId = config.get('spotifyClientId')
const clientSecret = config.get('spotifyClientSecret')
const searchLimit = config.get('searchLimit')
const logLevel = config.get('logLevel')
const sonosIp = config.get('sonos')
const webPort = config.get('webPort')
let ipAddress = config.get('ipAddress')
let blacklist = config.get('blacklist')
if (!Array.isArray(blacklist)) {
blacklist = blacklist.replace(/\s*(,|^|$)\s*/g, '$1').split(/\s*,\s*/)
}
/* Initialize Logger */
const logger = winston.createLogger({
level: logLevel,
format: winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), // Add timestamp
winston.format.json()
),
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), // Add timestamp to console logs
winston.format.printf(({ timestamp, level, message }) => {
return `[${timestamp}] ${level}: ${message}`;
})
)
})
]
});
/* Initialize Sonos */
const SONOS = require('sonos')
const Sonos = SONOS.Sonos
const sonos = new Sonos(sonosIp)
if (market !== 'US') {
sonos.setSpotifyRegion(SONOS.SpotifyRegion.EU)
logger.info('Setting Spotify region to EU...')
logger.info('Market is: ' + market)
}
/* Initialize Spotify instance */
const spotify = Spotify({
clientId: clientId,
clientSecret: clientSecret,
market: market,
logger: logger
})
let gongCounter = 0
let gongScore = {}
const gongLimitPerUser = 1
let voteImmuneCounter = 0
const voteImmuneLimitPerUser = 1
let voteImmuneScore = {}
let gongBanned = false
let gongTrack = '' // What track was a GONG called on
let voteCounter = 0
const voteLimitPerUser = 4
const flushVoteLimitPerUser = 1
let voteScore = {}
let flushVoteScore = {}
if (!token) {
throw new Error('SLACK_API_TOKEN is not set');
}
const { RTMClient } = require('@slack/rtm-api');
const { WebClient } = require('@slack/web-api');
const rtm = new RTMClient(token, {
logLevel: 'error',
dataStore: false,
autoReconnect: true,
autoMark: true
});
const web = new WebClient(token);
let botUserId;
(async () => {
try {
// Fetch the bot's user ID
const authResponse = await web.auth.test();
botUserId = authResponse.user_id;
await rtm.start();
} catch (error) {
logger.error(`Error starting RTMClient: ${error}`);
}
})();
rtm.on('message', (event) => {
// Ignore messages from the bot itself
if (event.user === botUserId) {
return;
}
const { type, ts, text, channel, user } = event;
logger.info(event.text);
logger.info(event.channel);
logger.info(event.user);
logger.info(`Received: ${type} ${channel} <@${user}> ${ts} "${text}"`);
if (type !== 'message' || !text || !channel) {
const errors = [
type !== 'message' ? `unexpected type ${type}.` : null,
!text ? 'text was undefined.' : null,
!channel ? 'channel was undefined.' : null
].filter(Boolean).join(' ');
logger.error(`Could not respond. ${errors}`);
return false;
}
processInput(text, channel, `<@${user}>`);
});
rtm.on('error', (error) => {
logger.error(`RTMClient error: ${error}`);
});
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Proper delay function
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Function to fetch the channel IDs
async function _lookupChannelID() {
let allChannels = [];
let nextCursor;
let retryAfter = 0;
let backoff = 1; // Exponential backoff starts at 1 second
try {
do {
// Wait if rate limited
if (retryAfter > 0) {
logger.warn(`Rate limit hit! Retrying after ${retryAfter} seconds...`);
logger.info(`Wait start: ${new Date().toISOString()}`);
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
retryAfter = 0; // Reset retryAfter
}
// Fetch channels
const url = `${SLACK_API_URL_LIST}?limit=1000&types=public_channel,private_channel${nextCursor ? `&cursor=${nextCursor}` : ''}`;
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
logger.info(`Response status for fetching channels: ${response.status}`);
if (response.status === 429) {
retryAfter = parseInt(response.headers.get('retry-after')) || backoff;
backoff = Math.min(backoff * 2, 60); // Exponential backoff up to 60s
continue;
}
const data = await response.json();
if (!data.ok) throw new Error(`Slack API Error: ${data.error}`);
// Extract and add channels
if (data.channels) allChannels = allChannels.concat(data.channels);
nextCursor = data.response_metadata?.next_cursor;
// Reset backoff after successful response
backoff = 1;
} while (nextCursor);
logger.info('Fetched channels: ' + allChannels.map(channel => channel.name).join(', '));
// Fetch Admin and Standard channel IDs
const adminChannelName = config.get('adminChannel').replace('#', '');
const standardChannelName = config.get('standardChannel').replace('#', '');
logger.info('Admin channel (in config): ' + adminChannelName);
logger.info('Standard channel (in config): ' + standardChannelName);
const adminChannelInfo = allChannels.find(channel => channel.name === adminChannelName);
if (!adminChannelInfo) throw new Error(`Admin channel "${adminChannelName}" not found`);
const standardChannelInfo = allChannels.find(channel => channel.name === standardChannelName);
if (!standardChannelInfo) throw new Error(`Standard channel "${standardChannelName}" not found`);
// Set the global variables
global.adminChannel = adminChannelInfo.id;
global.standardChannel = standardChannelInfo.id;
logger.info('Admin channelID: ' + global.adminChannel);
logger.info('Standard channelID: ' + global.standardChannel);
} catch (error) {
logger.error(`Error fetching channels: ${error.message}`);
}
}
// Call the function to lookup channel IDs
_lookupChannelID();
// TEST CODE: Force Slack API Rate Limit
//async function testRateLimit() {
// const requests = 500; // Adjust the number of simultaneous requests
//
// logger.info(`Starting ${requests} parallel API calls to test rate limit...`);
//
// const promises = [];
// for (let i = 0; i < requests; i++) {
// promises.push(_lookupChannelID());
// }
// await Promise.all(promises);
// logger.info('Finished parallel API calls.');
//}
// Run the rate limit test
//(async () => {
// logger.info('Starting API rate limit test...');
// await testRateLimit();
// logger.info('Rate limit test completed.');
//})();
function processInput(text, channel, userName) {
var input = text.split(' ')
var term = input[0].toLowerCase()
var matched = true
logger.info('term: ' + term)
switch (term) {
case 'add':
_add(input, channel, userName)
break
case 'addalbum':
_addalbum(input, channel, userName)
break
case 'bestof':
_bestof(input, channel, userName)
break
case 'append':
_append(input, channel, userName)
break
case 'searchplaylist':
_searchplaylist(input, channel, userName)
break
case 'searchalbum':
_searchalbum(input, channel)
break
case 'addplaylist':
_addplaylist(input, channel, userName)
break
case 'search':
_search(input, channel, userName)
break
case 'current':
case 'wtf':
_currentTrack(channel)
break
case 'dong':
case ':gong:':
case ':gun:':
case 'gong':
_gong(channel, userName)
break
case 'gongcheck':
_gongcheck(channel, userName)
break
case 'voteimmune':
_voteImmune(input, channel, userName)
break
case 'vote':
case ':star:':
_vote(input, channel, userName)
break
case 'voteimmunecheck':
_voteImmunecheck(channel, userName)
break
case 'votecheck':
_votecheck(channel, userName)
break
case 'list':
case 'ls':
case 'playlist':
_showQueue(channel)
break
case 'upnext':
_upNext(channel)
break
case 'volume':
_getVolume(channel)
break
case 'flushvote':
_flushvote(channel, userName)
break
case 'size':
case 'count':
case 'count(list)':
_countQueue(channel)
break
case 'status':
_status(channel)
break
case 'help':
_help(input, channel)
break
default:
matched = false
break
case 'flush':
_flush(input, channel, userName)
break
}
if (!matched && channel === global.adminChannel) {
switch (term) {
case 'debug':
_debug(channel, userName)
break
case 'next':
_nextTrack(channel, userName)
break
case 'stop':
_stop(input, channel, userName)
break
case 'flush':
_flush(input, channel, userName)
break
case 'play':
_play(input, channel, userName)
break
case 'pause':
_pause(input, channel, userName)
break
case 'playpause':
case 'resume':
_resume(input, channel, userName)
break
case 'previous':
_previous(input, channel, userName)
break
case 'shuffle':
_shuffle(input, channel, userName)
break
case 'normal':
_normal(input, channel, userName)
break
case 'setvolume':
_setVolume(input, channel, userName)
break
case 'blacklist':
_blacklist(input, channel, userName)
break
case 'test':
_addToSpotifyPlaylist(input, channel)
break
case 'remove':
_removeTrack(input, channel)
break
case 'thanos':
case 'snap':
_purgeHalfQueue(input, channel)
break
case 'listimmune':
_listImmune(channel)
break
case 'tts':
case 'say':
_tts(input, channel)
break
case 'move':
case 'mv':
_moveTrackAdmin(input, channel, userName)
break
case 'stats':
_stats(input, channel, userName)
break
default:
}
}
}
function _slackMessage(message, id) {
if (rtm.connected) {
rtm.sendMessage(message, id)
} else {
logger.info(message)
}
}
const userCache = {};
async function _checkUser(userId) {
try {
// Clean the userId if wrapped in <@...>
userId = userId.replace(/[<@>]/g, "");
// Check if user info is already in cache
if (userCache[userId]) {
return userCache[userId];
}
// Fetch user info from Slack API
const result = await web.users.info({ user: userId });
if (result.ok && result.user) {
userCache[userId] = result.user.name; // Cache the user info
return result.user.name;
} else {
logger.error('User not found: ' + userId);
return null;
}
} catch (error) {
if (error.data && error.data.error === 'user_not_found') {
logger.error('User not found: ' + userId);
} else {
logger.error('Error fetching user info: ' + error);
}
return null;
}
}
function _getVolume(channel) {
sonos.getVolume().then(vol => {
logger.info('The volume is: ' + vol);
_slackMessage('Currently blasting at ' + vol + ' dB _(ddB)_', channel);
}).catch(err => {
logger.error('Error occurred: ' + err);
});
}
function _setVolume(input, channel, userName) {
_logUserAction(userName, 'setVolume');
if (channel !== global.adminChannel) {
return;
}
const vol = Number(input[1]);
if (isNaN(vol)) {
_slackMessage('Nope.', channel);
return;
}
logger.info('Volume is: ' + vol);
if (vol > maxVolume) {
_slackMessage("That's a bit extreme, " + userName + '... lower please.', channel);
return;
}
setTimeout(() => {
sonos.setVolume(vol).then(() => {
logger.info('The volume is set to: ' + vol);
_getVolume(channel);
}).catch(err => {
logger.error('Error occurred while setting volume: ' + err);
});
}, 1000);
}
function _countQueue(channel, cb) {
sonos.getQueue().then(result => {
if (cb) {
return cb(result.total)
}
_slackMessage(`${result.total} songs in the queue`, channel)
}).catch(err => {
logger.error(err)
if (cb) {
return cb(null, err)
}
_slackMessage('Error getting queue length', channel)
})
}
async function _showQueue(channel) {
try {
const result = await sonos.getQueue();
// logger.info('Current queue: ' + JSON.stringify(result, null, 2))
_status(channel, function (state) {
logger.info('_showQueue, got state = ' + state)
});
_currentTrack(channel, function (err, track) {
if (!result) {
logger.debug(result);
_slackMessage('Seems like the queue is empty... Have you tried adding a song?!', channel);
}
if (err) {
logger.error(err);
}
var message = 'Total tracks in queue: ' + result.total + '\n====================\n';
logger.info('Total tracks in queue: ' + result.total);
const tracks = [];
result.items.map(
function (item, i) {
let trackTitle = item.title;
if (_isTrackGongBanned(item.title)) {
tracks.push(':lock: ' + '_#' + i + '_ ' + trackTitle + ' by ' + item.artist);
// trackTitle = ':lock:' + trackTitle;
} else if (item.title === track.title) {
trackTitle = '*' + trackTitle + '*';
} else {
trackTitle = '_' + trackTitle + '_';
}
if (item.title === track.title) {
tracks.push(':notes: ' + '_#' + i + '_ ' + trackTitle + ' by ' + item.artist);
} else {
tracks.push('>_#' + i + '_ ' + trackTitle + ' by ' + item.artist);
}
}
);
for (var i in tracks) {
message += tracks[i] + '\n';
if (i > 0 && Math.floor(i % 100) === 0) {
_slackMessage(message, channel);
message = '';
}
}
if (message) {
_slackMessage(message, channel);
}
});
} catch (err) {
logger.error('Error fetching queue: ' + err);
}
}
function _upNext(channel) {
sonos.getQueue().then(result => {
// logger.debug('Current queue: ' + JSON.stringify(result, null, 2));
_currentTrack(channel, function (err, track) {
if (!result || !result.items || result.items.length === 0) {
logger.debug('Queue is empty or undefined');
_slackMessage('Seems like the queue is empty... Have you tried adding a song?!', channel);
return;
}
if (err) {
logger.error('Error getting current track: ' + err);
return;
}
if (!track) {
logger.debug('Current track is undefined');
_slackMessage('No current track is playing.', channel);
return;
}
// logger.info('Got current track: ' + JSON.stringify(track, null, 2));
var message = 'Upcoming tracks\n====================\n';
let tracks = [];
let currentIndex = track.queuePosition;
// Add current track and upcoming tracks to the tracks array
result.items.forEach((item, i) => {
if (i >= currentIndex && i <= currentIndex + 5) {
tracks.push('_#' + i + '_ ' + "_" + item.title + "_" + ' by ' + item.artist);
}
});
for (var i in tracks) {
message += tracks[i] + '\n';
}
if (message) {
_slackMessage(message, channel);
}
});
}).catch(err => {
logger.error('Error fetching queue: ' + err);
});
}
let voteTimer = null;
const voteTimeLimit = voteTimeLimitMinutes * 60 * 1000; // Convert minutes to milliseconds
function _flushvote(channel, userName) {
_logUserAction(userName, 'flushvote');
logger.info('_flushvote...');
if (!(userName in flushVoteScore)) {
flushVoteScore[userName] = 0;
}
if (flushVoteScore[userName] >= flushVoteLimitPerUser) {
_slackMessage('Are you trying to cheat, ' + userName + '? DENIED!', channel);
} else {
flushVoteScore[userName] = flushVoteScore[userName] + 1;
voteCounter++;
logger.info('1voteCounter: ' + voteCounter);
logger.info('1voteTimer: ' + voteTimer);
if (voteCounter === 1) {
// Start the timer on the first vote
voteTimer = setTimeout(() => {
voteCounter = 0;
flushVoteScore = {};
_slackMessage('Voting period ended.', channel);
logger.info('Voting period ended... Guess the playlist isn´t that bad after all!!');
}, voteTimeLimit);
_slackMessage("Voting period started for a flush of the queue... You have " + voteTimeLimitMinutes + " minutes to gather " + flushVoteLimit + " votes !!", channel);
logger.info('Voting period started!!');
logger.info('3voteCounter: ' + voteCounter);
logger.info('3voteTimer: ' + voteTimer);
}
_slackMessage('This is VOTE ' + "*" + voteCounter + "*" + '/' + flushVoteLimit + ' for a full flush of the playlist!!', channel);
if (voteCounter >= flushVoteLimit) {
clearTimeout(voteTimer); // Clear the timer if the vote limit is reached
_slackMessage('The votes have spoken! Flushing the queue...:toilet:', channel);
try {
sonos.flush();
} catch (error) {
logger.error('Error flushing the queue: ' + error);
}
voteCounter = 0;
flushVoteScore = {};
}
}
}
function _gong(channel, userName) {
_logUserAction(userName, 'gong');
logger.info('_gong...')
_currentTrackTitle(channel, function (err, track) {
if (err) {
logger.error(err)
}
logger.info('_gong > track: ' + track)
// NOTE: The gongTrack is checked in _currentTrackTitle() so we
// need to let that go through before checking if gong is banned.
if (_isTrackGongBanned(track)) {
logger.info('Track is gongBanned: ' + track);
_slackMessage('Sorry ' + userName + ', the people have voted and this track cannot be gonged...', channel)
return
}
// Get message
logger.info('gongMessage.length: ' + gongMessage.length)
var ran = Math.floor(Math.random() * gongMessage.length)
var randomMessage = gongMessage[ran]
logger.info('gongMessage: ' + randomMessage)
// Need a delay before calling the rest
if (!(userName in gongScore)) {
gongScore[userName] = 0
}
if (gongScore[userName] >= gongLimitPerUser) {
_slackMessage('Are you trying to cheat, ' + userName + '? DENIED!', channel)
} else {
if (userName in voteImmuneScore) {
_slackMessage('Having regrets, ' + userName + "? We're glad you came to your senses...", channel)
}
gongScore[userName] = gongScore[userName] + 1
gongCounter++
_slackMessage(randomMessage + ' This is GONG ' + gongCounter + '/' + gongLimit + ' for ' + "*" + track + "*", channel)
if (gongCounter >= gongLimit) {
_slackMessage('The music got GONGED!!', channel)
_gongplay('play', channel)
gongCounter = 0
gongScore = {}
}
}
})
}
function _voteImmune(input, channel, userName) {
var voteNb = input[1];
voteNb = Number(voteNb) + 1; // Add 1 to match the queue index
voteNb = String(voteNb);
logger.info('voteNb: ' + voteNb);
sonos.getQueue().then(result => {
logger.info('Current queue: ' + JSON.stringify(result, null, 2));
logger.info('Finding track:' + voteNb);
let trackFound = false;
let voteTrackId = null;
let voteTrackName = null;
for (var i in result.items) {
var queueTrack = result.items[i].id;
queueTrack = queueTrack.split('/')[1];
logger.info('queueTrack: ' + queueTrack);
if (voteNb === queueTrack) {
voteTrackId = result.items[i].id.split('/')[1];
voteTrackName = result.items[i].title;
logger.info('voteTrackName: ' + voteTrackName);
trackFound = true;
break;
}
}
if (trackFound) {
if (!(userName in voteImmuneScore)) {
voteImmuneScore[userName] = 0;
}
if (voteImmuneScore[userName] >= voteImmuneLimitPerUser) {
_slackMessage('Are you trying to cheat, ' + userName + '? DENIED!', channel);
} else {
if (userName in gongScore) {
_slackMessage('Changed your mind, ' + userName + '? Well, ok then...', channel);
}
voteImmuneScore[userName] = voteImmuneScore[userName] + 1;
voteImmuneCounter++;
_slackMessage('This is VOTE ' + voteImmuneCounter + '/' + voteImmuneLimit + ' for ' + "*" + voteTrackName + "*", channel);
if (voteImmuneCounter >= voteImmuneLimit) {
_slackMessage('This track is now immune to GONG! (just this once)', channel);
voteImmuneCounter = 0;
voteImmuneScore = {};
gongBannedTracks[voteTrackName] = true; // Mark the track as gongBanned
}
}
}
});
}
// Function to check if a track is gongBanned
function _isTrackGongBanned(trackName) {
return gongBannedTracks[trackName] === true;
}
function _listImmune(channel) {
const gongBannedTracksList = Object.keys(gongBannedTracks);
if (gongBannedTracksList.length === 0) {
_slackMessage('No tracks are currently immune.', channel);
} else {
const message = 'Immune Tracks:\n' + gongBannedTracksList.join('\n');
_slackMessage(message, channel);
}
}
// Initialize vote count object
let trackVoteCount = {};
function _vote(input, channel, userName) {
_logUserAction(userName, 'vote');
// Get message
logger.info('voteMessage.length: ' + voteMessage.length)
var ran = Math.floor(Math.random() * voteMessage.length)
var randomMessage = voteMessage[ran]
logger.info('voteMessage: ' + randomMessage)
var voteNb = input[1];
voteNb = Number(voteNb) + 1; // Add 1 to match the queue index
voteNb = String(voteNb);
logger.info('voteNb: ' + voteNb);
sonos.getQueue().then(result => {
logger.info('Current queue: ' + JSON.stringify(result, null, 2))
logger.info('Finding track:' + voteNb);
let trackFound = false;
for (var i in result.items) {
var queueTrack = result.items[i].id;
queueTrack = queueTrack.split('/')[1];
logger.info('queueTrack: ' + queueTrack)
if (voteNb === queueTrack) {
var voteTrackName = result.items[i].title;
logger.info('voteTrackName: ' + voteTrackName);
trackFound = true;
break;
}
}
if (trackFound) {
if (!(userName in voteScore)) {
voteScore[userName] = 0;
}
if (voteScore[userName] >= voteLimitPerUser) {
_slackMessage('Are you trying to cheat, ' + userName + '? DENIED!', channel);
} else {
if (userName in gongScore) {
_slackMessage('Changed your mind, ' + userName + '? Well, ok then...', channel);
}
voteScore[userName] = voteScore[userName] + 1;
voteCounter++;
// Update the vote count for the track
if (!(voteNb in trackVoteCount)) {
trackVoteCount[voteNb] = 0;
}
trackVoteCount[voteNb] += 1;
// Log the vote count for the track
logger.info('Track ' + voteTrackName + ' has received ' + trackVoteCount[voteNb] + ' votes.');
_slackMessage('This is VOTE ' + trackVoteCount[voteNb] + '/' + voteLimit + ' for ' + "*" + voteTrackName + "*", channel);
if (trackVoteCount[voteNb] >= voteLimit) {
logger.info('Track ' + voteTrackName + ' has reached the vote limit.');
_slackMessage(randomMessage, channel);
// Reset the vote count for the track
voteImmuneCounter = 0;
voteImmuneScore = {};
//Now, lets move the track so it plays next
// Get the current track position
sonos.currentTrack().then(track => {
logger.info('Got current track: ' + track)
var currentTrackPosition = track.queuePosition;
logger.info('Current track position: ' + currentTrackPosition);
// Get the track position in the queue
var trackPosition = parseInt(voteNb);
logger.info('Track position: ' + trackPosition);
// Define the parameters
const startingIndex = trackPosition; // Assuming trackPosition is the starting index
const numberOfTracks = 1; // Assuming we are moving one track
const insertBefore = currentTrackPosition + 1; // Assuming desiredPosition is where the track should be moved to
const updateId = 0; // Leave updateId as 0
// Move to the track position using reorderTracksInQueue
sonos.reorderTracksInQueue(startingIndex, numberOfTracks, insertBefore, updateId).then(success => {
logger.info('Moved track to position: ' + insertBefore);
}).catch(err => {
logger.error('Error occurred: ' + err);
});
}).catch(err => {
logger.error('Error occurred: ' + err);
});
}
}
}
});
}
async function _moveTrackAdmin(input, channel, userName) {
if (channel !== global.adminChannel) {
_slackMessage('You do not have permission to move tracks.', channel);
return;
}
if (input.length < 3) {
_slackMessage('Please provide both the track number and the desired position.', channel);
return;
}
const trackNb = parseInt(input[1], 10); // Use the original input value
const desiredPosition = parseInt(input[2], 10); // Use the original input value
if (isNaN(trackNb) || isNaN(desiredPosition)) {
_slackMessage('Invalid track number or desired position.', channel);
return;
}
logger.info(`_moveTrackAdmin: Moving track ${trackNb} to position ${desiredPosition}`);
try {
const queue = await sonos.getQueue();
logger.info('Current queue: ' + JSON.stringify(queue, null, 2));
const track = queue.items.find(item => item.id.split('/')[1] === String(trackNb + 1)); // Adjust for 1-based index
if (!track) {
_slackMessage(`Track number ${trackNb} not found in the queue.`, channel);
return;
}
const currentTrackPosition = parseInt(track.id.split('/')[1], 10);
logger.info('Current track position: ' + currentTrackPosition);
// Define the parameters
const startingIndex = currentTrackPosition; // Current position of the track
const numberOfTracks = 1; // Moving one track
const insertBefore = desiredPosition + 1; // Adjust for 1-based index
// Move the track to the desired position using reorderTracksInQueue
await sonos.reorderTracksInQueue(startingIndex, numberOfTracks, insertBefore, 0);
logger.info(`Moved track ${trackNb} to position ${desiredPosition}`);
_slackMessage(`Moved track ${trackNb} to position ${desiredPosition}`, channel);
} catch (err) {
logger.error('Error occurred: ' + err);
_slackMessage('Error moving track. Please try again later.', channel);
}
}
/**
* Checks the vote status for all tracks and sends a Slack message with the results.
*
* @param {string} channel - The channel to send the message to.
*/
function _votecheck(channel) {
logger.info('Checking vote status for all tracks:');
sonos.getQueue().then(result => {
const trackNames = {};
for (var i in result.items) {
var queueTrack = result.items[i].id.split('/')[1];
var trackName = result.items[i].title;
trackNames[queueTrack] = trackName;
}
for (const trackId in trackVoteCount) {
if (trackVoteCount.hasOwnProperty(trackId)) {
const voteCount = trackVoteCount[trackId];
const trackName = trackNames[trackId] || 'Unknown Track';
const voters = Object.keys(voteScore).filter(user => voteScore[user] > 0 && voteScore[user] < voteLimitPerUser);
const votedBy = voters.map(user => `${user}`).join(', ');
_slackMessage("*" + trackName + "*" + ' has received ' + voteCount + ' votes. Voted by: ' + votedBy, channel);