Skip to content

Commit

Permalink
ML-139 event resolve and cancel emit user message
Browse files Browse the repository at this point in the history
  • Loading branch information
wholespace214 committed Oct 27, 2021
1 parent fd3de13 commit 194cb97
Show file tree
Hide file tree
Showing 14 changed files with 370 additions and 161 deletions.
21 changes: 5 additions & 16 deletions controllers/chats-controller.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,6 @@
const dotenv = require('dotenv');
dotenv.config();

const { validationResult } = require('express-validator');
const chatMessageService = require('../services/chat-message-service');
const { ErrorHandler } = require('../util/error-handler');

exports.getChatMessagesByRoom = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(new ErrorHandler(422, 'Invalid input passed, please check it'));
}

exports.getChatMessagesByRoom = async (req, res) => {
const skip = req.query.skip ? +req.query.skip : 0;
const limit = req.query.limit ? +req.query.limit : 20;

Expand All @@ -20,9 +10,8 @@ exports.getChatMessagesByRoom = async (req, res, next) => {
skip
);

res.status(200)
.json({
messages: messages?.data || [],
total: messages?.total || 0,
});
res.status(200).json({
messages: messages?.data || [],
total: messages?.total || 0,
});
};
57 changes: 57 additions & 0 deletions controllers/user-messages-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const websocketService = require('../services/websocket-service');
const chatMessageService = require('../services/chat-message-service');
const eventService = require('../services/event-service');
const _ = require('lodash');

exports.getMessagesByUser = async (req, res) => {
const skip = req.query.skip ? +req.query.skip : 0;
const limit = req.query.limit ? +req.query.limit : 20;

const messages = await chatMessageService.getLatestChatMessagesByUserId(
req.user._id,
limit,
skip
);

res.status(200).json({
messages: messages?.data || [],
total: messages?.total || 0,
});
};

exports.setMessageRead = async (req, res) => {
const { id } = req.params;
const requestingUser = req.user;
await chatMessageService.setMessageRead(id, requestingUser);
return res.status(200).send();
};

exports.sendMessage = async (req, res) => {
// console.log('sending a test message');

// // SEND OASIS EVENT RESOLVED
// setTimeout(async () => {
// const event = await eventService.getEvent('61792b2bc986908179b4e4b5');
// event.bookmarks.map(async (u) => {
// await websocketService.emitBetResolveNotification(u, event, event.bets[0], 0, 100);
// });
// }, 2000);

// // SEND ELON EVENT RESOLVED
// setTimeout(async () => {
// const event = await eventService.getEvent('617950d40a97aa8c14679fd0');
// event.bookmarks.map(async (u) => {
// await websocketService.emitBetResolveNotification(u, event, event.bets[0], 0, 0);
// });
// }, 4500);

// // SEND UEFA CANCELLED
// setTimeout(async () => {
// const event = await eventService.getEvent('61797d87fce07aa1dfc00b5c');
// event.bookmarks.map(async (u) => {
// await websocketService.emitEventCancelNotification(u, event, event.bets[0]);
// });
// }, 18000);

return res.status(200).send({});
};
7 changes: 7 additions & 0 deletions helper/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
/**
* @param {} req
* returns if the user is an admin and if a userId url param was passed and equal
* to the logged in user.
* TODO: replace with utils/auth.isUserAdminOrSelf
*/
exports.isAdmin = (req) => !(req.user.admin === false && req.params.userId !== req.user.id);

