simpler routing, fix socket reconnection bug, expand mod view

This commit is contained in:
Alec
2021-12-03 04:23:15 -05:00
parent 2b09cab5bc
commit 2debf7be35
16 changed files with 237 additions and 200 deletions

View File

@@ -1,6 +1,7 @@
export const globals = { export const globals = {
USER_SIGNATURE_LENGTH: 25, USER_SIGNATURE_LENGTH: 25,
CLOCK_TICK_INTERVAL_MILLIS: 10, CLOCK_TICK_INTERVAL_MILLIS: 10,
TOAST_DURATION_DEFAULT: 6,
ACCESS_CODE_LENGTH: 6, ACCESS_CODE_LENGTH: 6,
PLAYER_ID_COOKIE_KEY: 'play-werewolf-anon-id', PLAYER_ID_COOKIE_KEY: 'play-werewolf-anon-id',
ACCESS_CODE_CHAR_POOL: 'abcdefghijklmnopqrstuvwxyz0123456789', ACCESS_CODE_CHAR_POOL: 'abcdefghijklmnopqrstuvwxyz0123456789',

View File

@@ -1,5 +1,6 @@
import { globals } from "../config/globals.js"; import { globals } from "../config/globals.js";
import { toast } from "./Toast.js"; import { toast } from "./Toast.js";
import {templates} from "./Templates.js";
export class GameStateRenderer { export class GameStateRenderer {
constructor(gameState) { constructor(gameState) {
@@ -87,7 +88,10 @@ export class GameStateRenderer {
} }
renderModeratorView() { renderModeratorView() {
let div = document.createElement("div");
div.innerHTML = templates.END_GAME_PROMPT;
document.body.appendChild(div);
renderModeratorPlayers(this.gameState.people);
} }
} }
@@ -120,3 +124,28 @@ function removeExistingTitle() {
existingTitle.remove(); existingTitle.remove();
} }
} }
function renderModeratorPlayers(people) {
people.sort();
let teamGood = people.filter((person) => person.alignment === globals.ALIGNMENT.GOOD);
let teamEvil = people.filter((person) => person.alignment === globals.ALIGNMENT.EVIL);
renderGroupOfPlayersFromTeam(teamEvil, globals.ALIGNMENT.EVIL);
renderGroupOfPlayersFromTeam(teamGood, globals.ALIGNMENT.GOOD);
document.getElementById("players-alive-label").innerText =
'Players: ' + people.filter((person) => !person.out).length + ' / ' + people.length + ' Alive';
}
function renderGroupOfPlayersFromTeam(players, alignment) {
for (let player of players) {
let container = document.createElement("div");
container.classList.add('moderator-player');
container.innerHTML = templates.MODERATOR_PLAYER;
container.querySelector('.moderator-player-name').innerText = player.name;
let roleElement = container.querySelector('.moderator-player-role')
roleElement.innerText = player.gameRole;
roleElement.classList.add(alignment);
document.getElementById("player-list-moderator-team-" + alignment).appendChild(container);
}
}

View File

@@ -21,6 +21,10 @@ export const templates = {
"<div id='start-game-prompt'>" + "<div id='start-game-prompt'>" +
"<button id='start-game-button'>Start Game</button>" + "<button id='start-game-button'>Start Game</button>" +
"</div>", "</div>",
END_GAME_PROMPT:
"<div id='end-game-prompt'>" +
"<button id='end-game-button'>End Game</button>" +
"</div>",
GAME: GAME:
"<div id='game-header'>" + "<div id='game-header'>" +
"<div>" + "<div>" +
@@ -48,15 +52,29 @@ export const templates = {
"<label for='game-timer'>Time Remaining</label>" + "<label for='game-timer'>Time Remaining</label>" +
"<div id='game-timer'></div>" + "<div id='game-timer'></div>" +
"</div>" + "</div>" +
"<div id='play-pause'>" + "<div id='play-pause'>" + "</div>" +
"</div>" +
"<button class='moderator-player-button make-mod-button'>Transfer Mod Powers \uD83D\uDD00</button>" +
"</div>" +
"<div>" +
"<label id='players-alive-label'></label>" +
"<div id='player-list-moderator'>" +
"<div class='evil-players'>" +
"<label class='evil'>Team Evil</label>" +
"<div id='player-list-moderator-team-evil'></div>" +
"</div>" +
"<div class='good-players'>" +
"<label class='good'>Team Good</label>" +
"<div id='player-list-moderator-team-good'></div>" +
"</div>" + "</div>" +
"</div>" + "</div>" +
"</div>",
MODERATOR_PLAYER:
"<div>" + "<div>" +
"<label for='alive-count'>Players Left</label>" + "<div class='moderator-player-name'></div>" +
"<div id='alive-count'></div>" + "<div class='moderator-player-role'></div>" +
"</div>" + "</div>" +
"</div>" + "<div>" +
"<div id='player-list-moderator'></div>" + "<button class='moderator-player-button kill-player-button'>Kill \u2694</button>" +
"<button id='end-game-button'>End Game</button>" "</div>"
} }

