Skip to content

Commit

Permalink
refactor(server): separate runner from server logic
Browse files Browse the repository at this point in the history
  • Loading branch information
ttshivers committed Aug 23, 2020
1 parent dab8f17 commit a0d9f50
Show file tree
Hide file tree
Showing 6 changed files with 588 additions and 520 deletions.
8 changes: 8 additions & 0 deletions src/config/defaults.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const defaults = {
port: 8088,
base_url: '/',
ping_interval: 10000,
static_path: null,
};

export default defaults;
7 changes: 2 additions & 5 deletions src/config.js → src/config/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import nconf from 'nconf';
import defaults from './defaults';

nconf
.argv({
Expand All @@ -11,10 +12,6 @@ nconf
parseValues: true,
});

nconf.defaults({
port: 8088,
base_url: '/',
ping_interval: 10000,
});
nconf.defaults(defaults);

export default nconf;
44 changes: 5 additions & 39 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
#!/usr/bin/env node

import express from 'express';
import cors from 'cors';
import http from 'http';
import urljoin from 'url-join';

import config from './config';
import socketServer from './socketserver';

import { getHealth } from './socketserver/state';

// Using a single function to handle multiple signals
const handle = (signal) => {
console.log(`Received ${signal}. Exiting`);
Expand All @@ -19,36 +12,9 @@ const handle = (signal) => {
process.on('SIGINT', handle);
process.on('SIGTERM', handle);

http.globalAgent.keepAlive = true;

const app = express();
const server = http.Server(app);
const router = express.Router();

app.use(cors());

app.use(config.get('base_url'), router);

socketServer.attach(server, {
// TODO: Check if options are merged
path: urljoin(config.get('base_url'), '/socket.io'),
});

// Setup our router
if (config.get('static_path')) {
console.log('Serving static files at', config.get('static_path'));
router.use(express.static(config.get('static_path')));
} else {
router.get('/', (req, res) => {
res.send('You\'ve connected to the SLServer, you\'re probably looking for the webapp.');
});
}

router.get('/health', (req, res) => {
res.json(getHealth());
});

server.listen(config.get('port'), () => {
console.log('SyncLounge Server successfully started on port', config.get('port'));
console.log('Running with base URL:', config.get('base_url'));
socketServer({
baseUrl: config.get('base_url'),
staticPath: config.get('static_path'),
port: config.get('port'),
pingInterval: config.get('ping_interval'),
});
175 changes: 175 additions & 0 deletions src/socketserver/actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import {
isUserInARoom, getRoomUserData, getUserRoomId, makeUserHost,
getRoomSocketIds, removeUser, isRoomEmpty, removeRoom, getAnySocketIdInRoom,
generateAndSetSocketLatencySecret, formatUserData, getRoomHostId,
} from './state';

export const log = ({ socketId, message }) => {
const identifier = isUserInARoom(socketId)
? `[${socketId}] ${getRoomUserData(socketId).username}`
: `[${socketId}]`;

console.log(new Date().toISOString(), identifier, ':', message);
};

export const emitToSocket = ({
server, socketId, eventName, data,
}) => {
// console.log(data);
server.to(socketId).emit(eventName, data);
};

export const emitToUserRoomExcept = ({
server, eventName, data, exceptSocketId,
}) => {
getRoomSocketIds(getUserRoomId(exceptSocketId))
.filter((socketId) => socketId !== exceptSocketId)
.forEach((socketId) => {
emitToSocket({
server, socketId, eventName, data,
});
});
};

const emitToRoom = ({
server, roomId, eventName, data,
}) => {
getRoomSocketIds(roomId).forEach((socketId) => {
emitToSocket({
server, socketId, eventName, data,
});
});
};

export const emitToSocketRoom = ({
server, socketId, eventName, data,
}) => {
emitToRoom({
server, roomId: getUserRoomId(socketId), eventName, data,
});
};

export const announceNewHost = ({ server, roomId, hostId }) => {
emitToRoom({
server,
roomId,
eventName: 'newHost',
data: hostId,
});
};

export const removeUserAndUpdateRoom = ({ server, socketId }) => {
const roomId = getUserRoomId(socketId);

removeUser(socketId);

if (isRoomEmpty(roomId)) {
removeRoom(roomId);
return;
}

if (getRoomHostId(roomId) === socketId) {
// Make someone else host
const desiredHostId = getAnySocketIdInRoom(roomId);
makeUserHost(desiredHostId);

log({
socketId,
message: `Transferring host to: [${desiredHostId}] ${getRoomUserData(desiredHostId).username}`,
});
emitToRoom({
server,
roomId,
eventName: 'userLeft',
data: {
id: socketId,
newHostId: desiredHostId,
},
});

return;
}

emitToRoom({
server,
roomId,
eventName: 'userLeft',
data: {
id: socketId,
},
});
};

export const sendPing = ({ server, socketId }) => {
const secret = generateAndSetSocketLatencySecret(socketId);

emitToSocket({
server,
socketId,
eventName: 'slPing',
data: secret,
});
};

// Used to emit both player state updates and media updates.
// Adjusts the time by the latency to the recipient
export const emitAdjustedUserDataToRoom = ({
server, eventName, exceptSocketId, userData,
}) => {
getRoomSocketIds(getUserRoomId(exceptSocketId))
.filter((socketId) => socketId !== exceptSocketId)
.forEach((socketId) => {
emitToSocket({
server,
socketId,
eventName,
data: {
...formatUserData({
...userData,
recipientId: socketId,
}),
id: exceptSocketId,
},
});
});
};

export const emitPlayerStateUpdateToRoom = ({ server, socketId }) => {
const {
updatedAt, state, time, duration, playbackRate,
} = getRoomUserData(socketId);

emitAdjustedUserDataToRoom({
server,
eventName: 'playerStateUpdate',
exceptSocketId: socketId,
userData: {
updatedAt,
state,
time,
duration,
playbackRate,
},
});
};

export const emitMediaUpdateToRoom = ({ server, socketId, makeHost }) => {
const {
updatedAt, state, time, duration, playbackRate, media,
} = getRoomUserData(socketId);

emitAdjustedUserDataToRoom({
server,
eventName: 'mediaUpdate',
exceptSocketId: socketId,
userData: {
updatedAt,
state,
time,
duration,
playbackRate,
media,
makeHost,
},
});
};
Loading

0 comments on commit a0d9f50

Please sign in to comment.