exports.generate = (n) => {
const add = 1;
let max = 12 - add;
Expand Down
29 changes: 14 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,7 @@ let mongoURL = process.env.DB_CONNECTION;
const corsOptions = {
origin: '*',
credentials: true,
allowedMethods: [
'GET',
'PUT',
'POST',
'PATCH',
'DELETE',
],
allowedMethods: ['GET', 'PUT', 'POST', 'PATCH', 'DELETE'],
allowedHeaders: [
'Origin',
'X-Requested-With',
Expand All @@ -41,7 +35,7 @@ const corsOptions = {
],
exposedHeaders: ['Content-Length'],
preflightContinue: false,
}
};

// Connection to Database
async function connectMongoDB() {
Expand Down Expand Up @@ -84,10 +78,6 @@ async function main() {
// Import cors
const cors = require('cors');

// Import middleware for jwt verification
const passport = require('passport');
require('./util/auth');

// Initialise server using express
const server = express();
const httpServer = http.createServer(server);
Expand Down Expand Up @@ -135,9 +125,13 @@ async function main() {

subClient.subscribe('message');

// Giving server ability to parse json
// Jwt verification
const passport = require('passport');
const auth = require('./util/auth');
auth.setPassportStrategies();
server.use(passport.initialize());
server.use(passport.session());
server.use(auth.evaluateIsAdmin);
adminService.buildRouter();

server.use(adminService.getRootPath(), adminService.getRouter());
Expand All @@ -163,11 +157,11 @@ async function main() {
const chatRoutes = require('./routes/users/chat-routes');
const notificationEventsRoutes = require('./routes/users/notification-events-routes');
const authRoutes = require('./routes/auth/auth-routes');
const userMessagesRoutes = require('./routes/users/user-messages-routes');

const auth0ShowcaseRoutes = require('./routes/auth0-showcase-routes');
server.use(auth0ShowcaseRoutes);


// Using Routes
server.use('/api/event', eventRoutes);
server.use('/api/event', passport.authenticate('jwt', { session: false }), secureEventRoutes);
Expand All @@ -180,9 +174,14 @@ async function main() {
secureBetTemplateRoute
);
server.use('/webhooks/twitch/', twitchWebhook);
server.use('/api/chat', chatRoutes);
server.use('/api/chat', passport.authenticate('jwt', { session: false }), chatRoutes);
server.use('/api/notification-events', notificationEventsRoutes);
server.use('/api/auth', authRoutes);
server.use(
'/api/user-messages',
passport.authenticate('jwt', { session: false }),
userMessagesRoutes
);

// Error handler middleware
// eslint-disable-next-line no-unused-vars
Expand Down
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions routes/users/chat-routes.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
const router = require('express').Router();
const { check } = require('express-validator');
const chatsController = require('../../controllers/chats-controller');
const { validateRequest } = require('../../util/request-validator');

router.get(
'/chat-messages/:roomId',
[check('roomId').notEmpty()],
chatsController.getChatMessagesByRoom,
[check('roomId').notEmpty(), check('roomId').isMongoId()],
validateRequest(chatsController.getChatMessagesByRoom)
);

module.exports = router;
16 changes: 16 additions & 0 deletions routes/users/user-messages-routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const router = require('express').Router();
const { check } = require('express-validator');
const { validateRequest } = require('../../util/request-validator');
const controller = require('../../controllers/user-messages-controller');

router.get('/', controller.getMessagesByUser);

router.put('/:id/read', [check('id').isMongoId()], validateRequest(controller.setMessageRead));

router.post(
'/',
[check('userId').exists(), check('userId'.isMongoId)],
validateRequest(controller.sendMessage)
);

module.exports = router;
32 changes: 19 additions & 13 deletions services/admin-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const AdminBro = require('admin-bro');
const AdminBroExpress = require('@admin-bro/express');
const AdminBroMongoose = require('@admin-bro/mongoose');
const { Router } = require('express');
const _ = require('lodash');

AdminBro.registerAdapter(AdminBroMongoose);

Expand Down Expand Up @@ -148,14 +149,12 @@ exports.initialize = function () {

if (dbBet) {
const event = await eventService.getEvent(dbBet.event);

if (event.bookmarks) {
// union of users who placed a bet and have bookmarked the event
userIds = _.union(userIds, event.bookmarks);
}
for (const userId of userIds) {
websocketService.emitEventCancelNotification(
userId,
dbBet.event,
event.name,
dbBet.reasonOfCancellation
);
websocketService.emitEventCancelNotification(userId, event, dbBet);
}
}

Expand Down Expand Up @@ -191,7 +190,7 @@ exports.initialize = function () {
const indexOutcome = request.fields.index;
const { evidenceActual } = request.fields;
const { evidenceDescription } = request.fields;

let stillToNotifyUsersIds = event.bookmarks;
if (bet.status !== 'active' && bet.status !== 'closed') {
context.record.params.message =
'Event can only be resolved if it is active or closed';
Expand Down Expand Up @@ -256,15 +255,22 @@ exports.initialize = function () {
await userService.increaseAmountWon(userId, winToken);

// send notification to this user
websocketService.emitBetResolveNotification(
await websocketService.emitBetResolveNotification(
userId,
id,
bet.marketQuestion,
bet.outcomes[indexOutcome].name,
event,
bet,
Math.round(investedValues[userId]),
event.previewImageUrl,
winToken
);
stillToNotifyUsersIds = stillToNotifyUsersIds.filter((u) => u != userId);
}

if (stillToNotifyUsersIds) {
// the users who bookmarked but didn't place a bet
stillToNotifyUsersIds.map(
async (u) =>
await websocketService.emitEventResolvedNotification(u, event, bet)
);
}
}
return {
Expand Down
32 changes: 11 additions & 21 deletions services/bet-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@ const { toScaledBigInt, fromScaledBigInt } = require('../util/number-helper');
const { calculateAllBetsStatus, filterPublishedBets } = require('../services/event-service');

exports.listBets = async (q) => {
return Bet.find(q).populate('event')
.map(calculateAllBetsStatus)
.map(filterPublishedBets);
}
return Bet.find(q).populate('event').map(calculateAllBetsStatus).map(filterPublishedBets);
};

exports.filterBets = async (
type = 'all',
Expand All @@ -24,7 +22,7 @@ exports.filterBets = async (
status = 'active',
published = true,
resolved = false,
canceled = false,
canceled = false
) => {
const eventQuery = {};
const betQuery = {};
Expand Down Expand Up @@ -64,7 +62,6 @@ exports.filterBets = async (
return result;
};


exports.editBet = async (betId, betData) => {
const updatedEvent = await Bet.findByIdAndUpdate(betId, betData, { new: true });
return updatedEvent;
Expand Down Expand Up @@ -132,7 +129,7 @@ exports.placeBet = async (userId, betId, amount, outcome, minOutcomeTokens) => {
producer: 'user',
producerId: userId,
data: { bet, trade: response.trade, user, event },
broadcast: true
broadcast: true,
});
return response;
} catch (err) {
Expand Down Expand Up @@ -200,7 +197,7 @@ exports.refundUserHistory = async (bet, session) => {
bet,
userIds,
},
broadcast: true
broadcast: true,
});

return userIds;
Expand Down Expand Up @@ -253,7 +250,7 @@ exports.resolve = async ({
producer: 'system',
producerId: 'notification-service',
data: { bet, event },
broadcast: true
broadcast: true,
});
} catch (err) {
console.debug(err);
Expand Down Expand Up @@ -297,18 +294,16 @@ exports.resolve = async ({
producer: 'system',
producerId: 'notification-service',
data: { bet, event, userId, winToken: winToken.toString() },
broadcast: true
broadcast: true,
});

// send notification to this user
websocketService.emitBetResolveNotification(
// eslint-disable-line no-unsafe-finally
userId,
betId,
bet.marketQuestion,
bet.outcomes[outcomeIndex].name,
event,
bet,
+investedValues[userId],
event.previewImageUrl,
winToken
);
}
Expand Down Expand Up @@ -349,14 +344,9 @@ exports.cancel = async (bet, cancellationReason) => {
reasonOfCancellation: dbBet.reasonOfCancellation,
previewImageUrl: event.previewImageUrl,
},
broadcast: true
broadcast: true,
});
websocketService.emitEventCancelNotification(
userId,
dbBet.event,
event.name,
dbBet.reasonOfCancellation
);
websocketService.emitEventCancelNotification(userId, event, dbBet);
}
}

Expand Down
Loading

0 comments on commit 194cb97

Please sign in to comment.