View File

@@ -34,11 +34,11 @@ function stepFn (expected, interval, start, totalTime) {
} }
const delta = now - expected; const delta = now - expected;
expected += interval; expected += interval;
let displayTime = (totalTime - (expected - start)) < 60000 let displayTime = (totalTime - (now - start)) < 60000
? returnHumanReadableTime(totalTime - (expected - start), true) ? returnHumanReadableTime(totalTime - (now - start), true)
: returnHumanReadableTime(totalTime - (expected - start)); : returnHumanReadableTime(totalTime - (now - start));
postMessage({ postMessage({
timeRemainingInMilliseconds: totalTime - (expected - start), timeRemainingInMilliseconds: totalTime - (now - start),
displayTime: displayTime displayTime: displayTime
}); });
Singleton.setNewTimeoutReference(setTimeout(() => { Singleton.setNewTimeoutReference(setTimeout(() => {

View File

@@ -1,34 +1,40 @@
export const toast = (message, type, positionAtTop = true, dispelAutomatically=true) => { import {globals} from "../config/globals.js";
export const toast = (message, type, positionAtTop = true, dispelAutomatically=true, duration=null) => {
if (message && type) { if (message && type) {
buildAndInsertMessageElement(message, type, positionAtTop, dispelAutomatically); buildAndInsertMessageElement(message, type, positionAtTop, dispelAutomatically, duration);
} }
}; };
function buildAndInsertMessageElement (message, type, positionAtTop, dispelAutomatically) { function buildAndInsertMessageElement (message, type, positionAtTop, dispelAutomatically, duration) {
cancelCurrentToast(); cancelCurrentToast();
let backgroundColor; let backgroundColor, border;
const position = positionAtTop ? 'top:3rem;' : 'bottom: 35px;'; const position = positionAtTop ? 'top:2rem;' : 'bottom: 35px;';
switch (type) { switch (type) {
case 'warning': case 'warning':
backgroundColor = '#fff5b1'; backgroundColor = '#fff5b1';
border = '3px solid #c7c28a';
break; break;
case 'error': case 'error':
backgroundColor = '#fdaeb7'; backgroundColor = '#fdaeb7';
border = '3px solid #c78a8a';
break; break;
case 'success': case 'success':
backgroundColor = '#bef5cb'; backgroundColor = '#bef5cb';
border = '3px solid #8ac78a;'
break; break;
} }
let durationInSeconds = duration ? duration + 's' : globals.TOAST_DURATION_DEFAULT + 's';
let animation = ''; let animation = '';
if (dispelAutomatically) { if (dispelAutomatically) {
animation = 'animation:fade-in-slide-down-then-exit 6s ease normal forwards'; animation = 'animation:fade-in-slide-down-then-exit ' + durationInSeconds + ' ease normal forwards';
} else { } else {
animation = 'animation:fade-in-slide-down 6s ease normal forwards'; animation = 'animation:fade-in-slide-down ' + durationInSeconds + ' ease normal forwards';
} }
const messageEl = document.createElement("div"); const messageEl = document.createElement("div");
messageEl.setAttribute("id", "current-info-message"); messageEl.setAttribute("id", "current-info-message");
messageEl.setAttribute("style", 'background-color:' + backgroundColor + ';' + position + animation); messageEl.setAttribute("style", 'background-color:' + backgroundColor + ';' + 'border:' + border + ';' + position + animation);
messageEl.setAttribute("class", 'info-message'); messageEl.setAttribute("class", 'info-message');
messageEl.innerText = message; messageEl.innerText = message;
document.body.prepend(messageEl); document.body.prepend(messageEl);

View File

@@ -6,14 +6,17 @@ import {cancelCurrentToast, toast} from "../modules/Toast.js";
import {GameTimerManager} from "../modules/GameTimerManager.js"; import {GameTimerManager} from "../modules/GameTimerManager.js";
export const game = () => { export const game = () => {
let timerWorker = new Worker('../modules/Timer.js'); let timerWorker;
const socket = io('/in-game'); const socket = io('/in-game');
socket.on('disconnect', () => { socket.on('disconnect', () => {
timerWorker.terminate(); if (timerWorker) {
timerWorker.terminate();
}
toast('Disconnected. Attempting reconnect...', 'error', true, false); toast('Disconnected. Attempting reconnect...', 'error', true, false);
}); });
socket.on('connect', () => { socket.on('connect', () => {
socket.emit(globals.COMMANDS.GET_ENVIRONMENT, function(returnedEnvironment) { socket.emit(globals.COMMANDS.GET_ENVIRONMENT, function(returnedEnvironment) {
timerWorker = new Worker('../modules/Timer.js');
prepareGamePage(returnedEnvironment, socket, timerWorker); prepareGamePage(returnedEnvironment, socket, timerWorker);
}); });
}) })
@@ -26,9 +29,9 @@ function prepareGamePage(environment, socket, timerWorker) {
if (/^[a-zA-Z0-9]+$/.test(accessCode) && accessCode.length === globals.ACCESS_CODE_LENGTH) { if (/^[a-zA-Z0-9]+$/.test(accessCode) && accessCode.length === globals.ACCESS_CODE_LENGTH) {
socket.emit(globals.COMMANDS.FETCH_GAME_STATE, accessCode, userId, function (gameState) { socket.emit(globals.COMMANDS.FETCH_GAME_STATE, accessCode, userId, function (gameState) {
if (gameState === null) { if (gameState === null) {
window.location = '/not-found' window.location = '/not-found?reason=' + encodeURIComponent('game-not-found');
} else { } else {
toast('You are connected.', 'success', true); toast('You are connected.', 'success', true, true, 3);
console.log(gameState); console.log(gameState);
userId = gameState.client.id; userId = gameState.client.id;
UserUtility.setAnonymousUserId(userId, environment); UserUtility.setAnonymousUserId(userId, environment);
@@ -43,7 +46,7 @@ function prepareGamePage(environment, socket, timerWorker) {
} }
}); });
} else { } else {
window.location = '/not-found'; window.location = '/not-found?reason=' + encodeURIComponent('invalid-access-code');
} }
} }
@@ -64,16 +67,25 @@ function processGameState (gameState, userId, socket, gameStateRenderer) {
} }
break; break;
case globals.STATUS.IN_PROGRESS: case globals.STATUS.IN_PROGRESS:
document.querySelector("#start-game-prompt")?.remove();
gameStateRenderer.gameState = gameState; gameStateRenderer.gameState = gameState;
gameStateRenderer.renderGameHeader(); gameStateRenderer.renderGameHeader();
if (gameState.client.userType === globals.USER_TYPES.PLAYER || gameState.client.userType === globals.USER_TYPES.TEMPORARY_MODERATOR) { switch (gameState.client.userType) {
document.getElementById("game-state-container").innerHTML = templates.GAME; case globals.USER_TYPES.PLAYER:
gameStateRenderer.renderPlayerRole(); document.getElementById("game-state-container").innerHTML = templates.GAME;
} else if (gameState.client.userType === globals.USER_TYPES.MODERATOR) { gameStateRenderer.renderPlayerRole();
document.getElementById("game-state-container").innerHTML = templates.MODERATOR_GAME_VIEW; break;
gameStateRenderer.renderModeratorView(); case globals.USER_TYPES.MODERATOR:
document.querySelector("#start-game-prompt")?.remove();
document.getElementById("game-state-container").innerHTML = templates.MODERATOR_GAME_VIEW;
gameStateRenderer.renderModeratorView();
break;
case globals.USER_TYPES.TEMPORARY_MODERATOR:
document.querySelector("#start-game-prompt")?.remove();
break;
default:
break;
} }
socket.emit(globals.COMMANDS.GET_TIME_REMAINING, gameState.accessCode); socket.emit(globals.COMMANDS.GET_TIME_REMAINING, gameState.accessCode);
break; break;
default: default:

View File

@@ -134,8 +134,9 @@ h1 {
} }
#game-timer { #game-timer {
padding: 1px; padding: 10px;
background-color: #3c3c3c; margin-top: 5px;
background-color: #262626;
color: whitesmoke; color: whitesmoke;
border-radius: 3px; border-radius: 3px;
font-size: 35px; font-size: 35px;
@@ -228,7 +229,7 @@ label[for='moderator'] {
font-size: 30px; font-size: 30px;
} }
#start-game-prompt { #start-game-prompt, #end-game-prompt {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
@@ -252,10 +253,9 @@ label[for='moderator'] {
background-color: #333243; background-color: #333243;
} }
#start-game-button { #start-game-button, #end-game-button {
font-family: 'signika-negative', sans-serif !important; font-family: 'signika-negative', sans-serif !important;
padding: 10px; padding: 10px;
background-color: #1c8a36;
border-radius: 3px; border-radius: 3px;
color: whitesmoke; color: whitesmoke;
font-size: 30px; font-size: 30px;
@@ -265,14 +265,28 @@ label[for='moderator'] {
text-shadow: 0 3px 4px rgb(0 0 0 / 85%); text-shadow: 0 3px 4px rgb(0 0 0 / 85%);
} }
#start-game-button {
background-color: #1c8a36;
}
#end-game-button {
background-color: #8a1c1c;
}
#start-game-button:hover { #start-game-button:hover {
background-color: #326243; background-color: #326243;
border: 2px solid #1c8a36; border: 2px solid #1c8a36;
} }
#end-game-button:hover {
background-color: #623232;
border: 2px solid #8a1c1c;
}
#play-pause { #play-pause {
display: flex; display: flex;
align-items: center; align-items: center;
margin-left: 1em;
} }
#play-pause img { #play-pause img {
@@ -301,6 +315,7 @@ label[for='moderator'] {
flex-wrap: wrap; flex-wrap: wrap;
align-items: center; align-items: center;
justify-content: space-evenly; justify-content: space-evenly;
flex-direction: column;
} }
.timer-container-moderator { .timer-container-moderator {
@@ -308,6 +323,81 @@ label[for='moderator'] {
flex-wrap: wrap; flex-wrap: wrap;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
margin-bottom: 1em;
}
.moderator-player {
border-left: 2px solid gray;
display: flex;
color: #d7d7d7;
background-color: black;
align-items: center;
padding: 0 5px;
justify-content: space-between;
margin: 0.5em 0;
}
.moderator-player-name {
width: 10em;
overflow: hidden;
white-space: nowrap;
font-weight: bold;
font-size: 18px;
text-overflow: ellipsis;
}
.kill-player-button, .make-mod-button {
font-family: 'signika-negative', sans-serif !important;
padding: 5px;
border-radius: 3px;
color: whitesmoke;
font-size: 16px;
cursor: pointer;
border: 2px solid transparent;
transition: background-color, border 0.3s ease-out;
text-shadow: 0 3px 4px rgb(0 0 0 / 55%);
margin: 5px 0 5px 25px;
min-width: 6em;
}
.make-mod-button {
background-color: #3f5256;
font-size: 18px;
padding: 10px;
}
.good-players {
background-color: #1c1a36;
}
.evil-players {
background-color: #361a1a;
}
.kill-player-button {
background-color: #3f5256;
}
#player-list-moderator > div {
padding: 2px 10px;
border-radius: 3px;
margin-bottom: 1em;
}
#players-alive-label {
display: block;
margin-bottom: 10px;
font-size: 25px;
}
@media(max-width: 685px) {
#end-game-button {
font-size: 25px;
}
#end-game-prompt {
height: 85px;
}
} }
@keyframes pulse { @keyframes pulse {

View File

@@ -13,16 +13,16 @@
<link rel="icon" href="/favicon.ico"> <link rel="icon" href="/favicon.ico">
<link rel="icon" href="/favicon.svg" type="image/svg+xml"> <link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/apple-touch-icon.png"> <link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="stylesheet" href="../styles/GLOBAL.css"> <link rel="stylesheet" href="./styles/GLOBAL.css">
<link rel="stylesheet" href="../styles/create.css"> <link rel="stylesheet" href="./styles/create.css">
<link rel="stylesheet" href="../styles/modal.css"> <link rel="stylesheet" href="./styles/modal.css">
<link rel="stylesheet" href="../styles/third_party/dropdown.min.css"> <link rel="stylesheet" href="./styles/third_party/dropdown.min.css">
<link rel="stylesheet" href="../styles/third_party/transition.min.css"> <link rel="stylesheet" href="./styles/third_party/transition.min.css">
<link rel="stylesheet" href="../styles/third_party/search.min.css"> <link rel="stylesheet" href="./styles/third_party/search.min.css">
<script src="../modules/third_party/jQuery/jquery-3.6.0.min.js"></script> <script src="./modules/third_party/jQuery/jquery-3.6.0.min.js"></script>
<script src="../modules/third_party/semantic-ui/transition.min.js"></script> <script src="./modules/third_party/semantic-ui/transition.min.js"></script>
<script src="../modules/third_party/semantic-ui/dropdown.min.js"></script> <script src="./modules/third_party/semantic-ui/dropdown.min.js"></script>
<script src="../modules/third_party/semantic-ui/search.min.js"></script> <script src="./modules/third_party/semantic-ui/search.min.js"></script>
</head> </head>
<body> <body>
<div id="navbar"> <div id="navbar">

View File

@@ -16,8 +16,8 @@
<link rel="icon" href="/favicon.svg" type="image/svg+xml"> <link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/apple-touch-icon.png"> <link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="stylesheet" href="../styles/GLOBAL.css"> <link rel="stylesheet" href="./styles/GLOBAL.css">
<link rel="stylesheet" href="../styles/home.css"> <link rel="stylesheet" href="./styles/home.css">
</head> </head>
<body> <body>
<img src="../images/logo_cropped.gif"/> <img src="../images/logo_cropped.gif"/>
@@ -36,7 +36,7 @@
</form> </form>
</div> </div>
<script type="module"> <script type="module">
import { home } from "../scripts/home.js"; import { home } from "./scripts/home.js";
home(); home();
</script> </script>
<script src="/socket.io/socket.io.js"></script> <script src="/socket.io/socket.io.js"></script>

View File

@@ -90,12 +90,17 @@ app.use('/favicon.ico', (req, res) => {
}); });
const router = require('./routes/router'); const router = require('./routes/router');
const faviconRouter = require('./routes/favicon-router');
const staticRouter = require('./routes/static-router');
app.use('', router); app.use('', router);
app.use('', staticRouter);
app.use('', faviconRouter); app.use('/images', express.static(path.join(__dirname, '../client/images')));
app.use('/scripts', express.static(path.join(__dirname, '../client/scripts')));
app.use('/styles', express.static(path.join(__dirname, '../client/styles')));
app.use('/styles/third-party', express.static(path.join(__dirname, '../client/styles/third_party')));
app.use('/modules/third-party', express.static(path.join(__dirname, '../client/modules/third_party')))
app.use('/modules', express.static(path.join(__dirname, '../client/modules')))
app.use('/model', express.static(path.join(__dirname, '../client/model')))
app.use('/config', express.static(path.join(__dirname, '../client/config')))
app.use('/webfonts', express.static(path.join(__dirname, '../client/webfonts')));
app.use(function (req, res) { app.use(function (req, res) {
res.sendFile(path.join(__dirname, '../client/views/404.html')); res.sendFile(path.join(__dirname, '../client/views/404.html'));

View File

@@ -244,7 +244,16 @@ function handleRequestForGameState(namespace, logger, gameRunner, accessCode, pe
matchingPerson.socketId = socket.id; matchingPerson.socketId = socket.id;
ackFn(GameStateCurator.getGameStateFromPerspectiveOfPerson(game, matchingPerson, gameRunner, socket, logger)); ackFn(GameStateCurator.getGameStateFromPerspectiveOfPerson(game, matchingPerson, gameRunner, socket, logger));
} else { } else {
rejectClientRequestForGameState(ackFn); logger.trace('this person is already associated with a socket connection');
let alreadyConnectedSocket = namespace.connected[matchingPerson.socketId];
if (alreadyConnectedSocket && alreadyConnectedSocket.leave) {
alreadyConnectedSocket.leave(accessCode, ()=> {
logger.trace('kicked existing connection out of room ' + accessCode);
socket.join(accessCode);
matchingPerson.socketId = socket.id;
ackFn(GameStateCurator.getGameStateFromPerspectiveOfPerson(game, matchingPerson, gameRunner, socket, logger));
})
}
} }
} }
} else { } else {
@@ -271,11 +280,13 @@ function handleRequestForGameState(namespace, logger, gameRunner, accessCode, pe
); );
} else { } else {
rejectClientRequestForGameState(ackFn); rejectClientRequestForGameState(ackFn);
logger.trace('this game is full');
} }
} }
} }
} else { } else {
rejectClientRequestForGameState(ackFn); rejectClientRequestForGameState(ackFn);
logger.trace('the game' + accessCode + ' was not found');
} }
} }

