Merge branch 'master' into likes

This commit is contained in:
asankaran35
2019-12-04 17:41:28 -05:00
committed by GitHub
20 changed files with 1370 additions and 493 deletions

View File

@@ -1,76 +1,141 @@
/* eslint-disable prefer-arrow-callback */
/* eslint-disable promise/always-return */
const admin = require('firebase-admin');
const { db } = require('../util/admin');
const admin = require("firebase-admin");
const { db } = require("../util/admin");
exports.putPost = (req, res) => {
const newPost = {
body: req.body.body,
userHandle: req.user.handle,
userImage: req.body.userImage,
userID: req.user.uid,
microBlogTitle: req.body.microBlogTitle,
createdAt: new Date().toISOString(),
likeCount: 0,
commentCount: 0,
microBlogTopics: req.body.microBlogTopics,
quoteBody: null
};
const newPost = {
body: req.body.body,
userHandle: req.user.handle,
userImage: req.body.userImage,
userID: req.user.uid,
microBlogTitle: req.body.microBlogTitle,
createdAt: new Date().toISOString(),
likeCount: 0,
commentCount: 0,
microBlogTopics: req.body.microBlogTopics,
quoteBody: null
};
admin.firestore().collection('posts').add(newPost)
.then((doc) => {
doc.update({postId: doc.id})
const resPost = newPost;
resPost.postId = doc.id;
return res.status(200).json(resPost);
admin
.firestore()
.collection("posts")
.add(newPost)
.then(doc => {
doc.update({ postId: doc.id });
const resPost = newPost;
resPost.postId = doc.id;
return res.status(200).json(resPost);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: 'something went wrong'});
.catch(err => {
console.error(err);
return res.status(500).json({ error: "something went wrong" });
});
};
exports.getallPostsforUser = (req, res) => {
var post_query = admin.firestore().collection("posts").where("userHandle", "==", req.user.handle);
var post_query = admin
.firestore()
.collection("posts")
.where("userHandle", "==", req.user.handle);
post_query.get()
post_query
.get()
.then(function(myPosts) {
let posts = [];
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
return res.status(200).json(posts);
let posts = [];
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
return res.status(200).json(posts);
})
.then(function() {
return res.status(200).json("Successfully retrieved all user's posts from database.");
return res
.status(200)
.json("Successfully retrieved all user's posts from database.");
})
.catch(function(err) {
return res.status(500).json("Failed to retrieve user's posts from database.", err);
return res
.status(500)
.json("Failed to retrieve user's posts from database.", err);
});
};
exports.getallPosts = (req, res) => {
var post_query = admin.firestore().collection("posts");
post_query.get()
.then(function(allPosts) {
let posts = [];
allPosts.forEach(function(doc) {
posts.push(doc.data());
let posts = [];
let users = {};
// Get all the posts
var postsPromise = new Promise((resolve, reject) => {
db.collection("posts").get()
.then((allPosts) => {
allPosts.forEach((post) => {
posts.push(post.data());
});
return res.status(200).json(posts);
resolve();
})
.catch((error) => {
reject(error);
})
});
// Get all users
var usersPromise = new Promise((resolve, reject) => {
db.collection("users").get()
.then((allUsers) => {
allUsers.forEach((user) => {
users[user.data().handle] = user.data();
})
resolve();
})
.catch((error) => {
reject(error);
})
});
// Wait for the two promises
Promise.all([postsPromise, usersPromise])
.then(() => {
let newPosts = []
// Add the image url of the person who made the post to all of the post objects
posts.forEach((post) => {
post.profileImage = users[post.userHandle].imageUrl ? users[post.userHandle].imageUrl : null;
newPosts.push(post);
});
return res.status(200).json(newPosts);
})
.catch((error) => {
return res.status(500).json({error});
})
};
exports.getOtherUsersPosts = (req, res) => {
var post_query = admin
.firestore()
.collection("posts")
.where("userHandle", "==", req.body.handle);
post_query
.get()
.then(function(myPosts) {
let posts = [];
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
return res.status(200).json(posts);
})
.then(function() {
return res.status(200).json("Successfully retrieved every post from database.");
return res
.status(200)
.json("Successfully retrieved all user's posts from database.");
})
.catch(function(err) {
return res.status(500).json("Failed to retrieve posts from database.", err);
return res
.status(500)
.json("Failed to retrieve user's posts from database.", err);
});
};
exports.quoteWithPost = (req, res) => {
let quoteData;
const quoteDoc = admin.firestore().collection('quote').
where('userHandle', '==', req.user.handle).
@@ -89,46 +154,50 @@ exports.quoteWithPost = (req, res) => {
return res.status(404).json({error: 'Post not found'});
}
})
.then((data) => {
if(data.empty) {
return admin.firestore().collection('quote').add({
quoteId : req.params.postId,
userHandle : req.user.handle,
quoteBody : req.body.quoteBody
})
.then(() => {
const post = {
body: quoteData.body,
userHandle : req.user.handle,
quoteBody: req.body.quoteBody,
createdAt : new Date().toISOString(),
userImage: req.body.userImage,
likeCount: 0,
commentCount: 0,
userID: req.user.uid,
microBlogTitle: quoteData.microBlogTitle,
microBlogTopics: quoteData.microBlogTopics,
quoteId: req.params.postId
}
return admin.firestore().collection('posts').add(post)
.then((doc) => {
doc.update({postId: doc.id})
.then(data => {
if (data.empty) {
return admin
.firestore()
.collection("quote")
.add({
quoteId: req.params.postId,
userHandle: req.user.handle,
quoteBody: req.body.quoteBody
})
.then(() => {
const post = {
body: quoteData.body,
userHandle: req.user.handle,
quoteBody: req.body.quoteBody,
createdAt: new Date().toISOString(),
userImage: req.body.userImage,
likeCount: 0,
commentCount: 0,
userID: req.user.uid,
microBlogTitle: quoteData.microBlogTitle,
microBlogTopics: quoteData.microBlogTopics,
quoteId: req.params.postId
};
return admin
.firestore()
.collection("posts")
.add(post)
.then(doc => {
doc.update({ postId: doc.id });
const resPost = post;
resPost.postId = doc.id;
return res.status(200).json(resPost);
})
})
}
else {
return res.status(400).json({ error: 'Post has already been quoted.' });
}
})
.catch((err) => {
return res.status(500).json({error: err});
});
});
} else {
return res.status(400).json({ error: "Post has already been quoted." });
}
})
}
.catch(err => {
return res.status(500).json({ error: err });
});
};
exports.quoteWithoutPost = (req, res) => {
let quoteData;
@@ -149,70 +218,77 @@ exports.quoteWithoutPost = (req, res) => {
return res.status(404).json({error: 'Post not found'});
}
})
.then((data) => {
if(data.empty) {
return admin.firestore().collection('quote').add({
quoteId : req.params.postId,
userHandle : req.user.handle,
quoteBody: null
})
.then(() => {
const post = {
userHandle : req.user.handle,
body: quoteData.body,
quoteBody: null,
createdAt : new Date().toISOString(),
likeCount: 0,
commentCount: 0,
userID: req.user.uid,
userImage: req.body.userImage,
microBlogTitle: quoteData.microBlogTitle,
microBlogTopics: quoteData.microBlogTopics,
quoteId: req.params.postId
}
return admin.firestore().collection('posts').add(post)
.then((doc) => {
doc.update({postId: doc.id})
.then(data => {
if (data.empty) {
return admin
.firestore()
.collection("quote")
.add({
quoteId: req.params.postId,
userHandle: req.user.handle,
quoteBody: null
})
.then(() => {
const post = {
userHandle: req.user.handle,
body: quoteData.body,
quoteBody: null,
createdAt: new Date().toISOString(),
likeCount: 0,
commentCount: 0,
userID: req.user.uid,
userImage: req.body.userImage,
microBlogTitle: quoteData.microBlogTitle,
microBlogTopics: quoteData.microBlogTopics,
quoteId: req.params.postId
};
return admin
.firestore()
.collection("posts")
.add(post)
.then(doc => {
doc.update({ postId: doc.id });
const resPost = post;
resPost.postId = doc.id;
return res.status(200).json(resPost);
})
})
}
else {
return res.status(400).json({ error: 'Post has already been quoted.' });
});
});
} else {
return res.status(400).json({ error: "Post has already been quoted." });
}
})
.catch((err) => {
return res.status(500).json({error: 'Something is wrong'});
})
}
.catch(err => {
// return res.status(500).json({ error: "Something is wrong" });
return res.status(500).json({ error: err });
});
};
exports.checkforLikePost = (req, res) => {
const likedPostDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
.where('postId', '==', req.params.postId).limit(1);
let result;
const likedPostDoc = admin
.firestore()
.collection("likes")
.where("userHandle", "==", req.user.handle)
.where("postId", "==", req.params.postId)
.limit(1);
let result;
likedPostDoc.get()
.then((data) => {
if (data.empty) {
result = false;
return res.status(200).json(result);
}
else
{
result = true;
return res.status(200).json(result);
}
})
}
likedPostDoc.get().then(data => {
if (data.empty) {
result = false;
return res.status(200).json(result);
} else {
result = true;
return res.status(200).json(result);
}
})
.catch((err) => {
console.log(err);
return res.status(500).json({error: err});
})
};
exports.likePost = (req, res) => {
const postId = req.params.postId;
let likedPostDoc;
db.doc(`/users/${req.userData.handle}`)
@@ -369,6 +445,7 @@ exports.unlikePost = (req, res) => {
}
exports.getLikes = (req, res) => {
db.doc(`/users/${req.userData.handle}`)
.get()
@@ -386,5 +463,11 @@ exports.getLikes = (req, res) => {
}
exports.getFilteredPosts = (req, res) => {
admin.firestore().collection('posts').where('userHandle', '==', 'new user').where('microBlogTopics', '==')
};
admin
.firestore()
.collection("posts")
.where("userHandle", "==", "new user")
.where("microBlogTopics", "==");
};

View File

@@ -1,4 +1,6 @@
/* eslint-disable promise/catch-or-return */
/* eslint-disable promise/always-return */
const { admin, db } = require("../util/admin");
const config = require("../util/config");
const { validateUpdateProfileInfo } = require("../util/validator");
@@ -209,7 +211,7 @@ exports.deleteUser = (req, res) => {
let errors = {};
function thenFunction(data) {
console.log(`${data} data for ${req.userData.handle} has been deleted.`);
console.log(`${data} for ${req.userData.handle} has been deleted.`);
}
function catchFunction(data, err) {
@@ -217,14 +219,131 @@ exports.deleteUser = (req, res) => {
errors[data] = err;
}
function deleteDirectMessages() {
return new Promise((resolve, reject) => {
const deleteUsername = req.userData.handle;
db.doc(`/users/${deleteUsername}`)
.get()
.then((deleteUserDocSnap) => {
const dms = deleteUserDocSnap.data().dms;
const dmRecipients = deleteUserDocSnap.data().dmRecipients;
if (!dms) {
resolve();
return;
}
// Iterate over the list of users who this person has DM'd
let otherUsersPromises = [];
// Resolve if they don't have a dmRecipients list
if (dmRecipients === undefined || dmRecipients === null || dmRecipients.length === 0) {
resolve();
return;
}
dmRecipients.forEach((dmRecipient) => {
otherUsersPromises.push(
// Get each users data
db.doc(`/users/${dmRecipient}`).get()
.then((otherUserDocSnap) => {
// Get the index of deleteUsername so that we can remove the dangling
// reference to the DM document
let otherUserDMRecipients = otherUserDocSnap.data().dmRecipients;
let otherUserDMs = otherUserDocSnap.data().dms;
let index = -1;
otherUserDMRecipients.forEach((dmRecip, i) => {
if (dmRecip === deleteUsername) {
index = i;
}
})
if (index !== -1) {
// Remove deleteUsername from their dmRecipients list
otherUserDMRecipients.splice(index, 1);
// Remove the DM channel with deleteUsername
otherUserDMs.splice(index, 1);
// Update the users data
return otherUserDocSnap.ref.update({
dmRecipients: otherUserDMRecipients,
dms: otherUserDMs
});
}
})
)
})
// Wait for the removal of DM data stored on other users to be deleted
Promise.all(otherUsersPromises)
.then(() => {
// Iterate through DM references and delete them from the dm collection
let dmRefsPromises = [];
dms.forEach((dmRef) => {
// Create a delete queue
let batch = db.batch();
dmRefsPromises.push(
// Add the messages to the delete queue
db.collection(`/dm/${dmRef.id}/messages`).listDocuments()
.then((docs) => {
console.log("second")
console.log(docs);
docs.map((doc) => {
batch.delete(doc);
})
// Add the doc that the DM is stored in to the delete queue
batch.delete(dmRef);
// Commit the writes
return batch.commit();
})
)
})
return Promise.all(dmRefsPromises);
})
.then(() => {
resolve();
return;
})
.catch((err) => {
console.log("error " + err);
reject(err);
return;
})
})
.catch((err) => {
console.log(err);
return res.status(500).json({error: err});
})
})
}
// Deletes user from authentication
let auth = admin.auth().deleteUser(userId);
// Deletes database data
let data = db
.collection("users")
.doc(`${req.user.handle}`)
.delete();
let data = new Promise((resolve, reject) => {
deleteDirectMessages()
.then(() => {
return db
.collection("users")
.doc(`${req.user.handle}`)
.delete()
})
.then(() => {
resolve();
return;
})
.catch((err) => {
console.log(err);
reject(err);
return;
})
})
// Deletes any custom profile image
let image;
@@ -298,7 +417,7 @@ exports.updateProfileInfo = (req, res) => {
// Update the database entry for this user
db.collection("users")
.doc(req.user.handle)
.set(profileData, { merge: true })
.set(profileData)
.then(() => {
console.log(`${req.user.handle}'s profile info has been updated.`);
return res.status(201).json({
@@ -331,6 +450,25 @@ exports.getUserDetails = (req, res) => {
});
};
exports.getAllHandles = (req, res) => {
var user_query = admin.firestore().collection("users");
user_query.get()
.then((allUsers) => {
let users = [];
allUsers.forEach((user) => {
users.push(user.data().handle);
});
return res.status(200).json(users);
})
.catch((err) => {
return res.status(500).json({
message:"Failed to retrieve posts from database.",
error: err
});
});
};
// Returns all data stored for a user
exports.getAuthenticatedUser = (req, res) => {
let credentials = {};
db.doc(`/users/${req.user.handle}`)
@@ -466,6 +604,126 @@ exports.getSubs = (req, res) => {
});
};
// Uploads a profile image
exports.uploadProfileImage = (req, res) => {
const BusBoy = require("busboy");
const path = require("path");
const os = require("os");
const fs = require("fs");
const busboy = new BusBoy({ headers: req.headers });
let imageFileName;
let imageToBeUploaded = {};
let oldImageFileName = req.userData.imageUrl ? req.userData.imageUrl.split("/o/")[1].split("?alt")[0] : null;
// console.log(`old file: ${oldImageFileName}`);
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') {
return res.status(400).json({ error: "Wrong filetype submitted" });
}
// console.log(fieldname);
// console.log(filename);
// console.log(mimetype);
const imageExtension = filename.split(".")[filename.split(".").length - 1]; // Get the image file extension
imageFileName = `${Math.round(Math.random() * 100000000000)}.${imageExtension}`; // Get a random filename
const filepath = path.join(os.tmpdir(), imageFileName);
imageToBeUploaded = { filepath, mimetype };
file.pipe(fs.createWriteStream(filepath));
});
busboy.on("finish", () => {
// Save the file to the storage bucket
admin.storage().bucket(config.storageBucket).upload(imageToBeUploaded.filepath, {
resumable: false,
metadata: {
metadata: {
contentType: imageToBeUploaded.mimetype
}
}
})
.then(() => {
// Add the new URL to the user's profile
const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`;
return db.doc(`/users/${req.user.handle}`).update({ imageUrl });
})
.then(() => {
// Delete their old image if they have one
if (oldImageFileName !== null && oldImageFileName !== "no-img.png") {
admin.storage().bucket(config.storageBucket).file(oldImageFileName).delete()
.then(() => {
return res.status(201).json({ message: "Image uploaded successfully1"});
})
.catch((err) => {
console.log(err);
return res.status(201).json({ message: "Image uploaded successfully2"});
})
// return res.status(201).json({ message: "Image uploaded successfully"});
} else {
return res.status(201).json({ message: "Image uploaded successfully3"});
}
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code})
})
});
busboy.end(req.rawBody);
// const BusBoy = require('busboy');
// const path = require('path');
// const os = require('os');
// const fs = require('fs');
// const busboy = new BusBoy({ headers: req.headers });
// let imageToBeUploaded = {};
// let imageFileName;
// busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
// // console.log(fieldname, file, filename, encoding, mimetype);
// if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') {
// return res.status(400).json({ error: 'Wrong file type submitted' });
// }
// // my.image.png => ['my', 'image', 'png']
// const imageExtension = filename.split('.')[filename.split('.').length - 1];
// // 32756238461724837.png
// imageFileName = `${Math.round(
// Math.random() * 1000000000000
// ).toString()}.${imageExtension}`;
// const filepath = path.join(os.tmpdir(), imageFileName);
// imageToBeUploaded = { filepath, mimetype };
// file.pipe(fs.createWriteStream(filepath));
// });
// busboy.on('finish', () => {
// admin
// .storage()
// .bucket(config.storageBucket)
// .upload(imageToBeUploaded.filepath, {
// resumable: false,
// metadata: {
// metadata: {
// contentType: imageToBeUploaded.mimetype
// }
// }
// })
// .then(() => {
// const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${
// config.storageBucket
// }/o/${imageFileName}?alt=media`;
// return db.doc(`/users/${req.user.handle}`).update({ imageUrl });
// })
// .then(() => {
// return res.json({ message: 'image uploaded successfully' });
// })
// .catch((err) => {
// console.error(err);
// return res.status(500).json({ error: 'something went wrong' });
// });
// });
// busboy.end(req.rawBody);
}
exports.removeSub = (req, res) => {
let new_following = [];
let userRef = db.doc(`/users/${req.userData.handle}`);
@@ -489,6 +747,7 @@ exports.removeSub = (req, res) => {
.catch(err => {
return res.status(500).json({ err });
});
return res.status(200).json({ message: "ok" });
});
};

View File

@@ -11,12 +11,14 @@ app.use(cors());
*------------------------------------------------------------------*/
const {
getAuthenticatedUser,
getAllHandles,
getUserDetails,
getProfileInfo,
login,
signup,
deleteUser,
updateProfileInfo,
uploadProfileImage,
verifyUser,
unverifyUser,
getUserHandles,
@@ -39,14 +41,23 @@ app.delete("/delete", fbAuth, deleteUser);
app.post("/getUserDetails", fbAuth, getUserDetails);
// Returns a list of all usernames
// Used for searching
app.get("/getAllHandles", fbAuth, getAllHandles);
// Returns all profile data of the currently logged in user
app.get("/getProfileInfo", fbAuth, getProfileInfo);
// Updates the currently logged in user's profile information
app.post("/updateProfileInfo", fbAuth, updateProfileInfo);
// Returns all user data for the logged in user.
// Used when setting the state in Redux.
app.get("/user", fbAuth, getAuthenticatedUser);
// Uploads a profile image
app.post("/user/image", fbAuth, uploadProfileImage);
// Verifies the user sent to the request
// Must be run by the Admin user
app.post("/verifyUser", fbAuth, verifyUser);
@@ -70,8 +81,10 @@ app.post("/removeSub", fbAuth, removeSub);
/*------------------------------------------------------------------*
* handlers/post.js *
*------------------------------------------------------------------*/
const { getallPostsforUser, getallPosts, putPost, likePost, unlikePost, getLikes, quoteWithPost, quoteWithoutPost, checkforLikePost} = require("./handlers/post");
app.get("/getallPostsforUser", fbAuth, getallPostsforUser);
app.get("/getallPosts", getallPosts);
@@ -87,7 +100,7 @@ app.get("/checkforLikePost/:postId", fbAuth, checkforLikePost);
app.post("/quoteWithPost/:postId", fbAuth, quoteWithPost);
app.post("/quoteWithoutPost/:postId", fbAuth, quoteWithoutPost);
app.post("/getOtherUsersPosts", fbAuth, getOtherUsersPosts);
/*------------------------------------------------------------------*
* handlers/topic.js *

View File

@@ -14,6 +14,7 @@
},
"dependencies": {
"axios": "^0.19.0",
"busboy": "^0.3.1",
"firebase": "^6.6.2",
"firebase-admin": "^8.6.0",
"firebase-functions": "^3.1.0",

View File

@@ -4,12 +4,12 @@ const { admin, db } = require('./admin');
// The function will only execute if the user is logged in, or rather, they have
// a valid token
module.exports = (req, res, next) => {
console.log(req);
console.log(req.body);
console.log(req.headers);
console.log(req.headers.authorization);
console.log(JSON.stringify(req.body));
console.log(JSON.stringify(req.header));
// console.log(req);
// console.log(req.body);
// console.log(req.headers);
// console.log(req.headers.authorization);
// console.log(JSON.stringify(req.body));
// console.log(JSON.stringify(req.header));
let idToken;