-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
1427 lines (1301 loc) · 39.8 KB
/
server.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
require('dotenv').config();
const Sentry = require('@sentry/node');
Sentry.init({
dsn:
'https://[email protected]/5340340',
environment: process.env.NODE_ENV,
});
const config = require('./config/config');
const version = require('project-version');
console.log('Version: ' + version);
const express = require('express');
const app = express();
const server = require('http').Server(app);
const passport = require('passport');
const twitchStrategy = require('passport-twitch.js').Strategy;
const bodyParser = require('body-parser');
const cookieSession = require('cookie-session');
const spotifyUri = require('spotify-uri');
const Spotify = require('node-spotify-api');
const spotify = new Spotify({
id: process.env.SPOTIFY_ID,
secret: process.env.SPOTIFY_SECRET,
});
const YouTube = require('simple-youtube-api');
const youtube = new YouTube(process.env.YT_API);
const moment = require('moment-timezone');
const io = require('socket.io')(server);
global.io = io;
const fetchJson = require('fetch-json');
const ComfyDiscord = require('comfydiscord');
const admins = config.admins;
const he = require('he');
const fs = require('fs');
const axios = require('axios');
const JoinedChannel = require('./models/joinedChannels');
const qs = require('querystring');
const { v4: uuidv4 } = require('uuid');
const helmet = require('helmet');
const { nanoid } = require('nanoid');
//require('./utils/StreamElements')(io);
const volleyball = require('volleyball');
const sanitizeHtml = require('sanitize-html');
// Redis
const { Message, Producer } = require('redis-smq');
const redis = require('./utils/redis')
const Redis = require('ioredis');
const subRedis = new Redis({ password: process.env.REDIS_PASS });
subRedis.on('connect', (reply) => {
console.log('Alerts redis client connected');
console.log(reply);
});
const Queue = require('./models/queues');
async function updateDocs() {
await Queue.updateMany(
{},
{
appendReqs: false,
}
);
}
//updateDocs()
// Discord Init
//ComfyDiscord.Init(process.env.DISCORDTOKEN);
// Twitch Creds for App
const TwitchCreds = require('./models/twitchCreds');
// TODO: Rewrite to use fetch and add refresh check
async function getTwitchCreds() {
const twitchCreds = await TwitchCreds.findOne({});
console.log(twitchCreds);
if (twitchCreds === null) {
const twitchUserURL = `https://id.twitch.tv/oauth2/token?client_id=${process.env.TWITCH_CLIENTID}&client_secret=${process.env.TWITCH_SECRET}&scope=user_read&grant_type=client_credentials`;
console.log(twitchUserURL);
const twitchResource = {};
const handleData = (data) => {
console.log(data);
const newTwitch = new TwitchCreds({
accessToken: data.access_token,
expireAt: moment().utc().add(data.expires_in, 'seconds'),
});
newTwitch
.save()
.then(console.log('New Twitch Creds created'))
.catch(console.error);
};
fetchJson.post(twitchUserURL).then(handleData).catch(console.error);
} else {
console.log('Twitch Creds already exist');
}
}
getTwitchCreds();
// Real time data
const rqs = io.of('/req-namescape');
const polls = io.of('/polls-namescape');
const widgets = io.of('/widgets');
rqs.on('connection', function (socket) {
// Create room and
// Trigger front end notification
socket.on('create', function (room) {
console.log(` ${room} Connected to requests`);
socket.join(room);
rqs.to(`${room}`).emit('socketConnect', {});
});
//Whenever someone disconnects this piece of code executed
rqs.on('disconnect', function () {
console.log('User disconnected from requests');
});
});
app.set('trust proxy', 1);
app.set('views', './views');
app.set('view engine', 'ejs');
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: [
"'self'",
'*.cloudflare.com',
'*.bootstrapcdn.com',
'*.fontawesome.com',
'cdn.jsdelivr.net',
'static-cdn.jtvnw.net',
'code.jquery.com',
'*.google.com',
'*.gstatic.com',
'*.cloudfront.net'
],
styleSrc: [
"'self'",
"'unsafe-inline'",
'*.cloudflare.com',
'*.bootstrapcdn.com',
'*.fontawesome.com',
'cdn.jsdelivr.net',
'fonts.googleapis.com',
],
fontSrc: [
'fonts.googleapis.com',
'fonts.gstatic.com',
'*.fontawesome.com'
],
upgradeInsecureRequests: [],
},
})
);
app.use(express.static('public'));
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(bodyParser.json());
app.use(
cookieSession({
name: 'session',
secret: `${process.env.SESSION_SECRET}`,
saveUninitialized: false,
resave: false,
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(volleyball);
// Route Files
const indexRoute = require('./routes/index');
const authRoute = require('./routes/auth');
const reqsRoute = require('./routes/requests');
const mixRoute = require('./routes/mix');
const widgetRoute = require('./routes/widget');
const apiRoute = require('./routes/api');
const settingsRoute = require('./routes/settings');
const authedUser = require('./routes/authedUser');
app.use('/', indexRoute);
app.use('/auth', authRoute);
app.use('/u', authedUser);
app.use('/widget', widgetRoute);
app.use('/api', apiRoute);
app.use('/settings', settingsRoute);
// Databae
const mongoose = require('mongoose');
switch (process.env.NODE_ENV) {
case 'production':
mongoose
.connect(
`mongodb+srv://vibey_bot:${process.env.DB_PASS}@cluster0-gtgmw.mongodb.net/vibeybot?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}
)
.catch(function (err) {
// TODO: Throw error page if DB doesn't connect
console.error(
'Unable to connect to the mongodb instance. Error: ',
err
);
});
break;
case 'staging':
mongoose
.connect(
`mongodb+srv://vibey_bot:${process.env.DB_PASS}@cluster0-gtgmw.mongodb.net/vibeystaging?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}
)
.catch(function (err) {
// TODO: Throw error page if DB doesn't connect
console.error(
'Unable to connect to the mongodb instance. Error: ',
err
);
});
break;
case 'dev':
mongoose
.connect(
`mongodb+srv://vibey_bot:${process.env.DB_PASS}@cluster0-gtgmw.mongodb.net/vibeydev?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}
)
.catch(function (err) {
// TODO: Throw error page if DB doesn't connect
console.error(
'Unable to connect to the mongodb instance. Error: ',
err
);
});
break;
}
const db = mongoose.connection;
db.on('error', (error) => {
console.error(error);
});
db.once('open', () => console.log('Connected to Mongoose ' + Date()));
//Models
const User = require('./models/users');
const SongRequest = require('./models/songRequests');
const Poll = require('./models/polls');
const Good = require('./models/goods');
const channelQueue = require('./models/queues');
const ChannelEvent = require('./models/channelEvent');
// Twitch auth
passport.use(
new twitchStrategy(
{
clientID: process.env.TWITCH_CLIENTID,
clientSecret: process.env.TWITCH_SECRET,
callbackURL: `${process.env.APP_URL}/auth/twitch/callback`,
scope: 'user:read:email channel_subscriptions bits:read',
},
async function (accessToken, refreshToken, profile, done) {
try {
User.findOne({
twitch_id: profile.id,
})
.exec()
.then(function (UserSearch) {
if (UserSearch === null) {
var user = new User({
twitch_id: profile.id,
username: profile.login,
display_name: profile.display_name,
email: profile.email,
profile_pic_url: profile.profile_image_url,
provider: 'twitch',
twitch: profile,
accessToken: accessToken,
refreshToken: refreshToken,
expireAt: moment().utc().add(8, 'hours'),
});
console.log('New user created');
let queue = new channelQueue({
channel: profile.login,
});
queue.save();
user.save();
return done(null, profile);
} else {
console.log('User already exists');
console.log(UserSearch.twitch_id);
return done(null, profile);
}
})
.catch((err) => {
console.error(err);
});
} catch (err) {
console.error(err);
}
}
)
);
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
/* *** DON'T PLACE ANY PAGES ***
*** AFTER THE 404 PAGE *** */
//404
app.get('*', (req, res) => {
res.render('404');
});
// Twitch Client
const tmi = require('tmi.js');
const twitchclientid = process.env.TWITCH_CLIENTID;
const twitchuser = process.env.TWITCH_USER;
const twitchpass = process.env.TWITCH_PASS;
console.log(process.argv);
let connectConfig;
if (process.argv.includes('-testserv')) {
connectConfig = {
secure: true,
// Test server
server: 'irc.fdgt.dev',
reconnect: true,
};
} else {
connectConfig = {
secure: true,
reconnect: true,
};
}
tmiOptions = {
options: {
debug: false,
clientId: twitchclientid,
},
connection: connectConfig,
identity: {
username: twitchuser,
password: twitchpass,
},
};
const botclient = new tmi.client(tmiOptions);
// Connect the twitch chat client to the server..
botclient.connect();
global.botclient = botclient;
// re-join channels that were already connected
JoinedChannel.find({}).then((res) => {
res.forEach((doc) => {
console.log(doc.channel);
botclient.join(doc.channel);
});
});
// Test functions
function subDelay() {
setTimeout(sendSubs, 15000);
}
function sendSubs() {
botclient.say('#opti_21', `subgift --tier 1 --username speedrazer`);
// botclient.say('#opti_21', `subgift --tier 1 --username charlierose`);
// botclient.say('#opti_21', `subgift --tier 1 --username marothon`);
// botclient.say('#opti_21', `subgift --tier 1 --username speedrazer`);
// botclient.say('#opti_21', `subgift --tier 1 --username speedrazer`);
}
function sendSMG() {
botclient.say(
'#opti_21',
`submysterygift --count ${Math.floor(
Math.random() * (10 - 5) + 5
)} --username speedrazer`
);
}
function sendBits() {
botclient.say(
'#opti_21',
`bits --bitscount ${Math.floor(Math.random() * (1000 - 5) + 5)}`
);
}
function sendraid() {
botclient.say('#opti_21', `raid`);
}
if (process.argv.includes('-sendsmg')) {
setInterval(sendSMG, 10000);
}
if (process.argv.includes('-sendbits')) {
setInterval(sendBits, 5000);
}
if (process.argv.includes('-sendsubs')) {
setInterval(sendSubs, 10000);
// subDelay();
}
if (process.argv.includes('-sendraid')) {
setInterval(sendraid, 11000);
}
// Bot connected to IRC server
botclient.on('connected', (address, port) => {
console.log('connected to twitch chat client');
console.log(address);
});
// Regex
const URLRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;
const spRegex = /https?:\/\/(?:embed\.|open\.)(?:spotify\.com\/)(?:track\/|\?uri=spotify:track:)((\w|-){22})/;
const ytRegex = /(?:https?:\/\/)?(?:(?:(?:www\.?)?youtube\.com(?:\/(?:(?:watch\?.*?(v=[^&\s]+).*)|(?:v(\/.*))|(channel\/.+)|(?:user\/(.+))|(?:results\?(search_query=.+))))?)|(?:youtu\.be(\/.*)?))/;
function refreshTokenThenAdd(user, uri) {
let cb_url = process.env.SPOTIFY_CALLBACK_URL;
console.log('REFRESH SPOTIFY TOKEN');
console.log(user);
console.log(user.spotify.refresh_token);
let body = {
client_id: process.env.SPOTIFY_ID,
client_secret: process.env.SPOTIFY_SECRET,
refresh_token: user.spotify.refresh_token,
grant_type: 'refresh_token',
redirect_uri: cb_url,
};
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
};
axios
.post('https://accounts.spotify.com/api/token/', qs.stringify(body), config)
.then((code_res) => {
//console.log(code_res.data);
try {
User.findOneAndUpdate(
{
twitch_id: user.twitch_id,
},
{
spotify: {
access_token: code_res.data.access_token,
refresh_token: user.spotify.refresh_token,
token_type: code_res.data.token_type,
expires_in: moment()
.utc()
.add(code_res.data.expires_in, 'seconds'),
scope: code_res.data.scope,
},
},
{
new: true,
}
).then((update_res) => {
//console.log(update_res);
console.log('spotify token refreshed');
checkPlaylist(uri, user.username, update_res.spotify.access_token);
});
} catch (e) {
console.error(e);
}
})
.catch((e) => {
console.error(e);
});
}
function findURI(object, property, value) {
return (
object[property] === value ||
Object.keys(object).some(function (k) {
return (
object[k] &&
typeof object[k] === 'object' &&
findURI(object[k], property, value)
);
})
);
}
function checkPlaylist(uri, channel, user_token) {
axios({
method: 'get',
url: `https://api.spotify.com/v1/playlists/${config.spotify_playlist}/tracks`,
headers: {
Authorization: 'Bearer ' + user_token,
},
params: {
fields: 'items(track(uri))',
},
})
.then((res) => {
if (!findURI(res.data.items, 'uri', uri)) {
addSongtoPlaylist(uri, channel, user_token);
} else {
botclient.say(channel, 'Song is already on the playlist');
return;
}
})
.catch((e) => {
console.error(e);
});
}
function addSongtoPlaylist(uri, channel, user_token) {
// Add song to playlist
axios({
method: 'post',
url: `https://api.spotify.com/v1/playlists/${config.spotify_playlist}/tracks`,
data: {
uris: [uri],
},
headers: {
Authorization: 'Bearer ' + user_token,
Accept: 'application/json',
},
})
.then((res) => {
console.log(res.data);
spotify
.request(`https://api.spotify.com/v1/tracks/${uri.slice(14)}`)
.then(function (data) {
console.log('Song added to playlist');
botclient.say(
channel,
`${data.name} by ${data.artists[0].name} added to playlist successfully`
);
});
})
.catch((err) => {
console.error(err);
botclient.say(channel, `Error adding song to playlist @opti_21`);
});
}
// Spotify redemptions
botclient.on('chat', async (channel, userstate, message, self) => {
if (self) return;
let noHashChan = channel.slice(1);
let song = message;
if (
userstate['custom-reward-id'] === '609d1f92-0dde-4057-9902-30f5f78237e6'
) {
console.log('I SEE THE REDEMPTION');
if (spRegex.test(song)) {
try {
var spID = spotifyUri.parse(song);
var spURI = spotifyUri.formatURI(song);
let vibeyUser = await User.findOne({
username: noHashChan,
});
//console.log(vibeyUser);
let userToken = vibeyUser.spotify.access_token;
let tokenExpire = vibeyUser.spotify.expires_in;
console.log(tokenExpire);
console.log(moment(moment().utc()).isBefore(tokenExpire));
// Check to see if token is valid
if (moment(moment().utc()).isBefore(tokenExpire)) {
checkPlaylist(spURI, noHashChan, userToken);
} else {
refreshTokenThenAdd(vibeyUser, spURI);
}
} catch (err) {
console.log(err);
botclient.say(
config.comfyChan,
'Error adding song @opti_21 @veryhandsomebilly'
);
}
} else {
botclient.say(
config.comfyChan,
`This isn't a spotify link please try again @opti_21 @veryhandsomebilly please refund`
);
}
}
});
// Clear events
if (process.argv.includes('-clearevents')) {
ChannelEvent.deleteMany({}).then((doc) => {
console.log('EVENTS DELETED');
});
}
// Publish alerts to the front end
subRedis.subscribe('wsalerts', (err) => {
if (err) console.error(err);
console.log('Subscribed to alerts redis');
});
subRedis.on('message', (channel, message) => {
switch (channel) {
case 'wsalerts':
{
console.log('WS Alert ' + JSON.parse(message).type);
let parsedM = JSON.parse(message);
rqs.to(parsedM.channel).emit('noti', parsedM);
}
break;
}
});
// Song Requests
botclient.on('chat', async (channel, userstate, message, self) => {
if (self) return;
let noHashChan = channel.slice(1);
if (message === 'boop') {
}
if (message[0] !== '!') return;
let parsedM = message.trim().split(' ');
let command = parsedM[0].slice(1).toLowerCase();
// TODO: Combine open and closing commands
if (command === 'closesr') {
if (userstate.badges.broadcaster === '1' || userstate.mod === true) {
channelQueue
.updateOne(
{
channel: channel.slice(1),
},
{
allowReqs: false,
}
)
.then((doc) => {
botclient.say(channel, 'Requests are now closed');
})
.catch((err) => console.error(err));
} else {
return;
}
}
if (command === 'opensr') {
if (userstate.badges.broadcaster === '1' || userstate.mod === true) {
channelQueue
.updateOne(
{
channel: channel.slice(1),
},
{
allowReqs: true,
}
)
.then((doc) => {
botclient.say(channel, 'Requests are now open');
})
.catch((err) => console.error(err));
} else {
return;
}
}
if (command === 'replies') {
if (userstate.badges.broadcaster === '1' || userstate.mod === true) {
let allowed = ['off', 'on'];
let setting = parsedM[1];
if (!allowed.includes(setting)) {
botclient.say(noHashChan, 'Unrecognized setting, please use off or on');
return;
}
let settingBool;
if (setting === 'off') {
settingBool = false;
}
if (setting === 'on') {
settingBool = true;
}
channelQueue
.updateOne(
{
channel: noHashChan,
},
{
replyInChat: settingBool,
}
)
.then((doc) => {
botclient.say(channel, `Replies are now ${setting}`);
})
.catch((err) => console.error(err));
} else {
return;
}
}
if (command === 'sr' || command === 'songrequest') {
let queue = await channelQueue.findOne({
channel: noHashChan,
});
let chatRespond = queue.replyInChat;
console.log(queue.replyInChat);
if (queue.allowReqs) {
if (URLRegex.test(parsedM[1])) {
// Spotify link
if (spRegex.test(parsedM[1])) {
console.log('spotify link');
var spID = spotifyUri.parse(parsedM[1]);
var spURI = spotifyUri.formatURI(parsedM[1]);
spotify
.request(`https://api.spotify.com/v1/tracks/${spID.id}`)
.then(function (data) {
let newSr = {
id: uuidv4(),
track: {
name: data.name,
artist: data.artists[0].name,
link: parsedM[1],
uri: spURI,
},
requestedBy: userstate.username,
timeOfReq: moment.utc().format(),
source: 'spotify',
channel: channel.slice(1),
};
queue.currQueue.push(newSr);
let newQueue = queue.currQueue;
// console.log(queue);
channelQueue
.findOneAndUpdate(
{
channel: noHashChan,
},
{
currQueue: newQueue,
},
{
new: true,
useFindAndModify: false,
}
)
.then((queueDoc) => {
// Real time data push to front end
// console.log(doc);
// console.log(queueDoc);
rqs.to(`${noHashChan}`).emit('sr-event', {
id: `${newSr.id}`,
reqBy: `${newSr.requestedBy}`,
track: `${newSr.track.name}`,
artist: `${newSr.track.artist}`,
uri: `${newSr.track.uri}`,
link: `${newSr.track.link}`,
source: `${newSr.source}`,
timeOfReq: `${newSr.timeOfReq}`,
});
redis.incr('sr-processed', (err, res) => {
if(err) {
console.error(err)
}
})
if (chatRespond) {
botclient.say(
channel,
`@${newSr.requestedBy} requested ${newSr.track.name} by ${newSr.track.artist} - ${newSr.track.link}`
);
}
})
.catch((e) => {
console.error(e);
});
})
.catch(function (err) {
console.error('Error occurred: ' + err);
});
}
// Youtube Link
if (ytRegex.test(parsedM[1])) {
console.log('youtube link');
youtube.getVideo(parsedM[1]).then((video) => {
let newSr = {
id: uuidv4(),
track: {
name: video.title,
link: parsedM[1],
},
requestedBy: userstate.username,
timeOfReq: moment.utc().format(),
source: 'youtube',
channel: channel.slice(1),
};
queue.currQueue.push(newSr);
let newQueue = queue.currQueue;
// console.log(queue);
channelQueue
.findOneAndUpdate(
{
channel: noHashChan,
},
{
currQueue: newQueue,
},
{
new: true,
useFindAndModify: false,
}
)
.then((queueDoc) => {
// Real time data push to front end
// console.log(doc);
// console.log(queueDoc);
rqs.to(`${noHashChan}`).emit('sr-event', {
id: `${newSr.id}`,
reqBy: `${newSr.requestedBy}`,
track: `${newSr.track.name}`,
uri: `${newSr.track.uri}`,
link: `${newSr.track.link}`,
source: `${newSr.source}`,
timeOfReq: `${newSr.timeOfReq}`,
});
redis.incr('sr-processed', (err, res) => {
if(err) {
console.error(err)
}
})
if (chatRespond) {
botclient.say(
channel,
`@${newSr.requestedBy} requested ${newSr.track.name} - ${newSr.track.link}`
);
}
})
.catch((e) => {
console.error(e);
});
});
}
}
// Check for text content
if (parsedM[1] === undefined) {
botclient.say(
channel,
`No input received. !requests to see how to submit requests`
);
} else {
// Searches Spotify & Youtube when only text is provided
if (!ytRegex.test(parsedM[1])) {
let request = sanitizeText(parsedM.slice(1).join(' '))
// var ytQuery = parsedM.slice(1).join('+');
// var ytSearch = `https://www.youtube.com/results?search_query=${ytQuery}`;
spotify.search(
{
type: 'track',
query: `${request}`,
limit: 1,
},
function (err, data) {
if (err) {
console.error(err);
}
if (data.tracks.items.length === 0) {
// If Spotify can't find the song search for song on Youtube
youtube
.search(request, 1)
.then((results) => {
let newSr = {
id: uuidv4(),
track: {
name: results[0].title,
link: `https://youtu.be/${results[0].id}`,
},
requestedBy: userstate.username,
timeOfReq: moment.utc().format(),
source: 'youtube',
channel: channel.slice(1),
};
queue.currQueue.push(newSr);
let newQueue = queue.currQueue;
// console.log(queue);
channelQueue
.findOneAndUpdate(
{
channel: noHashChan,
},
{
currQueue: newQueue,
},
{
new: true,
useFindAndModify: false,
}
)
.then((queueDoc) => {
// Real time data push to front end
// console.log(doc);
// console.log(queueDoc);
rqs.to(`${noHashChan}`).emit('sr-event', {
id: `${newSr.id}`,
reqBy: `${newSr.requestedBy}`,
track: `${newSr.track.name}`,
uri: `${newSr.track.uri}`,
link: `${newSr.track.link}`,
source: `${newSr.source}`,
timeOfReq: `${newSr.timeOfReq}`,
});
redis.incr('sr-processed', (err, res) => {
if(err) {
console.error(err)
}
})
if (chatRespond) {
botclient.say(
channel,
`@${newSr.requestedBy} requested ${newSr.track.name} - ${newSr.track.link}`
);
}
})
.catch((e) => {
console.error(e);
});
})
.catch(console.error);
} else {
// If song was found on Spotify add song to queue
let newSr = {
id: uuidv4(),
track: {
name: data.tracks.items[0].name,
artist: data.tracks.items[0].artists[0].name,
link: data.tracks.items[0].external_urls.spotify,
uri: data.tracks.items[0].uri,
},
requestedBy: userstate.username,
timeOfReq: moment.utc().format(),
source: 'spotify',
channel: channel.slice(1),
};
queue.currQueue.push(newSr);
let newQueue = queue.currQueue;
// console.log(queue);
channelQueue
.findOneAndUpdate(
{
channel: noHashChan,
},
{
currQueue: newQueue,
},
{
new: true,
useFindAndModify: false,
}
)