Fix server code style with prettier (#136)

This commit is contained in:
Jérémie Pardou-Piquemal 2020-05-07 14:25:41 +02:00 committed by GitHub
parent be81d7420c
commit a923e91bf5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 39 additions and 53 deletions

7
.prettierrc Normal file
View File

@ -0,0 +1,7 @@
{
"trailingComma": "all",
"tabWidth": 2,
"singleQuote": true,
"arrowParens": "avoid",
"printWidth": 120
}

View File

@ -1,7 +1,4 @@
{ {
"presets": ["@babel/preset-env"], "presets": ["@babel/preset-env"],
"plugins": [ "plugins": ["@babel/plugin-transform-async-to-generator", "@babel/plugin-transform-runtime"]
"@babel/plugin-transform-async-to-generator", }
"@babel/plugin-transform-runtime"
]
}

View File

@ -1,7 +1,7 @@
{ {
"parser": "babel-eslint", "parser": "babel-eslint",
"rules": { "rules": {
"semi": ["error", "always"], "semi": ["error", "always"],
"quotes": ["error", "single"] "quotes": ["error", "single"]
} }
} }

View File

@ -1,3 +1,3 @@
# Darkwire Server # Darkwire Server
This is the backend for [Darkwire](https://github.com/darkwire/darkwire.io). It requires [darkwire-client](../client) in order to run. This is the backend for [Darkwire](https://github.com/darkwire/darkwire.io). It requires [darkwire-client](../client) in order to run.

View File

@ -7,16 +7,12 @@ export async function pollForInactiveRooms() {
const rooms = (await store.getAll('rooms')) || {}; const rooms = (await store.getAll('rooms')) || {};
console.log(`${Object.keys(rooms).length} rooms found`); console.log(`${Object.keys(rooms).length} rooms found`);
Object.keys(rooms).forEach(async (roomId) => { Object.keys(rooms).forEach(async roomId => {
const room = JSON.parse(rooms[roomId]); const room = JSON.parse(rooms[roomId]);
const timeSinceUpdatedInSeconds = (Date.now() - room.updatedAt) / 1000; const timeSinceUpdatedInSeconds = (Date.now() - room.updatedAt) / 1000;
const timeSinceUpdatedInDays = Math.round( const timeSinceUpdatedInDays = Math.round(timeSinceUpdatedInSeconds / 60 / 60 / 24);
timeSinceUpdatedInSeconds / 60 / 60 / 24
);
if (timeSinceUpdatedInDays > 7) { if (timeSinceUpdatedInDays > 7) {
console.log( console.log(`Deleting roomId ${roomId} which hasn't been used in ${timeSinceUpdatedInDays} days`);
`Deleting roomId ${roomId} which hasn't been used in ${timeSinceUpdatedInDays} days`
);
await store.del('rooms', roomId); await store.del('rooms', roomId);
} }
}); });

View File

@ -34,19 +34,16 @@ if ((siteURL || env === 'development') && !isReviewApp) {
origin: env === 'development' ? '*' : siteURL, origin: env === 'development' ? '*' : siteURL,
allowMethods: ['GET', 'HEAD', 'POST'], allowMethods: ['GET', 'HEAD', 'POST'],
credentials: true, credentials: true,
}) }),
); );
} }
router.post('/abuse/:roomId', koaBody, async (ctx) => { router.post('/abuse/:roomId', koaBody, async ctx => {
let { roomId } = ctx.params; let { roomId } = ctx.params;
roomId = roomId.trim(); roomId = roomId.trim();
if ( if (process.env.ABUSE_FROM_EMAIL_ADDRESS && process.env.ABUSE_TO_EMAIL_ADDRESS) {
process.env.ABUSE_FROM_EMAIL_ADDRESS &&
process.env.ABUSE_TO_EMAIL_ADDRESS
) {
const abuseForRoomExists = await store.get('abuse', roomId); const abuseForRoomExists = await store.get('abuse', roomId);
if (!abuseForRoomExists) { if (!abuseForRoomExists) {
mailer.send({ mailer.send({
@ -66,9 +63,7 @@ router.post('/abuse/:roomId', koaBody, async (ctx) => {
app.use(router.routes()); app.use(router.routes());
const apiHost = process.env.API_HOST; const apiHost = process.env.API_HOST;
const cspDefaultSrc = `'self'${ const cspDefaultSrc = `'self'${apiHost ? ` https://${apiHost} wss://${apiHost}` : ''}`;
apiHost ? ` https://${apiHost} wss://${apiHost}` : ''
}`;
function setStaticFileHeaders(ctx) { function setStaticFileHeaders(ctx) {
ctx.set({ ctx.set({
@ -78,8 +73,7 @@ function setStaticFileHeaders(ctx) {
'X-XSS-Protection': '1; mode=block', 'X-XSS-Protection': '1; mode=block',
'X-Content-Type-Options': 'nosniff', 'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer', 'Referrer-Policy': 'no-referrer',
'Feature-Policy': 'Feature-Policy': "geolocation 'none'; vr 'none'; payment 'none'; microphone 'none'",
"geolocation 'none'; vr 'none'; payment 'none'; microphone 'none'",
}); });
} }
@ -92,12 +86,12 @@ if (clientDistDirectory) {
})(ctx, next); })(ctx, next);
}); });
app.use(async (ctx) => { app.use(async ctx => {
setStaticFileHeaders(ctx); setStaticFileHeaders(ctx);
await koaSend(ctx, 'index.html', { root: clientDistDirectory }); await koaSend(ctx, 'index.html', { root: clientDistDirectory });
}); });
} else { } else {
app.use(async (ctx) => { app.use(async ctx => {
ctx.body = { ready: true }; ctx.body = { ready: true };
}); });
} }
@ -117,7 +111,7 @@ if (store.hasSocketAdapter) {
const roomHashSecret = process.env.ROOM_HASH_SECRET; const roomHashSecret = process.env.ROOM_HASH_SECRET;
const getRoomIdHash = (id) => { const getRoomIdHash = id => {
if (env === 'development') { if (env === 'development') {
return id; return id;
} }
@ -131,7 +125,7 @@ const getRoomIdHash = (id) => {
export const getIO = () => io; export const getIO = () => io;
io.on('connection', async (socket) => { io.on('connection', async socket => {
const roomId = socket.handshake.query.roomId; const roomId = socket.handshake.query.roomId;
const roomIdHash = getRoomIdHash(roomId); const roomIdHash = getRoomIdHash(roomId);

View File

@ -53,14 +53,14 @@ export default class Socket {
if (getStore().hasSocketAdapter) { if (getStore().hasSocketAdapter) {
getIO() getIO()
.of('/') .of('/')
.adapter.remoteJoin(socket.id, roomId, (err) => { .adapter.remoteJoin(socket.id, roomId, err => {
if (err) { if (err) {
reject(); reject();
} }
resolve(); resolve();
}); });
} else { } else {
socket.join(roomId, (err) => { socket.join(roomId, err => {
if (err) { if (err) {
reject(); reject();
} }
@ -71,11 +71,11 @@ export default class Socket {
} }
async handleSocket(socket) { async handleSocket(socket) {
socket.on('ENCRYPTED_MESSAGE', (payload) => { socket.on('ENCRYPTED_MESSAGE', payload => {
socket.to(this._roomId).emit('ENCRYPTED_MESSAGE', payload); socket.to(this._roomId).emit('ENCRYPTED_MESSAGE', payload);
}); });
socket.on('USER_ENTER', async (payload) => { socket.on('USER_ENTER', async payload => {
let room = await this.fetchRoom(); let room = await this.fetchRoom();
if (_.isEmpty(room)) { if (_.isEmpty(room)) {
room = { room = {
@ -109,9 +109,7 @@ export default class Socket {
socket.on('TOGGLE_LOCK_ROOM', async (data, callback) => { socket.on('TOGGLE_LOCK_ROOM', async (data, callback) => {
const room = await this.fetchRoom(); const room = await this.fetchRoom();
const user = (room.users || []).find( const user = (room.users || []).find(u => u.socketId === socket.id && u.isOwner);
(u) => u.socketId === socket.id && u.isOwner
);
if (!user) { if (!user) {
callback({ callback({
@ -146,7 +144,7 @@ export default class Socket {
const newRoom = { const newRoom = {
...room, ...room,
users: (room.users || []) users: (room.users || [])
.filter((u) => u.socketId !== socket.id) .filter(u => u.socketId !== socket.id)
.map((u, index) => ({ .map((u, index) => ({
...u, ...u,
isOwner: index === 0, isOwner: index === 0,

View File

@ -42,7 +42,6 @@ export class MemoryStore {
this.store[key][field] += inc; this.store[key][field] += inc;
return this.store[key][field]; return this.store[key][field];
} }
} }
export default MemoryStore export default MemoryStore;

View File

@ -34,9 +34,9 @@ export class RedisStore {
return this.redis.incrbyAsync(key, field, inc); return this.redis.incrbyAsync(key, field, inc);
} }
getSocketAdapter() { getSocketAdapter() {
return socketRedis(this.redisUrl); return socketRedis(this.redisUrl);
} }
} }
export default RedisStore export default RedisStore;

View File

@ -1,9 +1,6 @@
require('dotenv').config() require('dotenv').config();
const { const { MAILGUN_API_KEY, MAILGUN_DOMAIN } = process.env;
MAILGUN_API_KEY,
MAILGUN_DOMAIN,
} = process.env;
const apiKey = MAILGUN_API_KEY; const apiKey = MAILGUN_API_KEY;
const domain = MAILGUN_DOMAIN; const domain = MAILGUN_DOMAIN;
@ -11,14 +8,12 @@ const domain = MAILGUN_DOMAIN;
let mailgun; let mailgun;
if (apiKey && domain) { if (apiKey && domain) {
mailgun = require('mailgun-js')({apiKey, domain}); mailgun = require('mailgun-js')({ apiKey, domain });
} }
module.exports.send = (data) => { module.exports.send = data => {
if (!mailgun) { if (!mailgun) {
return; return;
} }
mailgun.messages().send(data, function (error, body) { mailgun.messages().send(data, function (error, body) {});
};
});
}