-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
95 lines (81 loc) · 2.76 KB
/
app.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
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var userHelpers = require('./serverHelpers/userHelpers.js');
var users = [];
var messages = [];
app.set('port', (process.env.PORT || 8347));
app.use(express.static(__dirname + '/app'));
app.use(express.static(__dirname + '/bower_components'));
http.listen(app.get('port'), function() {
console.log('Node app is running on port ' + app.get('port'));
});
app.get('/', function(request, response) {
response.render('index');
});
io.on('connection', function(socket) {
console.log('user connected');
socket.on('store message', function(newMessage){
messages.push(newMessage);
io.emit('update messages', newMessage);
});
socket.on('disconnect', function() {
var user = userHelpers.getUser(users, socket.id);
if (users.length > 1 && user && user.master === true) {
userHelpers.getOthers(users, socket.id)[0].master = true;
console.log(user.name, 'disconnected');
}
userHelpers.removeUser(users, socket.id, function(remainingUsers) {
users = remainingUsers;
io.emit('user departed', socket.id);
io.emit('update users', users);
});
});
socket.on('new user', function(user) {
console.log('new user:', user.name);
socket.emit('assign socket id', socket.id);
user.color = userHelpers.chooseColor();
user.socketId = socket.id;
user.recording = {};
io.emit('connect users', users);
if (users.length === 0) {
socket.emit('start transport');
user.master = true;
} else {
user.master = false;
}
users.push(user);
io.emit('update users', users);
});
socket.on('transmit sound', function(tone) {
io.emit('play sound', tone, userHelpers.userColor(users, socket.id));
});
socket.on('transmit drum', function(drumName) {
io.emit('play drum', drumName);
});
socket.on('record sound', function(soundMap) {
var userRecording = userHelpers.getUser(users, socket.id).recording;
var snappedPosition = userHelpers.snapToBeat(soundMap[1]);
if (userRecording[soundMap[0]] === undefined) {
userRecording[soundMap[0]] = new Array(snappedPosition);
} else {
userRecording[soundMap[0]].push(snappedPosition);
}
io.emit('update users', users);
});
socket.on('remove sound', function(index) {
var recording = userHelpers.getUser(users, socket.id).recording;
var timeToRemove = '0:0:' + index;
Object.keys(recording).forEach(function(key) {
recording[key] = recording[key].filter(function(time) {
return time !== timeToRemove;
});
});
io.emit('update users', users);
});
socket.on('sync', function() {
io.emit('update users', users);
io.emit('start transport');
});
});