View File

@@ -71,7 +71,8 @@ function mapPeopleForModerator(people, client) {
userType: person.userType, userType: person.userType,
gameRole: person.gameRole, gameRole: person.gameRole,
gameRoleDescription: person.gameRoleDescription, gameRoleDescription: person.gameRoleDescription,
alignment: person.alignment alignment: person.alignment,
out: person.out
})); }));
} }
@@ -82,12 +83,13 @@ function mapPeopleForTempModerator(people, client) {
}) })
.map((person) => ({ .map((person) => ({
name: person.name, name: person.name,
userType: person.userType userType: person.userType,
out: person.out
})); }));
} }
function mapPerson(person) { function mapPerson(person) {
return { name: person.name, userType: person.userType }; return { name: person.name, userType: person.userType, out: person.out };
} }
module.exports = GameStateCurator; module.exports = GameStateCurator;

View File

@@ -1,14 +1,14 @@
function stepFn (serverTimerInstance, expected) { function stepFn (serverTimerInstance, expected) {
const now = Date.now(); const now = Date.now(); //
serverTimerInstance.currentTimeInMillis = serverTimerInstance.totalTime - (now - serverTimerInstance.start); serverTimerInstance.currentTimeInMillis = serverTimerInstance.totalTime - (now - serverTimerInstance.start);
if (now - serverTimerInstance.start >= serverTimerInstance.totalTime) { if (now - serverTimerInstance.start >= serverTimerInstance.totalTime) { // check if the time has elapsed
clearTimeout(serverTimerInstance.ticking);
serverTimerInstance.logger.debug( serverTimerInstance.logger.debug(
'ELAPSED: ' + (now - serverTimerInstance.start) + 'ms (~' 'ELAPSED: ' + (now - serverTimerInstance.start) + 'ms (~'
+ (Math.abs(serverTimerInstance.totalTime - (now - serverTimerInstance.start)) / serverTimerInstance.totalTime).toFixed(3) + '% error).' + (Math.abs(serverTimerInstance.totalTime - (now - serverTimerInstance.start)) / serverTimerInstance.totalTime).toFixed(3) + '% error).'
); );
serverTimerInstance.timesUpResolver(); // this is a reference to the callback defined in the construction of the promise in runTimer() serverTimerInstance.timesUpResolver(); // this is a reference to the callback defined in the construction of the promise in runTimer()
clearTimeout(serverTimerInstance.ticking);
return; return;
} }
const delta = now - expected; const delta = now - expected;
@@ -64,10 +64,6 @@ class ServerTimer {
clearTimeout(this.ticking); clearTimeout(this.ticking);
} }
let now = Date.now(); let now = Date.now();
this.logger.debug(
'ELAPSED (PAUSE): ' + (now - this.start) + 'ms (~'
+ (Math.abs(this.totalTime - (now - this.start)) / this.totalTime).toFixed(3) + '% error).'
);
} }
resumeTimer() { resumeTimer() {

View File

@@ -1,18 +0,0 @@
const express = require('express');
const faviconRouter = express.Router();
const path = require('path');
const checkIfFileExists = require("./util");
faviconRouter.use('/client/favicon_package/*', (req, res) => {
let filePath = path.join(__dirname, ('../../' + req.baseUrl));
let extension = path.extname(filePath);
checkIfFileExists(filePath).then((fileExists) => {
if (fileExists && (extension === '.png' || extension === '.ico' || extension === '.svg' || extension === 'xml')) {
res.sendFile(filePath);
} else {
res.sendStatus(404);
}
});
});
module.exports = faviconRouter;

View File

@@ -1,5 +1,5 @@
const express = require('express'); const express = require('express');
const router = express.Router(); const router = express.Router({ strict: true });
const path = require('path'); const path = require('path');
router.get('/', function (request, response) { router.get('/', function (request, response) {

View File

@@ -1,115 +0,0 @@
const express = require('express');
const staticRouter = express.Router();
const path = require('path');
const checkIfFileExists = require("./util");
staticRouter.use('/styles/**', (req, res) => {
let filePath = path.join(__dirname, ('../../client/' + req.baseUrl));
let extension = path.extname(filePath);
checkIfFileExists(filePath).then((fileExists) => {
if (fileExists && (extension === '.css' || extension === '.min.css')) {
res.sendFile(filePath);
} else {
res.sendStatus(404);
}
});
});
staticRouter.use('/client/webfonts/*', (req, res) => {
let filePath = path.join(__dirname, ('../' + req.baseUrl));
let extension = path.extname(filePath);
checkIfFileExists(filePath).then((fileExists) => {
if (fileExists && (extension === '.ttf' || extension === '.woff2')) {
res.sendFile(filePath);
} else {
res.sendStatus(404);
}
});
});
staticRouter.use('/images/*', (req, res) => {
let filePath = path.join(__dirname, ('../../client/' + req.baseUrl));
let extension = path.extname(filePath);
checkIfFileExists(filePath).then((fileExists) => {
if (fileExists && (extension === '.svg' || extension === '.png' || extension === '.jpg' || extension === '.gif')) {
res.sendFile(filePath);
} else {
res.sendStatus(404);
}
});
});
staticRouter.use('/scripts/*', (req, res) => {
let filePath = path.join(__dirname, ('../../client/' + req.baseUrl));
let extension = path.extname(filePath);
checkIfFileExists(filePath).then((fileExists) => {
if (fileExists && (extension === '.js')) {
res.sendFile(filePath);
} else {
res.sendStatus(404);
}
});
});
staticRouter.use('/webfonts/*', (req, res) => {
let filePath = path.join(__dirname, ('../../client/' + req.baseUrl));
let extension = path.extname(filePath);
checkIfFileExists(filePath).then((fileExists) => {
if (fileExists && (extension === '.woff2')) {
res.sendFile(filePath);
} else {
res.sendStatus(404);
}
});
});
staticRouter.use('/views/*', (req, res) => {
let filePath = path.join(__dirname, ('../../client/' + req.baseUrl));
let extension = path.extname(filePath);
checkIfFileExists(filePath).then((fileExists) => {
if (fileExists && (extension === '.html')) {
res.sendFile(filePath);
} else {
res.sendFile('../views/404.html');
}
});
});
staticRouter.use('/config/*', (req, res) => {
let filePath = path.join(__dirname, ('../../client/' + req.baseUrl));
let extension = path.extname(filePath);
checkIfFileExists(filePath).then((fileExists) => {
if (fileExists && (extension === '.js')) {
res.sendFile(filePath);
} else {
res.sendFile('../views/404.html');
}
});
});
staticRouter.use('/modules/**', (req, res) => {
let filePath = path.join(__dirname, ('../../client/' + req.baseUrl));
let extension = path.extname(filePath);
checkIfFileExists(filePath).then((fileExists) => {
if (fileExists && (extension === '.js' || extension === '.min.js')) {
res.sendFile(filePath);
} else {
res.sendFile('../views/404.html');
}
});
});
staticRouter.use('/model/**', (req, res) => {
let filePath = path.join(__dirname, ('../../client/' + req.baseUrl));
let extension = path.extname(filePath);
checkIfFileExists(filePath).then((fileExists) => {
if (fileExists && (extension === '.js')) {
res.sendFile(filePath);
} else {
res.sendFile('../views/404.html');
}
});
});
module.exports = staticRouter;