Files
watchparty/functions/index.js
T
2020-04-22 11:17:06 -04:00

300 lines
8.3 KiB
JavaScript

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const secret = require('./FirebaseSecret.json');
const express = require('express');
const cors = require('cors');
const authenticator = (req, res, next) => {
res.set('Access-Control-Allow-Origin', ['*']);
if (req.method === 'OPTIONS') {
res.status(200).send();
return next();
}
const token = req.headers.authorization.split(' ')[1];
const reqToken = token.split(':')[0];
const reqUid = token.split(':')[1];
admin
.auth()
.verifyIdToken(reqToken)
.then((user) => {
if (user.uid === reqUid) {
console.log('Verified Token - UID - ', reqUid);
if (req.method === 'POST') {
const bodydata = JSON.parse(req.body);
bodydata.uid = user.uid;
req.body = JSON.stringify(bodydata);
}
if (req.method === 'GET' || req.method === 'DELETE') {
req.body = JSON.stringify({ uid: user.uid });
}
return next();
} else {
return res.status(401).send('Unauthorized');
}
})
.catch((err) => {
console.log('Failed Auth - ', req.headers.authorization, '\n', err);
return res.status(500).send(err);
});
return null;
};
const createRoom = async (req, res) => {
const bodydata = JSON.parse(req.body);
console.log('Requested Create - UID - ', bodydata.uid);
if (!bodydata.userName) res.status(400).send('Missing user name');
const roomId = await admin
.firestore()
.collection('rooms')
.add({
name: bodydata.roomName,
player: bodydata.player,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
.then((ref) => ref.id)
.catch((err) => {
console.error(err);
});
await admin
.firestore()
.collection('rooms')
.doc(roomId)
.collection('messages')
.add({
uid: '<system>',
name: '',
text: `${bodydata.userName} started the party.`,
time: new Date().toISOString(),
});
await admin
.firestore()
.collection('rooms')
.doc(roomId)
.collection('users')
.doc(bodydata.uid)
.set({
admin: true,
name: bodydata.userName,
});
res.status(201).send({ roomId });
};
const joinRoom = async (req, res) => {
const bodydata = JSON.parse(req.body);
console.log('Requested Join - UID - ', bodydata.uid, '\n\tRoom - ', bodydata.roomId);
const exists = await admin
.firestore()
.collection('rooms')
.doc(bodydata.roomId)
.get()
.then((roomSnap) => roomSnap.exists);
const userExists = await admin
.firestore()
.collection('rooms')
.doc(bodydata.roomId)
.collection('users')
.doc(bodydata.uid)
.get()
.then((userSnap) => userSnap.exists);
if (userExists) res.status(200).send({ roomId: bodydata.roomId });
else if (!userExists && exists && bodydata.roomId && bodydata.userName) {
await admin
.firestore()
.collection('rooms')
.doc(bodydata.roomId)
.collection('messages')
.add({
uid: '<system>',
name: '',
text: `${bodydata.userName} joined the party.`,
time: new Date().toISOString(),
});
await admin
.firestore()
.collection('rooms')
.doc(bodydata.roomId)
.collection('users')
.doc(bodydata.uid)
.set({
admin: false,
name: bodydata.userName,
});
await admin.firestore().collection('rooms').doc(bodydata.roomId).update({
updatedAt: new Date().toISOString(),
});
res.status(200).send({ roomId: bodydata.roomId });
} else if (!userExists && !bodydata.userName)
res.status(400).send({ message: 'Missing user name' });
else res.status(404).send({ message: 'Party Not Found' });
};
const sendMessage = async (req, res) => {
const { name, text, time, uid, roomId } = JSON.parse(req.body);
await admin
.firestore()
.collection('rooms')
.doc(roomId)
.collection('messages')
.add({
name,
text,
time,
uid,
})
.catch((messageErr) => res.status(500).send(messageErr));
await admin.firestore().collection('rooms').doc(roomId).update({
updatedAt: new Date().toISOString(),
});
res.status(200).send({ message: 'Sent a message' });
};
const leaveRoom = async (req, res) => {
console.log('Requested Leave - UID - ', req.params.uid, '\n\tRoom - ', req.params.rid);
await admin
.firestore()
.collection('rooms')
.doc(req.params.rid)
.collection('users')
.doc(req.params.uid)
.delete()
.catch((err) => res.status(500).send(err));
res.status(200).send({ message: 'Left the party' });
};
const deleteRoom = async (req, res) => {
console.log('Requested Delete - Room - ', req.params.rid);
console.log(req.body);
const isAdmin = await admin
.firestore()
.collection('rooms')
.doc(req.params.rid)
.collection('users')
.doc(JSON.parse(req.body).uid)
.get()
.then((v) => {
if (v.exists) {
return v.data().admin;
}
return false;
});
if (!isAdmin) {
console.log('[UNAUTHORIZED] Requested Delete - Room - ', req.params.rid);
res.status(401).send({ message: 'Not authorized to end this party.' });
return;
}
await admin
.firestore()
.collection('rooms')
.doc(req.params.rid)
.collection('messages')
.listDocuments()
.then((messages) => messages.forEach((message) => message.delete()))
.catch((err) => res.status(500).send(err));
await admin
.firestore()
.collection('rooms')
.doc(req.params.rid)
.collection('users')
.listDocuments()
.then((users) => users.forEach((user) => user.delete()))
.catch((err) => res.status(500).send(err));
await admin
.firestore()
.collection('rooms')
.doc(req.params.rid)
.delete()
.catch((err) => res.status(500).send(err));
res.status(200).send({ message: 'Ended the party' });
};
const updatePlayer = async (req, res) => {
const { player, roomId, uid, showChanged, userName } = JSON.parse(req.body);
const statusString =
player.status === 'PLAYING'
? 'started playing from'
: player.status === 'PAUSED'
? 'paused at'
: player.status === 'NOT_PLAYING'
? 'stopped at'
: 'is at';
const timeString =
player.time > 3600
? new Date(player.time * 1000).toISOString().substr(11, 8)
: new Date(player.time * 1000).toISOString().substr(14, 5);
const [roomExists, roomData] = await admin
.firestore()
.collection('rooms')
.doc(roomId)
.get()
.then((docSnap) => [docSnap.exists, docSnap.data()]);
if (!roomExists) return res.status(404).send({ message: 'Party not found.' });
const userExists = await admin
.firestore()
.collection('rooms')
.doc(roomId)
.collection('users')
.doc(uid)
.get()
.then((userSnap) => userSnap.exists);
if (userExists) {
if (showChanged === true) {
await admin
.firestore()
.collection('rooms')
.doc(roomId)
.collection('messages')
.add({
uid: '<system>',
name: '',
text: `${userName} changed show to \n${player.showName}`,
time: new Date().toISOString(),
});
}
if (roomData.status !== player.status) {
await admin
.firestore()
.collection('rooms')
.doc(roomId)
.update({
player,
})
.catch((err) => res.status(500).send(err));
await admin
.firestore()
.collection('rooms')
.doc(roomId)
.collection('messages')
.add({
uid: '<system>',
name: '',
text: `${userName} ${statusString} ${timeString}`,
time: new Date().toISOString(),
});
return res.status(200).send({ message: 'Synced party player' });
} else {
return res.status(208).send({ message: 'Player already up to date' });
}
} else {
return res.status(401).send('Not in room to sync');
}
};
const app = express();
app.use(cors({ origin: true }));
app.use(authenticator);
admin.initializeApp({
credential: admin.credential.cert(secret),
databaseURL: 'https://watch-party-crx.firebaseio.com',
});
app.post('/create', createRoom);
app.post('/join', joinRoom);
app.post('/message', sendMessage);
app.delete('/leave/:rid/users/:uid', leaveRoom);
app.delete('/delete/:rid', deleteRoom);
app.post('/updatePlayer', updatePlayer);
exports.widgets = functions.https.onRequest(app);