finish apl nuke v1.0.0

main
Ayush Mukherjee 4 years ago
parent cc3f53051f
commit 9393d91a9c

@ -11,9 +11,9 @@ through the CMS for creating/updating data.
- [ ] create data - [ ] create data
- [ ] update data - [ ] update data
- [ ] websocket - [ ] websocket
- [ ] create ws server - [x] create ws server
- [ ] how do you wanna authenticate? - [ ] handle events
- [ ] authentication - [x] authentication
- [ ] create collection - [x] create collection
- [ ] cache tokens on startup - [x] figure out auth
- [ ] allow create, update only on authentication - [ ] casters stuff

@ -1,3 +1,4 @@
NODE_ENV=development NODE_ENV=development
PORT=5000 PORT=5000
CMS_TOKEN= CMS_TOKEN=
MONGO_URI=

14
package-lock.json generated

@ -15,6 +15,7 @@
"helmet": "^4.1.0", "helmet": "^4.1.0",
"mongoose": "^5.11.19", "mongoose": "^5.11.19",
"morgan": "^1.10.0", "morgan": "^1.10.0",
"uuid": "^8.3.2",
"ws": "^7.4.4" "ws": "^7.4.4"
}, },
"devDependencies": { "devDependencies": {
@ -2068,6 +2069,14 @@
"node": ">= 0.4.0" "node": ">= 0.4.0"
} }
}, },
"node_modules/uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/vary": { "node_modules/vary": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
@ -3736,6 +3745,11 @@
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=" "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM="
}, },
"uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="
},
"vary": { "vary": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",

@ -18,6 +18,7 @@
"helmet": "^4.1.0", "helmet": "^4.1.0",
"mongoose": "^5.11.19", "mongoose": "^5.11.19",
"morgan": "^1.10.0", "morgan": "^1.10.0",
"uuid": "^8.3.2",
"ws": "^7.4.4" "ws": "^7.4.4"
}, },
"devDependencies": { "devDependencies": {

@ -1,5 +1,8 @@
const express = require('express') const express = require('express')
const axios = require('axios') const axios = require('axios')
const { v4 } = require('uuid')
const { push } = require('../uuids')
const router = express.Router() const router = express.Router()
@ -16,12 +19,14 @@ router.post('/', async (req, res) => {
}, },
}) })
if (r.data.entries.length === 1) { if (r.data.entries.length === 1) {
const id = v4();
push(id)
res.json({ res.json({
message: r.data.entries.length session: id,
}) })
} else { } else {
res.status(403).json({ res.status(403).json({
message: r.data.entries, message: 'Forbidden',
}) })
} }
} catch(e) { } catch(e) {

@ -1,6 +1,17 @@
const mongoose = require('mongoose')
const WebSocket = require('ws') const WebSocket = require('ws')
const url = require('url') const url = require('url')
const app = require('./app') const app = require('./app')
const { get } = require('./uuids')
const handler = require('./ws/handler')
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
const db = mongoose.connection
db.once('open', () => console.log('Connected to mongodb instance!'))
const port = process.env.PORT || 5000; const port = process.env.PORT || 5000;
@ -8,11 +19,9 @@ wss = new WebSocket.Server({
noServer: true, noServer: true,
}) })
wss.on('connection', (ws) => { wss.on('connection', (ws, req) => {
ws.on('message', (msg) => { const id = req.id
console.log(`received ${msg}`); handler(ws, id)
})
ws.send('something');
}) })
const server = app.listen(port, () => { const server = app.listen(port, () => {
@ -20,9 +29,11 @@ const server = app.listen(port, () => {
}) })
server.on('upgrade', (req, socket, head) => { server.on('upgrade', (req, socket, head) => {
const pathname = url.parse(req.url).pathname const pathname = url.parse(req.url).pathname.split('/')
if (pathname === '/ws') { const token = pathname[2]
if (pathname[1] === 'ws' && get(token)) {
wss.handleUpgrade(req, socket, head, (socket) => { wss.handleUpgrade(req, socket, head, (socket) => {
req.id = token
wss.emit('connection', socket, req); wss.emit('connection', socket, req);
}) })
} }

@ -0,0 +1,24 @@
const { Schema, model } = require('mongoose')
const casters = new Schema({
username: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
twitter: {
type: String,
required: true,
},
image: {
type: String,
required: true,
},
});
const Caster = model('Casters', casters)
module.exports = Caster

@ -1,10 +1,13 @@
import { Schema, model } from 'mongoose'; const mongoose = require('mongoose');
const events = new Schema({ const events = new mongoose.Schema({
name: { name: {
type: String, type: String,
required: true, required: true,
unique: true,
}, },
}); });
export default model('Events', events); const Event = mongoose.model('Events', events)
module.exports = Event

@ -0,0 +1,24 @@
const { Schema, model } = require('mongoose')
const hosts = new Schema({
username: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
twitter: {
type: String,
required: true,
},
image: {
type: String,
required: true,
},
});
const Host = model('Hosts', hosts)
module.exports = Host

@ -1,4 +1,4 @@
import { Schema, model } from 'mongoose'; const { Schema, model } = require('mongoose')
const gameScores = new Schema({ const gameScores = new Schema({
orange: { orange: {
@ -9,16 +9,16 @@ const gameScores = new Schema({
type: Number, type: Number,
required: true, required: true,
}, },
}); })
const matches = new Schema({ const matches = new Schema({
orange: { orange: {
type: Schema.types.ObjectId, type: Schema.Types.ObjectId,
refs: 'Rosters', refs: 'Rosters',
required: true, required: true,
}, },
blue: { blue: {
type: Schema.types.ObjectId, type: Schema.Types.ObjectId,
refs: 'Rosters', refs: 'Rosters',
required: true, required: true,
}, },
@ -52,6 +52,8 @@ const matches = new Schema({
type: [gameScores], type: [gameScores],
required: true, required: true,
}, },
}); })
export default model('Matches', matches); const Match = model('Matches', matches)
module.exports = Match

@ -1,4 +1,4 @@
import { Schema, model } from 'mongoose'; const { Schema, model } = require('mongoose')
const stats = new Schema({ const stats = new Schema({
goals: { goals: {
@ -21,7 +21,7 @@ const stats = new Schema({
type: Number, type: Number,
required: true, required: true,
}, },
}); })
const players = new Schema({ const players = new Schema({
name: { name: {
@ -36,11 +36,11 @@ const players = new Schema({
type: [stats], type: [stats],
required: true, required: true,
}, },
}); })
const rosters = new Schema({ const rosters = new Schema({
event: { event: {
type: Schema.types.ObjectId, type: Schema.Types.ObjectId,
ref: 'Events', ref: 'Events',
required: true, required: true,
}, },
@ -56,6 +56,8 @@ const rosters = new Schema({
type: [players], type: [players],
required: true, required: true,
}, },
}); })
export default model('Rosters', rosters); const Roster = model('Rosters', rosters)
module.exports = Roster

@ -1,4 +1,4 @@
import { Schema, model } from 'mongoose'; const { Schema, model } = require('mongoose')
const streams = new Schema({ const streams = new Schema({
name: { name: {
@ -6,15 +6,17 @@ const streams = new Schema({
required: true, required: true,
}, },
event: { event: {
type: Schema.types.ObjectId, type: Schema.Types.ObjectId,
refs: 'Events', refs: 'Events',
requried: true, requried: true,
}, },
matches: { matches: {
type: [Schema.types.ObjectId], type: [Schema.Types.ObjectId],
refs: 'matches', refs: 'matches',
requried: true, requried: true,
}, },
}); })
export default model('Streams', streams); const Stream = model('Streams', streams)
module.exports = Stream

@ -0,0 +1,21 @@
let uuids = [];
const get = (id) => {
if (uuids.indexOf(id) !== -1)
return true;
return false;
}
const push = (id) => {
uuids.push(id)
}
const pop = (id) => {
uuids = uuids.filter((x) => x !== id)
}
module.exports = {
get,
push,
pop
};

@ -0,0 +1,29 @@
const channels = [
'rosters',
'matches',
'streams',
'events',
'casters',
'hosts',
];
const events = [
'create',
'read',
'update',
'delete',
];
const channelEvents = [];
channels.forEach((c) => {
events.forEach((e) => {
channelEvents.push(`${c}:${e}`);
});
})
module.exports = {
channelEvents,
channels,
events,
};

@ -0,0 +1,171 @@
const events = require('../models/events')
const rosters = require('../models/rosters')
const matches = require('../models/matches')
const streams = require('../models/streams')
const casters = require('../models/casters')
const hosts = require('../models/hosts')
const eventFns = {
getAll: async () => {
return await events.find().exec()
},
getById: async (id) => {
return await events.findById(id).exec()
},
update: async(id, data) => {
return await events.findByIdAndUpdate(id, data).exec()
},
delete: async (id) => {
return await events.findByIdAndDelete(id).exec()
},
create: async (data) => {
try {
const ev = new events(data)
ev.save((err) => {
if (err)
throw err;
})
} catch (e) {
throw e;
}
}
}
const rosterFns = {
getAll: async () => {
return await rosters.find().exec()
},
getById: async (id) => {
return await rosters.findById(id).exec()
},
update: async(id, data) => {
return await rosters.findByIdAndUpdate(id, data).exec()
},
delete: async (id) => {
return await rosters.findByIdAndDelete(id).exec()
},
create: async (data) => {
try {
const ev = new rosters(data)
ev.save((err) => {
if (err)
throw err;
})
} catch (e) {
throw e;
}
}
}
const matchFns = {
getAll: async () => {
return await matches.find().exec()
},
getById: async (id) => {
return await matches.findById(id).exec()
},
update: async(id, data) => {
return await matches.findByIdAndUpdate(id, data).exec()
},
delete: async (id) => {
return await matches.findByIdAndDelete(id).exec()
},
create: async (data) => {
try {
const ev = new matches(data)
ev.save((err) => {
if (err)
throw err;
})
} catch (e) {
throw e;
}
}
}
const streamFns = {
getAll: async () => {
return await streams.find().exec()
},
getById: async (id) => {
return await streams.findById(id).exec()
},
update: async(id, data) => {
return await streams.findByIdAndUpdate(id, data).exec()
},
delete: async (id) => {
return await streams.findByIdAndDelete(id).exec()
},
create: async (data) => {
try {
const ev = new streams(data)
ev.save((err) => {
if (err)
throw err;
})
} catch (e) {
throw e;
}
}
}
const casterFns = {
getAll: async () => {
return await casters.find().exec()
},
getById: async (id) => {
return await casters.findById(id).exec()
},
update: async(id, data) => {
return await casters.findByIdAndUpdate(id, data).exec()
},
delete: async (id) => {
return await casters.findByIdAndDelete(id).exec()
},
create: async (data) => {
try {
const ev = new casters(data)
ev.save((err) => {
if (err)
throw err;
})
} catch (e) {
throw e;
}
}
}
const hostFns = {
getAll: async () => {
return await hosts.find().exec()
},
getById: async (id) => {
return await hosts.findById(id).exec()
},
update: async(id, data) => {
return await hosts.findByIdAndUpdate(id, data).exec()
},
delete: async (id) => {
return await hosts.findByIdAndDelete(id).exec()
},
create: async (data) => {
try {
const ev = new hosts(data)
ev.save((err) => {
if (err)
throw err;
})
} catch (e) {
throw e;
}
}
}
module.exports = {
'events': eventFns,
'rosters': rosterFns,
'matches': matchFns,
'streams': streamFns,
'casters': casterFns,
'hosts': hostFns,
}

@ -0,0 +1,65 @@
const { pop } = require('../uuids')
const { channelEvents } = require('./channels')
const crud = require('./crud')
const connections = {};
const handler = (ws, id) => {
connections[id] = {
connection: ws,
events: [],
}
ws.send(JSON.stringify({
event: 'info',
data: 'Welcome to APL Nuke v1.0.0!'
}))
ws.on('message', (msg) => handleMsg(msg, id))
ws.on('close', () => {
delete connections[id]
pop(id)
})
}
const handleMsg = async (msg, id) => {
try {
const d = JSON.parse(msg)
if (d.hasOwnProperty('subscribe') && channelEvents.indexOf(d.subscribe) !== -1) {
const channel = d.subscribe.split(':')[0]
connections[id].events.push(d.subscribe)
connections[id].connection.send(JSON.stringify(await crud[channel].getAll()))
} else if (d.hasOwnProperty('event') && channelEvents.indexOf(d.event) !== -1) {
const ev = d.event.split(':')
const channel = ev[0]
const event = ev[1]
console.log(`received event for ${channel} with data %s`, d.data)
switch (event) {
case 'create':
await crud[channel].create(d.data)
fanoutMsg(channel, await crud[channel].getAll())
break;
case 'update':
await crud[channel].update(d.data.id, d.data.data)
fanoutMsg(channel, await crud[channel].getAll())
break;
case 'delete':
await crud[channel].delete(d.data.id)
fanoutMsg(channel, await crud[channel].getAll())
break;
}
}
} catch (e) {
console.log(e)
}
}
const fanoutMsg = (channel, data) => {
Object.keys(connections).forEach((k) => {
if (connections[k].events.indexOf(`${channel}:read`) !== -1) {
connections[k].connection.send(JSON.stringify(data))
}
})
}
module.exports = handler

@ -1,5 +0,0 @@
const WebSocket = require('ws')
let wss = null
module.exports = wss;
Loading…
Cancel
Save