v1.6.2/cleanup

- remove api v2
- linting
This commit is contained in:
2020-08-14 10:57:38 -04:00
parent aaf2506f78
commit 56cd151a04
32 changed files with 476 additions and 1437 deletions
+18 -34
View File
@@ -1,48 +1,32 @@
const FunctionModules = require("./modules/index");
const FunctionModules2 = require("./modules2/index");
const Webhooks = require("./webhooks/index");
const express = require("express");
const cors = require("cors");
const FunctionModules = require('./modules/index');
const Webhooks = require('./webhooks/index');
const express = require('express');
const cors = require('cors');
// WEBHOOKS
const webhooks = express();
webhooks.use(cors({ origin: true }));
webhooks.all("/conferenceEnded", Webhooks.conferenceEnd);
webhooks.all("/scheduledCleanup", Webhooks.scheduledCleanUp);
webhooks.all("/ask", Webhooks.ask);
webhooks.all("/userCleanUp", Webhooks.userCleanUp);
webhooks.all('/conferenceEnded', Webhooks.conferenceEnd);
webhooks.all('/scheduledCleanup', Webhooks.scheduledCleanUp);
webhooks.all('/ask', Webhooks.ask);
webhooks.all('/userCleanUp', Webhooks.userCleanUp);
// VERSION 1
const app = express();
app.use(cors({ origin: true }));
app.use(FunctionModules.authenticator);
app.get("/validator/:partyName", FunctionModules.tokenValidator);
app.get("/refresher/:token", FunctionModules.tokenRefresher);
app.post("/create", FunctionModules.createRoom);
app.post("/join", FunctionModules.joinRoom);
app.post("/message", FunctionModules.sendMessage);
app.post("/updatePlayer", FunctionModules.updatePlayer);
app.post("/updateVoxeet", FunctionModules.updateVoxeet);
app.delete("/leave/:rid/users/:uid", FunctionModules.leaveRoom);
app.delete("/delete/:rid", FunctionModules.deleteRoom);
app.put("/updateAdminOnly/:rid/:adminOnly", FunctionModules.updateAdminOnly);
// VERSION 2
const app2 = express();
app2.use(cors({ origin: true }));
app2.use(FunctionModules2.authenticator);
app2.get("/validator", FunctionModules2.tokenValidator);
app2.get("/refresher/:token", FunctionModules2.tokenRefresher);
app2.post("/create", FunctionModules2.createRoom);
app2.post("/join", FunctionModules2.joinRoom);
app2.post("/message", FunctionModules2.sendMessage);
app2.post("/updatePlayer", FunctionModules2.updatePlayer);
app2.post("/updateVoxeet", FunctionModules2.updateVoxeet);
app2.delete("/leave/:rid/users/:uid", FunctionModules2.leaveRoom);
app2.delete("/delete/:rid", FunctionModules2.deleteRoom);
app.get('/validator/:partyName', FunctionModules.tokenValidator);
app.get('/refresher/:token', FunctionModules.tokenRefresher);
app.post('/create', FunctionModules.createRoom);
app.post('/join', FunctionModules.joinRoom);
app.post('/message', FunctionModules.sendMessage);
app.post('/updatePlayer', FunctionModules.updatePlayer);
app.post('/updateVoxeet', FunctionModules.updateVoxeet);
app.delete('/leave/:rid/users/:uid', FunctionModules.leaveRoom);
app.delete('/delete/:rid', FunctionModules.deleteRoom);
app.put('/updateAdminOnly/:rid/:adminOnly', FunctionModules.updateAdminOnly);
module.exports = {
v1: app,
v2: app2,
webhooks,
};
-2
View File
@@ -12,7 +12,5 @@ admin.initializeApp(FIREBASE_OPTIONS);
// VERSION 1
exports.widgets = functions.https.onRequest(REST.v1);
// VERSION 2
exports.widgets2 = functions.https.onRequest(REST.v2);
// WEBHOOKS
exports.webhooks = functions.https.onRequest(REST.webhooks);
+20 -28
View File
@@ -1,62 +1,54 @@
const admin = require("firebase-admin");
const Logger = require("../Logger");
const mLogger = new Logger("modules", "authenticator");
const admin = require('firebase-admin');
const Logger = require('../Logger');
const mLogger = new Logger('modules', 'authenticator');
module.exports = (req, res, next) => {
mLogger.start();
res.set("Access-Control-Allow-Origin", ["*"]);
if (req.method === "OPTIONS") {
mLogger.success("OPTIONS CALL", { URL: req.url });
res.set('Access-Control-Allow-Origin', ['*']);
if (req.method === 'OPTIONS') {
mLogger.success('OPTIONS CALL', { URL: req.url });
res.status(200).send();
return next();
}
if (req.headers.authorization) {
try {
const token = req.headers.authorization.split(" ")[1];
const reqToken = token.split(":")[0];
const reqUid = token.split(":")[1];
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) {
if (req.method === "POST") {
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.method === "PUT"
) {
if (req.method === 'GET' || req.method === 'DELETE' || req.method === 'PUT') {
req.body = JSON.stringify({ uid: user.uid });
}
mLogger.success("AUTHORIZED", { URL: req.url, UID: reqUid });
mLogger.success('AUTHORIZED', { URL: req.url, UID: reqUid });
return next();
} else {
mLogger.success("NOT AUTHORIZED", { URL: req.url });
return res.status(401).send({ message: "Unauthorized" });
mLogger.success('NOT AUTHORIZED', { URL: req.url });
return res.status(401).send({ message: 'Unauthorized' });
}
})
.catch((err) => {
mLogger.error("AUTH VALIDATE FIREBASE ERROR", {
mLogger.error('AUTH VALIDATE FIREBASE ERROR', {
URL: req.url,
Error: err,
});
return res
.status(500)
.send({ message: "Unable to verify user token" });
return res.status(500).send({ message: 'Unable to verify user token' });
});
} catch (err) {
mLogger.error("AUTH VALIDATE ERROR", { URL: req.url, Error: err });
return res
.status(401)
.send({ message: "Something went wrong when authorizing" });
mLogger.error('AUTH VALIDATE ERROR', { URL: req.url, Error: err });
return res.status(401).send({ message: 'Something went wrong when authorizing' });
}
} else {
mLogger.error("NO AUTH TOKEN", { URL: req.url });
res.status(401).send({ message: "Got no user token" });
mLogger.error('NO AUTH TOKEN', { URL: req.url });
res.status(401).send({ message: 'Got no user token' });
}
return 0;
};
+31 -45
View File
@@ -1,27 +1,21 @@
const admin = require("firebase-admin");
const admin = require('firebase-admin');
module.exports = async (req, res) => {
const bodydata = JSON.parse(req.body);
console.log("Requested Create - UID - ", bodydata.uid);
if (!bodydata.userName)
res.status(400).send({ message: "Missing user name" });
if (!bodydata.partyName)
res.status(400).send({ message: "Missing party name" });
if (!bodydata.partyPin)
res.status(400).send({ message: "Missing party pin" });
console.log('Requested Create - UID - ', bodydata.uid);
if (!bodydata.userName) res.status(400).send({ message: 'Missing user name' });
if (!bodydata.partyName) res.status(400).send({ message: 'Missing party name' });
if (!bodydata.partyPin) res.status(400).send({ message: 'Missing party pin' });
const roomNameTaken = await admin
.firestore()
.collection("rooms")
.doc(bodydata.partyName.replace("/", "\\"))
.collection('rooms')
.doc(bodydata.partyName.replace('/', '\\'))
.get()
.then((docSnap) => docSnap.exists);
if (roomNameTaken)
return res
.status(409)
.send({ message: "That party name is already taken" });
if (roomNameTaken) return res.status(409).send({ message: 'That party name is already taken' });
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(bodydata.partyName)
.set({
name: bodydata.partyName,
@@ -32,17 +26,17 @@ module.exports = async (req, res) => {
adminOnly: bodydata.adminOnly,
})
.catch((err) => {
res.status(500).send({ message: "Unable to start party." });
res.status(500).send({ message: 'Unable to start party.' });
console.error(err);
});
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(bodydata.partyName)
.collection("messages")
.collection('messages')
.add({
uid: "<system>",
name: "",
uid: '<system>',
name: '',
text: `${bodydata.userName} started the party.`,
time: new Date(),
})
@@ -54,9 +48,9 @@ module.exports = async (req, res) => {
});
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(bodydata.partyName)
.collection("users")
.collection('users')
.doc(bodydata.uid)
.set({
admin: true,
@@ -68,47 +62,39 @@ module.exports = async (req, res) => {
err
);
});
if (bodydata.player && bodydata.player.source === "amazon.") {
if (bodydata.player && bodydata.player.source === 'amazon.') {
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(bodydata.partyName)
.collection("messages")
.collection('messages')
.add({
uid: "<system>",
name: "Update to V1.6.1",
endpoint: "https://get.chromewatchparty.com",
type: "interactive/link",
uid: '<system>',
name: 'Update to V1.6.1',
endpoint: 'https://get.chromewatchparty.com',
type: 'interactive/link',
text: `If Watch Party doesn't work make sure you're on V1.6.1. Try removing and re-adding if an update option is not visible`,
time: new Date(),
})
.catch((err) => {
console.error(
`Failed to add amazon error message : \n\t Room: ${bodydata.partyName}`,
err
);
console.error(`Failed to add amazon error message : \n\t Room: ${bodydata.partyName}`, err);
});
}
if (bodydata.player && bodydata.player.source === "hulu.") {
if (bodydata.player && bodydata.player.source === 'hulu.') {
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(bodydata.partyName)
.collection("messages")
.collection('messages')
.add({
uid: "<system>",
name: "",
uid: '<system>',
name: '',
text: `Watch Party may not work temporarily. An update is coming to fix this.`,
time: new Date(),
})
.catch((err) => {
console.error(
`Failed to add amazon error message : \n\t Room: ${bodydata.partyName}`,
err
);
console.error(`Failed to add amazon error message : \n\t Room: ${bodydata.partyName}`, err);
});
}
res
.status(201)
.send({ roomId: bodydata.partyName, message: "Started a party!" });
res.status(201).send({ roomId: bodydata.partyName, message: 'Started a party!' });
};
+26 -37
View File
@@ -1,24 +1,19 @@
const admin = require("firebase-admin");
const admin = require('firebase-admin');
module.exports = async (req, res) => {
const bodydata = JSON.parse(req.body);
console.log(
"Requested Join - UID - ",
bodydata.uid,
"\n\tRoom - ",
bodydata.partyName
);
console.log('Requested Join - UID - ', bodydata.uid, '\n\tRoom - ', bodydata.partyName);
// GET ROOM EXISTS, ROOM SOURCE, & ROOM PIN
const [exists, roomSource, roomPin, adminUid] = await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(bodydata.partyName)
.get()
.then((roomSnap) => [
roomSnap.exists,
roomSnap.exists ? roomSnap.data().player.source : "",
roomSnap.exists ? roomSnap.data().pin : "",
roomSnap.exists ? roomSnap.data().adminUid : "",
roomSnap.exists ? roomSnap.data().player.source : '',
roomSnap.exists ? roomSnap.data().pin : '',
roomSnap.exists ? roomSnap.data().adminUid : '',
])
.catch((err) => {
console.error(
@@ -27,13 +22,13 @@ module.exports = async (req, res) => {
);
});
if (exists && roomPin !== bodydata.partyPin)
return res.status(401).send({ message: "Incorrect party pin" });
return res.status(401).send({ message: 'Incorrect party pin' });
if (adminUid === bodydata.uid) {
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(bodydata.partyName)
.collection("users")
.collection('users')
.doc(bodydata.uid)
.set({
admin: true,
@@ -43,15 +38,15 @@ module.exports = async (req, res) => {
// GET IF USER EXISTS AND IS ADMIN
const [userExists, userAdmin, userName] = await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(bodydata.partyName)
.collection("users")
.collection('users')
.doc(bodydata.uid)
.get()
.then((userSnap) => [
userSnap.exists,
userSnap.exists ? userSnap.data().admin : false,
userSnap.exists ? userSnap.data().name : "",
userSnap.exists ? userSnap.data().name : '',
])
.catch((err) => {
console.error(
@@ -65,15 +60,13 @@ module.exports = async (req, res) => {
if (userName !== bodydata.userName) {
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(bodydata.partyName)
.collection("users")
.collection('users')
.doc(bodydata.uid)
.update({ name: bodydata.userName });
}
res
.status(200)
.send({ partyName: bodydata.partyName, message: "Joined a party" });
res.status(200).send({ partyName: bodydata.partyName, message: 'Joined a party' });
}
// USER DOES NOT PRE-EXIST BUT SAME SOURCE AND RIGHT PIN
else if (
@@ -86,12 +79,12 @@ module.exports = async (req, res) => {
) {
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(bodydata.partyName)
.collection("messages")
.collection('messages')
.add({
uid: "<system>",
name: "",
uid: '<system>',
name: '',
text: `${bodydata.userName} joined the party.`,
time: new Date(),
})
@@ -103,9 +96,9 @@ module.exports = async (req, res) => {
});
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(bodydata.partyName)
.collection("users")
.collection('users')
.doc(bodydata.uid)
.set({
admin: false,
@@ -117,9 +110,7 @@ module.exports = async (req, res) => {
err
);
});
res
.status(200)
.send({ partyName: bodydata.partyName, message: "Joined a party" });
res.status(200).send({ partyName: bodydata.partyName, message: 'Joined a party' });
}
// ONLY WRONG SOURCE
else if (exists && roomSource !== bodydata.source) {
@@ -127,13 +118,13 @@ module.exports = async (req, res) => {
if (userAdmin === true) {
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(bodydata.partyName)
.update({
player: {
showName: null,
source: bodydata.source,
status: "NOT_PLAYING",
status: 'NOT_PLAYING',
time: 0,
updatedBy: bodydata.uid,
},
@@ -142,11 +133,9 @@ module.exports = async (req, res) => {
console.error(
`Failed to update player source when admin joining party \n\t Room: ${partyName} \n\t User: ${bodydata.uid}`
);
res
.status(500)
.send({ message: "Unable to move party, please try again" });
res.status(500).send({ message: 'Unable to move party, please try again' });
});
res.status(200).send({ message: `Moved party to ${roomSource}` });
} else res.status(417).send({ message: `This party is on ${roomSource}` });
} else res.status(404).send({ message: "Party Not Found" });
} else res.status(404).send({ message: 'Party Not Found' });
};
+10 -15
View File
@@ -1,39 +1,34 @@
const admin = require("firebase-admin");
const admin = require('firebase-admin');
module.exports = async (req, res) => {
const { name, text, uid, roomId, type, replyTo } = JSON.parse(req.body);
const roomExists = await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(roomId)
.get()
.then((roomSnap) => roomSnap.exists);
if (roomExists) {
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(roomId)
.collection("messages")
.collection('messages')
.add({
name,
text: text || "",
text: text || '',
time: new Date(),
uid,
type: type || "",
type: type || '',
replyTo: replyTo || null,
})
.catch((err) => {
console.error(
`Failed to send message to party : \n\t Room: ${roomId} \n\t ${uid}`,
err
);
res
.status(500)
.send({ message: "Couldn't send your message", error: messageErr });
console.error(`Failed to send message to party : \n\t Room: ${roomId} \n\t ${uid}`, err);
res.status(500).send({ message: "Couldn't send your message", error: messageErr });
});
res.status(200).send({ message: "Sent a message" });
res.status(200).send({ message: 'Sent a message' });
} else {
res.status(404).send({ message: "Looks like this party is over" });
res.status(404).send({ message: 'Looks like this party is over' });
}
};
+15 -18
View File
@@ -17,29 +17,26 @@ module.exports = async (req, res) => {
body: JSON.stringify({
grant_type: 'client_credentials',
}),
}).then((oauthResponse) => oauthResponse.json())
.catch((err) => res.status(500).send({err, message: 'Unable to generate token for call'}));
})
.then((oauthResponse) => oauthResponse.json())
.catch((err) => res.status(500).send({ err, message: 'Unable to generate token for call' }));
const [exists, conferencePending, conference, adminOnly, adminUid] = await admin
.firestore()
.collection('rooms')
.doc(req.params.partyName)
.get()
.then(snap => {
const data = snap.exists ? snap.data() : {};
return [snap.exists, data.conferencePending, data.conference, data.adminOnly, data.adminUid];
});
.firestore()
.collection('rooms')
.doc(req.params.partyName)
.get()
.then((snap) => {
const data = snap.exists ? snap.data() : {};
return [snap.exists, data.conferencePending, data.conference, data.adminOnly, data.adminUid];
});
if (exists === true) {
if (conference === undefined || conference === null) {
if (conferencePending === undefined || conferencePending === null) {
if (!adminOnly || (adminOnly && (adminUid === bodyData.uid)) ) {
await admin
.firestore()
.collection('rooms')
.doc(req.params.partyName)
.update({
conferencePending: bodyData.uid
if (!adminOnly || (adminOnly && adminUid === bodyData.uid)) {
await admin.firestore().collection('rooms').doc(req.params.partyName).update({
conferencePending: bodyData.uid,
});
await admin
.firestore()
@@ -51,7 +48,7 @@ module.exports = async (req, res) => {
name: '',
text: 'A call session is being created (will be available soon).',
time: new Date(),
});
});
}
}
}
+11 -6
View File
@@ -16,8 +16,8 @@ module.exports = async (req, res) => {
return false;
})
.catch((err) => {
console.err('Failed to get party to update adminOnly', err);
return res.status(404).send({ message: 'Failed to get party.' });
console.err('Failed to get party to update adminOnly', err);
return res.status(404).send({ message: 'Failed to get party.' });
});
if (!isAdmin) {
console.log('[UNAUTHORIZED] Requested Admin Mode Update - Room - ', req.params.rid);
@@ -25,12 +25,17 @@ module.exports = async (req, res) => {
return;
}
const adminOnly = req.params.adminOnly === 'true';
await admin.firestore().collection('rooms').doc(req.params.rid).update({
adminOnly
}).catch((err) => {
await admin
.firestore()
.collection('rooms')
.doc(req.params.rid)
.update({
adminOnly,
})
.catch((err) => {
console.err('Failed to update adminOnly for party', err);
res.status(409).send({ message: 'Failed to update party.' });
});
});
res.status(200).send({ message: 'Updated admin only mode for party' });
return;
};
+18 -29
View File
@@ -1,23 +1,16 @@
const admin = require("firebase-admin");
const admin = require('firebase-admin');
module.exports = async (req, res) => {
const { conference, partyName, partyPin, userName, uid } = JSON.parse(
req.body
);
const { conference, partyName, partyPin, userName, uid } = JSON.parse(req.body);
// GET ROOM PIN
const [exists, roomPin, conferencePending, partyConference] = await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(partyName)
.get()
.then((roomSnap) => {
const data = roomSnap.exists ? roomSnap.data() : {};
return [
roomSnap.exists,
data.pin,
data.conferencePending,
data.conference,
];
return [roomSnap.exists, data.pin, data.conferencePending, data.conference];
});
// CHECK IF ROOM EXISTS
if (exists === true) {
@@ -29,61 +22,57 @@ module.exports = async (req, res) => {
// UPDATE CONFERENCE DETAILS
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(partyName)
.update({ conference })
.catch((err) =>
res.status(500).send({
message: "Unable to update the call details",
message: 'Unable to update the call details',
error: err,
})
);
// REMOVE PENDING STATUS
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(partyName)
.update({
conferencePending: admin.firestore.FieldValue.delete(),
})
.catch((err) =>
console.error("Failed to remove pending status", err)
);
.catch((err) => console.error('Failed to remove pending status', err));
// ADD SYSTEM MESSAGE
await admin
.firestore()
.collection("rooms")
.collection('rooms')
.doc(partyName)
.collection("messages")
.collection('messages')
.add({
uid: "<system>",
name: "",
uid: '<system>',
name: '',
text: `${userName} started the call, everyone can join now.`,
time: new Date(),
})
.catch((err) =>
console.error("Failed to add update conference message", err)
);
res.status(200).send({ message: "Started the conference" });
.catch((err) => console.error('Failed to add update conference message', err));
res.status(200).send({ message: 'Started the conference' });
} else {
res.status(409).send({
message: "Looks like someone is already starting a call",
message: 'Looks like someone is already starting a call',
});
}
} else if (partyConference) {
res.status(409).send({
message: "Call already exists",
message: 'Call already exists',
conference: partyConference,
});
}
} else {
// WRONG ROOM PIN
res.status(401).send({ message: "Wrong party pin, try rejoining" });
res.status(401).send({ message: 'Wrong party pin, try rejoining' });
}
}
} else {
// ROOM DOESN'T EXIST
res.status(404).send({ message: "Party Not Found" });
res.status(404).send({ message: 'Party Not Found' });
}
return;
};
-42
View File
@@ -1,42 +0,0 @@
const admin = require('firebase-admin');
module.exports = (req, res, next) => {
res.set('Access-Control-Allow-Origin', ['*']);
if (req.method === 'OPTIONS') {
res.status(200).send();
return next();
}
if (req.headers.authorization) {
try {
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.info('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({ message: 'Unauthorized' });
}
})
.catch((err) => {
console.error('Failed Auth - ', req.headers.authorization, '\n', err);
return res.status(500).send({ message: 'Unable to verify user token' });
});
} catch (err) {
console.log(err);
return res.status(401).send({ message: 'Something went wrong when authorizing' });
}
} else return res.status(401).send({ message: 'Got no user token' });
};
-32
View File
@@ -1,32 +0,0 @@
const admin = require('firebase-admin');
module.exports = async (roomId) => {
admin
.firestore()
.collection('rooms')
.doc(roomId)
.collection('messages')
.listDocuments()
.then((messages) => messages.forEach((message) => message.delete()))
.catch((err) => {
console.error(`Failed to run auto clean up (delete room messages) @ ${roomId}`, err);
});
admin
.firestore()
.collection('rooms')
.doc(roomId)
.collection('users')
.listDocuments()
.then((users) => users.forEach((user) => user.delete()))
.catch((err) => {
console.error(`Failed to run auto clean up (delete room users) @ ${roomId}`, err);
});
admin
.firestore()
.collection('rooms')
.doc(roomId)
.delete()
.catch((err) => {
console.error(`Failed to run auto clean up (delete room) @ ${roomId}`, err);
});
};
-87
View File
@@ -1,87 +0,0 @@
const admin = require("firebase-admin");
module.exports = async (req, res) => {
const bodydata = JSON.parse(req.body);
console.log("Requested Create - UID - ", bodydata.uid);
if (!bodydata.userName)
res.status(400).send({ message: "Missing user name" });
if (!bodydata.partyName)
res.status(400).send({ message: "Missing party name" });
if (!bodydata.partyPin)
res.status(400).send({ message: "Missing party pin" });
const roomNameTaken = await admin
.firestore()
.collection("rooms")
.doc(bodydata.partyName.replace("/", "\\"))
.get()
.then((docSnap) => docSnap.exists);
if (roomNameTaken)
return res
.status(409)
.send({ message: "That party name is already taken" });
await admin
.firestore()
.collection("rooms")
.doc(bodydata.partyName)
.set({
name: bodydata.partyName,
pin: bodydata.partyPin,
player: bodydata.player,
createdAt: new Date(),
updatedAt: new Date(),
adminUid: bodydata.uid,
})
.catch((err) => {
res.status(500).send({ message: "Unable to start party." });
console.error(err);
});
await admin
.firestore()
.collection("rooms")
.doc(bodydata.partyName)
.collection("messages")
.add({
uid: "<system>",
name: "",
text: `${bodydata.userName} started the party.`,
time: new Date(),
})
.catch((err) => {
console.error(
`Failed to add system create party message : \n\t Room: ${bodydata.partyName}`,
err
);
});
await admin
.firestore()
.collection("rooms")
.doc(bodydata.partyName)
.collection("users")
.doc(bodydata.uid)
.set({
admin: true,
name: bodydata.userName,
})
.catch((err) => {
console.error(
`Failed to set admin when creating party : \n\t Room: ${bodydata.partyName} \n\t User: ${bodydata.uid}`,
err
);
});
admin
.firestore()
.collection("rooms")
.doc(bodydata.partyName)
.collection("messages")
.add({
uid: "<system>",
name: "",
text: `Big update coming on Monday (Aug. 10). Watch Party will be unavailable during the afternoon as we upgrade our services. See what's new at whatsnew.chromewatchparty.com`,
time: new Date(),
});
res
.status(201)
.send({ roomId: bodydata.partyName, message: "Started a party!" });
};
-62
View File
@@ -1,62 +0,0 @@
const admin = require('firebase-admin');
module.exports = 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) => {
console.error(
`Failed to delete room messages : \n\t Room: ${req.params.rid} \n\t User: ${req.params.uid}`,
err
);
});
await admin
.firestore()
.collection('rooms')
.doc(req.params.rid)
.collection('users')
.listDocuments()
.then((users) => users.forEach((user) => user.delete()))
.catch((err) => {
console.error(
`Failed to delete room users : \n\t Room: ${req.params.rid} \n\t User: ${req.params.uid}`,
err
);
});
await admin
.firestore()
.collection('rooms')
.doc(req.params.rid)
.delete()
.catch((err) => {
console.error(
`Failed to delete room : \n\t Room: ${req.params.rid} \n\t User: ${req.params.uid}`,
err
);
});
res.status(200).send({ message: 'Ended the party' });
};
-29
View File
@@ -1,29 +0,0 @@
const authenticator = require('./authenticator');
const cleanUpRoom = require('./cleanUpRoom');
const scheduledCleanUp = require('./scheduledCleanUp');
const createRoom = require('./createRoom');
const joinRoom = require('./joinRoom');
const sendMessage = require('./sendMessage');
const leaveRoom = require('./leaveRoom');
const deleteRoom = require('./deleteRoom');
const timeDiff = require('./timeDiff');
const updatePlayer = require('./updatePlayer');
const tokenValidator = require('./tokenValidator');
const tokenRefresher = require('./tokenRefresher');
const updateVoxeet = require('./updateVoxeet');
module.exports = {
authenticator,
createRoom,
joinRoom,
sendMessage,
updatePlayer,
leaveRoom,
deleteRoom,
scheduledCleanUp,
cleanUpRoom,
timeDiff,
tokenValidator,
tokenRefresher,
updateVoxeet,
};
-154
View File
@@ -1,154 +0,0 @@
const admin = require('firebase-admin');
module.exports = async (req, res) => {
const bodydata = JSON.parse(req.body);
console.log('Requested Join - UID - ', bodydata.uid, '\n\tRoom - ', bodydata.partyName);
// GET ROOM EXISTS, ROOM SOURCE, & ROOM PIN
const [exists, roomSource, roomPin, adminUid] = await admin
.firestore()
.collection('rooms')
.doc(bodydata.partyName)
.get()
.then((roomSnap) => [
roomSnap.exists,
roomSnap.exists ? roomSnap.data().player.source : '',
roomSnap.exists ? roomSnap.data().pin : '',
roomSnap.exists ? roomSnap.data().adminUid : '',
])
.catch((err) => {
console.error(
`Failed to get room when joining room : \n\t Room: ${bodydata.partyName} \n\t User: ${bodydata.uid}`,
err
);
});
if (exists && roomPin !== bodydata.partyPin)
return res.status(401).send({ message: 'Incorrect party pin' });
if (adminUid === bodydata.uid) {
await admin
.firestore()
.collection('rooms')
.doc(bodydata.partyName)
.collection('users')
.doc(bodydata.uid)
.set({
admin: true,
name: bodydata.userName,
});
}
// GET IF USER EXISTS AND IS ADMIN
const [userExists, userAdmin, userName] = await admin
.firestore()
.collection('rooms')
.doc(bodydata.partyName)
.collection('users')
.doc(bodydata.uid)
.get()
.then((userSnap) => [
userSnap.exists,
userSnap.exists ? userSnap.data().admin : false,
userSnap.exists ? userSnap.data().name : '',
])
.catch((err) => {
console.error(
`Failed to get user when joining room : \n\t Room: ${bodydata.partyName} \n\t User: ${bodydata.uid}`,
err
);
});
// IF USER PRE-EXISTS AND SAME SOURCE - JOIN
if (userExists && exists && roomSource === bodydata.source) {
// UPDATE NAME IF NEEDED
if (userName !== bodydata.userName) {
await admin
.firestore()
.collection('rooms')
.doc(bodydata.partyName)
.collection('users')
.doc(bodydata.uid)
.update({ name: bodydata.userName });
}
res.status(200).send({ partyName: bodydata.partyName, message: 'Joined a party' });
}
// USER DOES NOT PRE-EXIST BUT SAME SOURCE AND RIGHT PIN
else if (
!userExists &&
exists &&
bodydata.partyName &&
bodydata.userName &&
roomSource === bodydata.source &&
roomPin === bodydata.partyPin
) {
await admin
.firestore()
.collection('rooms')
.doc(bodydata.partyName)
.collection('messages')
.add({
uid: '<system>',
name: '',
text: `${bodydata.userName} joined the party.`,
time: new Date(),
})
.catch((err) => {
console.error(
`Failed to add system join party message : \n\t Room: ${partyName} \n\t ${bodydata.uid}`,
err
);
});
await admin
.firestore()
.collection('rooms')
.doc(bodydata.partyName)
.collection('users')
.doc(bodydata.uid)
.set({
admin: false,
name: bodydata.userName,
})
.catch((err) => {
console.error(
`Failed to set admin when joining party : \n\t Room: ${partyName} \n\t User: ${bodydata.uid}`,
err
);
});
await admin
.firestore()
.collection('rooms')
.doc(bodydata.partyName)
.update({
updatedAt: new Date(),
})
.catch((err) => {
console.error(
`Failed to set updated time when joining party : \n\t Room: ${partyName} \n\t User: ${bodydata.uid}`,
err
);
});
res.status(200).send({ partyName: bodydata.partyName, message: 'Joined a party' });
}
// ONLY WRONG SOURCE
else if (exists && roomSource !== bodydata.source) {
// MOVE SOURCE IF ADMIN
if (userAdmin === true) {
await admin
.firestore()
.collection('rooms')
.doc(bodydata.partyName)
.update({
player: {
showName: null,
source: bodydata.source,
status: 'NOT_PLAYING',
time: 0,
updatedBy: bodydata.uid,
},
})
.catch(() => {
console.error(
`Failed to update player source when admin joining party \n\t Room: ${partyName} \n\t User: ${bodydata.uid}`
);
res.status(500).send({ message: 'Unable to move party, please try again' });
});
res.status(200).send({ message: `Moved party to ${roomSource}` });
} else res.status(417).send({ message: `This party is on ${roomSource}` });
} else res.status(404).send({ message: 'Party Not Found' });
};
-19
View File
@@ -1,19 +0,0 @@
const admin = require('firebase-admin');
module.exports = 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) =>
console.error(
`Failed to remove user from party : \n\t Room: ${req.params.rid} \n\t User: ${req.params.uid}`,
err
)
);
res.status(200).send({ message: 'Left the party' });
};
-48
View File
@@ -1,48 +0,0 @@
const admin = require('firebase-admin');
const cleanUpRoom = require('./cleanUpRoom');
const timeDiff = (ds1, ds2) => {
const d1 = new Date(ds1);
const d2 = new Date(ds2);
var diff = (d2.getTime() - d1.getTime()) / 1000;
diff /= 60 * 60;
return Math.abs(Math.round(diff));
};
module.exports = async () => {
const startedTime = new Date();
const roomList = await admin
.firestore()
.collection('rooms')
.listDocuments()
.then((rL) => rL)
.catch((err) => {
console.error(
`Failed to run auto clean up (get room list) @ ${new Date().toLocaleTimeString()}`,
err
);
});
roomList.forEach((roomRef) => {
roomRef
.get()
.then(async (roomSnap) => {
if (
// MORE THAN 24 HOURS AND NOT IN USE
(timeDiff(roomSnap.createTime.toDate(), startedTime) >= 24 &&
timeDiff(roomSnap.updateTime.toDate(), startedTime) >= 12) ||
// LESS THAN 24 HOURS BUT NOT IN USE
timeDiff(roomSnap.updateTime.toDate(), startedTime) >= 12
) {
await cleanUpRoom(roomSnap.id);
console.info(`Deleted room ${roomSnap.id} from auto cleanup`);
}
return;
})
.catch((err) => {
console.error(
`Failed to run auto clean up (get room snap) @ ${new Date().toLocaleTimeString()}`,
err
);
});
});
};
-46
View File
@@ -1,46 +0,0 @@
const admin = require('firebase-admin');
module.exports = async (req, res) => {
const { name, text, uid, roomId, type } = JSON.parse(req.body);
const roomExists = await admin
.firestore()
.collection('rooms')
.doc(roomId)
.get()
.then((roomSnap) => roomSnap.exists);
if (roomExists) {
await admin
.firestore()
.collection('rooms')
.doc(roomId)
.collection('messages')
.add({
name,
text: text || '',
time: new Date(),
uid,
type: type || '',
})
.catch((err) => {
console.error(`Failed to send message to party : \n\t Room: ${roomId} \n\t ${uid}`, err);
res.status(500).send({ message: "Couldn't send your message", error: messageErr });
});
await admin
.firestore()
.collection('rooms')
.doc(roomId)
.update({
updatedAt: new Date(),
})
.catch((err) => {
console.error(
`Failed to set updated time when sending messasge to party : \n\t Room: ${roomId} \n\t User: ${uid}`,
err
);
});
res.status(200).send({ message: 'Sent a message' });
} else {
res.status(404).send({ message: 'Looks like this party is over' });
}
};
-7
View File
@@ -1,7 +0,0 @@
module.exports = function (ds1, ds2) {
const d1 = new Date(ds1);
const d2 = new Date(ds2);
var diff = (d2.getTime() - d1.getTime()) / 1000;
diff /= 60 * 60;
return Math.abs(Math.round(diff));
};
-20
View File
@@ -1,20 +0,0 @@
const VoxeetSecret = require('../VoxeetSecret.json');
module.exports = async (req, res) => {
const { key, secret } = VoxeetSecret;
const credentials = btoa(encodeURI(key) + ':' + encodeURI(secret));
const headers = {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
Authorization: 'Basic ' + credentials,
};
const oauth = await fetch(VoxeetSecret.refreshURL, {
method: 'POST',
headers,
body: JSON.stringify({
refresh_token: req.params.token,
}),
})
.then((oauthResponse) => oauthResponse.json())
.catch((err) => res.status(500).send(err));
if (oauth) res.status(200).send(oauth);
};
-21
View File
@@ -1,21 +0,0 @@
const VoxeetSecret = require('../VoxeetSecret.json');
const fetch = require('node-fetch');
module.exports = async (req, res) => {
const { key, secret } = VoxeetSecret;
const credentials = Buffer.from(encodeURI(key) + ':' + encodeURI(secret)).toString('base64');
const headers = {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
Authorization: 'Basic ' + credentials,
};
const oauth = await fetch(VoxeetSecret.validateURL, {
method: 'POST',
headers,
body: JSON.stringify({
grant_type: 'client_credentials',
}),
})
.then((oauthResponse) => oauthResponse.json())
.catch((err) => res.status(500).send(err));
if (oauth) res.status(200).send(oauth);
};
-85
View File
@@ -1,85 +0,0 @@
const admin = require('firebase-admin');
module.exports = 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);
if (!roomId) return res.status(204).send({ message: 'Party name not sent.' });
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 && player.showName) {
if (player.showName !== roomData.player.showName) {
await admin
.firestore()
.collection('rooms')
.doc(roomId)
.collection('messages')
.add({
uid: '<system>',
name: '',
text: `${userName} changed \n${player.showName ? 'to ' + player.showName : ''}`,
time: new Date(),
});
}
}
if (roomData.status !== player.status) {
await admin
.firestore()
.collection('rooms')
.doc(roomId)
.update({
player,
})
.catch((err) => {
console.error(`Failed to update player : \n\t Room: ${roomId} \n\t ${uid}`, err);
res.status(500).send({ message: "Uh oh party could't be synced", err });
});
// await admin
// .firestore()
// .collection('rooms')
// .doc(roomId)
// .collection('messages')
// .add({
// uid: '<system>',
// name: '',
// text: `${userName} ${statusString} ${timeString}`,
// time: new Date(),
// })
// .catch((err) => {
// console.error(
// `Failed to add system update player message : \n\t Room: ${roomId} \n\t ${uid}`,
// err
// );
// });
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({ message: 'Not in room to sync' });
}
};
-47
View File
@@ -1,47 +0,0 @@
const admin = require('firebase-admin');
module.exports = async (req, res) => {
const { conference, partyName, partyPin, userName } = JSON.parse(req.body);
// GET ROOM PIN
const roomPin = await admin
.firestore()
.collection('rooms')
.doc(partyName)
.get()
.then((roomSnap) => (roomSnap.exists ? roomSnap.data().pin : null));
// CHECK IF ROOM EXISTS
if (roomPin) {
// CHECK FOR CORRECT PIN
if (roomPin === partyPin) {
// UPDATE CONFERENCE DETAILS
await admin
.firestore()
.collection('rooms')
.doc(partyName)
.update({ conference })
.catch((err) =>
res.status(500).send({ message: 'Unable to update the call details', error: err })
);
// ADD SYSTEM MESSAGE
await admin
.firestore()
.collection('rooms')
.doc(partyName)
.collection('messages')
.add({
uid: '<system>',
name: '',
text: `${userName} started the call.`,
time: new Date(),
})
.catch((err) => console.error('Failed to add update conference message', err));
res.status(200).send({ message: 'Started the conference' });
} else {
// WRONG ROOM PIN
return res.status(401).send({ message: 'Wrong party pin, try rejoining' });
}
} else {
// ROOM DOESN'T EXIST
return res.status(404).send({ message: 'Party Not Found' });
}
};
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "watch-party-api",
"version": "1.6.1",
"version": "1.6.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {