mirror of
https://github.com/ClaytonWWilson/CS307-Team24.git
synced 2025-12-16 02:08:47 +00:00
Merge pull request #109 from ClaytonWWilson/finalfix
fixed user and topic relationship. allow add topic directly
This commit is contained in:
commit
c7859e0f0a
@ -66,46 +66,77 @@ exports.getallPosts = (req, res) => {
|
|||||||
|
|
||||||
// Get all the posts
|
// Get all the posts
|
||||||
var postsPromise = new Promise((resolve, reject) => {
|
var postsPromise = new Promise((resolve, reject) => {
|
||||||
db.collection("posts").get()
|
db.collection("posts")
|
||||||
.then((allPosts) => {
|
.get()
|
||||||
allPosts.forEach((post) => {
|
.then(allPosts => {
|
||||||
|
allPosts.forEach(post => {
|
||||||
posts.push(post.data());
|
posts.push(post.data());
|
||||||
});
|
});
|
||||||
resolve();
|
resolve();
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch(error => {
|
||||||
reject(error);
|
reject(error);
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Get all users
|
// Get all users
|
||||||
var usersPromise = new Promise((resolve, reject) => {
|
var usersPromise = new Promise((resolve, reject) => {
|
||||||
db.collection("users").get()
|
db.collection("users")
|
||||||
.then((allUsers) => {
|
.get()
|
||||||
allUsers.forEach((user) => {
|
.then(allUsers => {
|
||||||
|
allUsers.forEach(user => {
|
||||||
users[user.data().handle] = user.data();
|
users[user.data().handle] = user.data();
|
||||||
})
|
});
|
||||||
resolve();
|
resolve();
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch(error => {
|
||||||
reject(error);
|
reject(error);
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Wait for the two promises
|
// Wait for the two promises
|
||||||
Promise.all([postsPromise, usersPromise])
|
Promise.all([postsPromise, usersPromise])
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let newPosts = []
|
let newPosts = [];
|
||||||
// Add the image url of the person who made the post to all of the post objects
|
// Add the image url of the person who made the post to all of the post objects
|
||||||
posts.forEach((post) => {
|
posts.forEach(post => {
|
||||||
post.profileImage = users[post.userHandle].imageUrl ? users[post.userHandle].imageUrl : null;
|
post.profileImage = users[post.userHandle].imageUrl
|
||||||
|
? users[post.userHandle].imageUrl
|
||||||
|
: null;
|
||||||
newPosts.push(post);
|
newPosts.push(post);
|
||||||
});
|
});
|
||||||
return res.status(200).json(newPosts);
|
return res.status(200).json(newPosts);
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch(error => {
|
||||||
return res.status(500).json({error});
|
return res.status(500).json({ error });
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.getAlert = (req, res) => {
|
||||||
|
var post_query = admin
|
||||||
|
.firestore()
|
||||||
|
.collection("posts")
|
||||||
|
.where("microBlogTitle", "==", "Alert");
|
||||||
|
|
||||||
|
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 all user's posts from database.");
|
||||||
|
})
|
||||||
|
.catch(function(err) {
|
||||||
|
return res
|
||||||
|
.status(500)
|
||||||
|
.json("Failed to retrieve user's posts from database.", err);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
exports.getOtherUsersPosts = (req, res) => {
|
exports.getOtherUsersPosts = (req, res) => {
|
||||||
@ -137,21 +168,23 @@ exports.getOtherUsersPosts = (req, res) => {
|
|||||||
|
|
||||||
exports.quoteWithPost = (req, res) => {
|
exports.quoteWithPost = (req, res) => {
|
||||||
let quoteData;
|
let quoteData;
|
||||||
const quoteDoc = admin.firestore().collection('quote').
|
const quoteDoc = admin
|
||||||
where('userHandle', '==', req.user.handle).
|
.firestore()
|
||||||
where('quoteId', '==', req.params.postId).limit(1);
|
.collection("quote")
|
||||||
|
.where("userHandle", "==", req.user.handle)
|
||||||
|
.where("quoteId", "==", req.params.postId)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
const postDoc = db.doc(`/posts/${req.params.postId}`);
|
const postDoc = db.doc(`/posts/${req.params.postId}`);
|
||||||
|
|
||||||
postDoc.get()
|
postDoc
|
||||||
.then((doc) => {
|
.get()
|
||||||
if(doc.exists) {
|
.then(doc => {
|
||||||
|
if (doc.exists) {
|
||||||
quoteData = doc.data();
|
quoteData = doc.data();
|
||||||
return quoteDoc.get();
|
return quoteDoc.get();
|
||||||
}
|
} else {
|
||||||
else
|
return res.status(404).json({ error: "Post not found" });
|
||||||
{
|
|
||||||
return res.status(404).json({error: 'Post not found'});
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.then(data => {
|
.then(data => {
|
||||||
@ -201,21 +234,23 @@ exports.quoteWithPost = (req, res) => {
|
|||||||
|
|
||||||
exports.quoteWithoutPost = (req, res) => {
|
exports.quoteWithoutPost = (req, res) => {
|
||||||
let quoteData;
|
let quoteData;
|
||||||
const quoteDoc = admin.firestore().collection('quote').
|
const quoteDoc = admin
|
||||||
where('userHandle', '==', req.user.handle).
|
.firestore()
|
||||||
where('quoteId', '==', req.params.postId).limit(1);
|
.collection("quote")
|
||||||
|
.where("userHandle", "==", req.user.handle)
|
||||||
|
.where("quoteId", "==", req.params.postId)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
const postDoc = db.doc(`/posts/${req.params.postId}`);
|
const postDoc = db.doc(`/posts/${req.params.postId}`);
|
||||||
|
|
||||||
postDoc.get()
|
postDoc
|
||||||
.then((doc) => {
|
.get()
|
||||||
if(doc.exists) {
|
.then(doc => {
|
||||||
|
if (doc.exists) {
|
||||||
quoteData = doc.data();
|
quoteData = doc.data();
|
||||||
return quoteDoc.get();
|
return quoteDoc.get();
|
||||||
}
|
} else {
|
||||||
else
|
return res.status(404).json({ error: "Post not found" });
|
||||||
{
|
|
||||||
return res.status(404).json({error: 'Post not found'});
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.then(data => {
|
.then(data => {
|
||||||
@ -272,7 +307,9 @@ exports.checkforLikePost = (req, res) => {
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
let result;
|
let result;
|
||||||
|
|
||||||
likedPostDoc.get().then(data => {
|
likedPostDoc
|
||||||
|
.get()
|
||||||
|
.then(data => {
|
||||||
if (data.empty) {
|
if (data.empty) {
|
||||||
result = false;
|
result = false;
|
||||||
return res.status(200).json(result);
|
return res.status(200).json(result);
|
||||||
@ -281,49 +318,49 @@ exports.checkforLikePost = (req, res) => {
|
|||||||
return res.status(200).json(result);
|
return res.status(200).json(result);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
return res.status(500).json({error: err});
|
return res.status(500).json({ error: err });
|
||||||
})
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
exports.likePost = (req, res) => {
|
exports.likePost = (req, res) => {
|
||||||
|
|
||||||
const postId = req.params.postId;
|
const postId = req.params.postId;
|
||||||
let likedPostDoc;
|
let likedPostDoc;
|
||||||
db.doc(`/users/${req.userData.handle}`)
|
db.doc(`/users/${req.userData.handle}`)
|
||||||
.get()
|
.get()
|
||||||
.then((userDoc) => {
|
.then(userDoc => {
|
||||||
let likes = userDoc.data().likes;
|
let likes = userDoc.data().likes;
|
||||||
if (likes === undefined || likes === null) {
|
if (likes === undefined || likes === null) {
|
||||||
likes = [];
|
likes = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (likes.includes(postId)) {
|
if (likes.includes(postId)) {
|
||||||
return res.status(400).json({error: "This user has already liked this post"});
|
return res
|
||||||
|
.status(400)
|
||||||
|
.json({ error: "This user has already liked this post" });
|
||||||
}
|
}
|
||||||
|
|
||||||
likes.push(postId);
|
likes.push(postId);
|
||||||
|
|
||||||
return userDoc.ref.update({likes})
|
return userDoc.ref.update({ likes });
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
return db.doc(`/posts/${postId}`).get()
|
return db.doc(`/posts/${postId}`).get();
|
||||||
|
|
||||||
})
|
})
|
||||||
.then((postDoc) => {
|
.then(postDoc => {
|
||||||
let postData = postDoc.data();
|
let postData = postDoc.data();
|
||||||
postData.likeCount++;
|
postData.likeCount++;
|
||||||
likedPostDoc = postData;
|
likedPostDoc = postData;
|
||||||
return postDoc.ref.update({likeCount : postData.likeCount})
|
return postDoc.ref.update({ likeCount: postData.likeCount });
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
return res.status(201).json(likedPostDoc);
|
return res.status(201).json(likedPostDoc);
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
return res.status(500).json({error: err});
|
return res.status(500).json({ error: err });
|
||||||
})
|
});
|
||||||
|
|
||||||
// let postData;
|
// let postData;
|
||||||
// const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
|
// const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
|
||||||
@ -361,24 +398,23 @@ exports.likePost = (req, res) => {
|
|||||||
// .catch((err) => {
|
// .catch((err) => {
|
||||||
// return res.status(500).json({error: 'Something is wrong'});
|
// return res.status(500).json({error: 'Something is wrong'});
|
||||||
// })
|
// })
|
||||||
|
};
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
exports.unlikePost = (req, res) => {
|
exports.unlikePost = (req, res) => {
|
||||||
|
|
||||||
const postId = req.params.postId;
|
const postId = req.params.postId;
|
||||||
let likedPostDoc;
|
let likedPostDoc;
|
||||||
db.doc(`/users/${req.userData.handle}`)
|
db.doc(`/users/${req.userData.handle}`)
|
||||||
.get()
|
.get()
|
||||||
.then((userDoc) => {
|
.then(userDoc => {
|
||||||
let likes = userDoc.data().likes;
|
let likes = userDoc.data().likes;
|
||||||
if (likes === undefined || likes === null) {
|
if (likes === undefined || likes === null) {
|
||||||
likes = [];
|
likes = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!likes.includes(postId)) {
|
if (!likes.includes(postId)) {
|
||||||
return res.status(400).json({error: "This user hasn't liked this post yet"});
|
return res
|
||||||
|
.status(400)
|
||||||
|
.json({ error: "This user hasn't liked this post yet" });
|
||||||
}
|
}
|
||||||
|
|
||||||
let i;
|
let i;
|
||||||
@ -388,25 +424,24 @@ exports.unlikePost = (req, res) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return userDoc.ref.update({likes})
|
return userDoc.ref.update({ likes });
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
return db.doc(`/posts/${postId}`).get()
|
return db.doc(`/posts/${postId}`).get();
|
||||||
|
|
||||||
})
|
})
|
||||||
.then((postDoc) => {
|
.then(postDoc => {
|
||||||
let postData = postDoc.data();
|
let postData = postDoc.data();
|
||||||
postData.likeCount--;
|
postData.likeCount--;
|
||||||
likedPostDoc = postData;
|
likedPostDoc = postData;
|
||||||
return postDoc.ref.update({likeCount : postData.likeCount})
|
return postDoc.ref.update({ likeCount: postData.likeCount });
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
return res.status(201).json(likedPostDoc);
|
return res.status(201).json(likedPostDoc);
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
return res.status(500).json({error: err});
|
return res.status(500).json({ error: err });
|
||||||
})
|
});
|
||||||
|
|
||||||
// let postData;
|
// let postData;
|
||||||
// const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
|
// const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
|
||||||
@ -442,32 +477,28 @@ exports.unlikePost = (req, res) => {
|
|||||||
// console.error(err);
|
// console.error(err);
|
||||||
// return res.status(500).json({error: 'Something is wrong'});
|
// return res.status(500).json({error: 'Something is wrong'});
|
||||||
// })
|
// })
|
||||||
|
};
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
exports.getLikes = (req, res) => {
|
exports.getLikes = (req, res) => {
|
||||||
db.doc(`/users/${req.userData.handle}`)
|
db.doc(`/users/${req.userData.handle}`)
|
||||||
.get()
|
.get()
|
||||||
.then((doc) => {
|
.then(doc => {
|
||||||
let likes = doc.data().likes;
|
let likes = doc.data().likes;
|
||||||
if (likes === undefined || likes === null) {
|
if (likes === undefined || likes === null) {
|
||||||
likes = [];
|
likes = [];
|
||||||
}
|
}
|
||||||
return res.status(200).json({likes});
|
return res.status(200).json({ likes });
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
return res.status(500).json({error: err});
|
return res.status(500).json({ error: err });
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
exports.getFilteredPosts = (req, res) => {
|
exports.getFilteredPosts = (req, res) => {
|
||||||
|
|
||||||
admin
|
admin
|
||||||
.firestore()
|
.firestore()
|
||||||
.collection("posts")
|
.collection("posts")
|
||||||
.where("userHandle", "==", "new user")
|
.where("userHandle", "==", "new user")
|
||||||
.where("microBlogTopics", "==");
|
.where("microBlogTopics", "==");
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -26,6 +26,41 @@ exports.putTopic = (req, res) => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
exports.putNewTopic = (req, res) => {
|
||||||
|
let new_following = [];
|
||||||
|
let userRef = db.doc(`/users/${req.userData.handle}`);
|
||||||
|
userRef
|
||||||
|
.get()
|
||||||
|
.then(doc => {
|
||||||
|
let topics = [];
|
||||||
|
new_following = doc.data().following;
|
||||||
|
// new_following.push(req.body.following);
|
||||||
|
new_following.forEach(follow => {
|
||||||
|
if (follow.handle === req.body.handle) {
|
||||||
|
// topics = follow.topics;
|
||||||
|
follow.topics.push(req.body.topic);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// return res.status(201).json({ new_following });
|
||||||
|
|
||||||
|
// add stuff
|
||||||
|
userRef
|
||||||
|
.set({ following: new_following }, { merge: true })
|
||||||
|
.then(doc => {
|
||||||
|
return res
|
||||||
|
.status(201)
|
||||||
|
.json({ message: `Following ${req.body.topic}` });
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
return res.status(500).json({ err });
|
||||||
|
});
|
||||||
|
return res.status(200).json({ message: "OK" });
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
return res.status(500).json({ err });
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
exports.getAllTopics = (req, res) => {
|
exports.getAllTopics = (req, res) => {
|
||||||
admin
|
admin
|
||||||
.firestore()
|
.firestore()
|
||||||
|
|||||||
@ -226,7 +226,7 @@ exports.deleteUser = (req, res) => {
|
|||||||
const deleteUsername = req.userData.handle;
|
const deleteUsername = req.userData.handle;
|
||||||
db.doc(`/users/${deleteUsername}`)
|
db.doc(`/users/${deleteUsername}`)
|
||||||
.get()
|
.get()
|
||||||
.then((deleteUserDocSnap) => {
|
.then(deleteUserDocSnap => {
|
||||||
const dms = deleteUserDocSnap.data().dms;
|
const dms = deleteUserDocSnap.data().dms;
|
||||||
const dmRecipients = deleteUserDocSnap.data().dmRecipients;
|
const dmRecipients = deleteUserDocSnap.data().dmRecipients;
|
||||||
|
|
||||||
@ -239,25 +239,32 @@ exports.deleteUser = (req, res) => {
|
|||||||
let otherUsersPromises = [];
|
let otherUsersPromises = [];
|
||||||
|
|
||||||
// Resolve if they don't have a dmRecipients list
|
// Resolve if they don't have a dmRecipients list
|
||||||
if (dmRecipients === undefined || dmRecipients === null || dmRecipients.length === 0) {
|
if (
|
||||||
|
dmRecipients === undefined ||
|
||||||
|
dmRecipients === null ||
|
||||||
|
dmRecipients.length === 0
|
||||||
|
) {
|
||||||
resolve();
|
resolve();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
dmRecipients.forEach((dmRecipient) => {
|
dmRecipients.forEach(dmRecipient => {
|
||||||
otherUsersPromises.push(
|
otherUsersPromises.push(
|
||||||
// Get each users data
|
// Get each users data
|
||||||
db.doc(`/users/${dmRecipient}`).get()
|
db
|
||||||
.then((otherUserDocSnap) => {
|
.doc(`/users/${dmRecipient}`)
|
||||||
|
.get()
|
||||||
|
.then(otherUserDocSnap => {
|
||||||
// Get the index of deleteUsername so that we can remove the dangling
|
// Get the index of deleteUsername so that we can remove the dangling
|
||||||
// reference to the DM document
|
// reference to the DM document
|
||||||
let otherUserDMRecipients = otherUserDocSnap.data().dmRecipients;
|
let otherUserDMRecipients = otherUserDocSnap.data()
|
||||||
|
.dmRecipients;
|
||||||
let otherUserDMs = otherUserDocSnap.data().dms;
|
let otherUserDMs = otherUserDocSnap.data().dms;
|
||||||
let index = -1;
|
let index = -1;
|
||||||
otherUserDMRecipients.forEach((dmRecip, i) => {
|
otherUserDMRecipients.forEach((dmRecip, i) => {
|
||||||
if (dmRecip === deleteUsername) {
|
if (dmRecip === deleteUsername) {
|
||||||
index = i;
|
index = i;
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
if (index !== -1) {
|
if (index !== -1) {
|
||||||
// Remove deleteUsername from their dmRecipients list
|
// Remove deleteUsername from their dmRecipients list
|
||||||
@ -272,28 +279,29 @@ exports.deleteUser = (req, res) => {
|
|||||||
dms: otherUserDMs
|
dms: otherUserDMs
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
})
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
// Wait for the removal of DM data stored on other users to be deleted
|
// Wait for the removal of DM data stored on other users to be deleted
|
||||||
Promise.all(otherUsersPromises)
|
Promise.all(otherUsersPromises)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
// Iterate through DM references and delete them from the dm collection
|
// Iterate through DM references and delete them from the dm collection
|
||||||
let dmRefsPromises = [];
|
let dmRefsPromises = [];
|
||||||
dms.forEach((dmRef) => {
|
dms.forEach(dmRef => {
|
||||||
// Create a delete queue
|
// Create a delete queue
|
||||||
let batch = db.batch();
|
let batch = db.batch();
|
||||||
dmRefsPromises.push(
|
dmRefsPromises.push(
|
||||||
// Add the messages to the delete queue
|
// Add the messages to the delete queue
|
||||||
db.collection(`/dm/${dmRef.id}/messages`).listDocuments()
|
db
|
||||||
.then((docs) => {
|
.collection(`/dm/${dmRef.id}/messages`)
|
||||||
console.log("second")
|
.listDocuments()
|
||||||
|
.then(docs => {
|
||||||
|
console.log("second");
|
||||||
console.log(docs);
|
console.log(docs);
|
||||||
docs.map((doc) => {
|
docs.map(doc => {
|
||||||
batch.delete(doc);
|
batch.delete(doc);
|
||||||
})
|
});
|
||||||
|
|
||||||
// Add the doc that the DM is stored in to the delete queue
|
// Add the doc that the DM is stored in to the delete queue
|
||||||
batch.delete(dmRef);
|
batch.delete(dmRef);
|
||||||
@ -301,8 +309,8 @@ exports.deleteUser = (req, res) => {
|
|||||||
// Commit the writes
|
// Commit the writes
|
||||||
return batch.commit();
|
return batch.commit();
|
||||||
})
|
})
|
||||||
)
|
);
|
||||||
})
|
});
|
||||||
|
|
||||||
return Promise.all(dmRefsPromises);
|
return Promise.all(dmRefsPromises);
|
||||||
})
|
})
|
||||||
@ -310,18 +318,17 @@ exports.deleteUser = (req, res) => {
|
|||||||
resolve();
|
resolve();
|
||||||
return;
|
return;
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
console.log("error " + err);
|
console.log("error " + err);
|
||||||
reject(err);
|
reject(err);
|
||||||
return;
|
return;
|
||||||
|
});
|
||||||
})
|
})
|
||||||
})
|
.catch(err => {
|
||||||
.catch((err) => {
|
|
||||||
console.log(err);
|
console.log(err);
|
||||||
return res.status(500).json({error: err});
|
return res.status(500).json({ error: err });
|
||||||
})
|
});
|
||||||
|
});
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deletes user from authentication
|
// Deletes user from authentication
|
||||||
@ -334,18 +341,18 @@ exports.deleteUser = (req, res) => {
|
|||||||
return db
|
return db
|
||||||
.collection("users")
|
.collection("users")
|
||||||
.doc(`${req.user.handle}`)
|
.doc(`${req.user.handle}`)
|
||||||
.delete()
|
.delete();
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
resolve();
|
resolve();
|
||||||
return;
|
return;
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
reject(err);
|
reject(err);
|
||||||
return;
|
return;
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
|
|
||||||
// Deletes any custom profile image
|
// Deletes any custom profile image
|
||||||
let image;
|
let image;
|
||||||
@ -454,17 +461,18 @@ exports.getUserDetails = (req, res) => {
|
|||||||
|
|
||||||
exports.getAllHandles = (req, res) => {
|
exports.getAllHandles = (req, res) => {
|
||||||
var user_query = admin.firestore().collection("users");
|
var user_query = admin.firestore().collection("users");
|
||||||
user_query.get()
|
user_query
|
||||||
.then((allUsers) => {
|
.get()
|
||||||
|
.then(allUsers => {
|
||||||
let users = [];
|
let users = [];
|
||||||
allUsers.forEach((user) => {
|
allUsers.forEach(user => {
|
||||||
users.push(user.data().handle);
|
users.push(user.data().handle);
|
||||||
});
|
});
|
||||||
return res.status(200).json(users);
|
return res.status(200).json(users);
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
return res.status(500).json({
|
return res.status(500).json({
|
||||||
message:"Failed to retrieve posts from database.",
|
message: "Failed to retrieve posts from database.",
|
||||||
error: err
|
error: err
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -557,7 +565,7 @@ exports.unverifyUser = (req, res) => {
|
|||||||
|
|
||||||
// Returns all the DMs that the user is currently participating in
|
// Returns all the DMs that the user is currently participating in
|
||||||
exports.getDirectMessages = (req, res) => {
|
exports.getDirectMessages = (req, res) => {
|
||||||
/* Return value
|
/* Return value
|
||||||
* data: [DMs]
|
* data: [DMs]
|
||||||
* dm : {
|
* dm : {
|
||||||
* dmId: str
|
* dmId: str
|
||||||
@ -577,7 +585,7 @@ exports.getDirectMessages = (req, res) => {
|
|||||||
// Returns all the messages in a dm documentSnapshot
|
// Returns all the messages in a dm documentSnapshot
|
||||||
function getMessages(dm) {
|
function getMessages(dm) {
|
||||||
let promise = new Promise((resolve, reject) => {
|
let promise = new Promise((resolve, reject) => {
|
||||||
let messagesCollection = dm.collection('messages');
|
let messagesCollection = dm.collection("messages");
|
||||||
|
|
||||||
// If the messagesCollection is missing, that mean that there aren't any messages
|
// If the messagesCollection is missing, that mean that there aren't any messages
|
||||||
if (messagesCollection === null || messagesCollection === undefined) {
|
if (messagesCollection === null || messagesCollection === undefined) {
|
||||||
@ -588,90 +596,96 @@ exports.getDirectMessages = (req, res) => {
|
|||||||
let promises = [];
|
let promises = [];
|
||||||
|
|
||||||
// Get all of the messages in the DM
|
// Get all of the messages in the DM
|
||||||
messagesCollection.get()
|
messagesCollection.get().then(dmQuerySnap => {
|
||||||
.then((dmQuerySnap) => {
|
dmQuerySnap.forEach(dmQueryDocSnap => {
|
||||||
dmQuerySnap.forEach((dmQueryDocSnap) => {
|
|
||||||
promises.push(
|
promises.push(
|
||||||
dmQueryDocSnap.ref.get()
|
dmQueryDocSnap.ref.get().then(messageData => {
|
||||||
.then((messageData) => {
|
|
||||||
msgs.push(messageData.data());
|
msgs.push(messageData.data());
|
||||||
return;
|
return;
|
||||||
})
|
})
|
||||||
)
|
);
|
||||||
})
|
});
|
||||||
|
|
||||||
let waitPromise = Promise.all(promises);
|
let waitPromise = Promise.all(promises);
|
||||||
waitPromise.then(() => {
|
waitPromise.then(() => {
|
||||||
// Sort the messages in reverse order by date
|
// Sort the messages in reverse order by date
|
||||||
// Newest should be at the bottom, because that's how they will be displayed on the front-end
|
// Newest should be at the bottom, because that's how they will be displayed on the front-end
|
||||||
msgs.sort((a, b) => {
|
msgs.sort((a, b) => {
|
||||||
return (b.createdAt > a.createdAt) ? -1 : ((b.createdAt < a.createdAt) ? 1 : 0);
|
return b.createdAt > a.createdAt
|
||||||
})
|
? -1
|
||||||
|
: b.createdAt < a.createdAt
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
|
});
|
||||||
resolve(msgs);
|
resolve(msgs);
|
||||||
});
|
});
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
return promise;
|
return promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const dms = req.userData.dms;
|
const dms = req.userData.dms;
|
||||||
|
|
||||||
// Return null if this user has no DMs
|
// Return null if this user has no DMs
|
||||||
if (dms === undefined || dms === null || dms.length === 0) return res.status(200).json({data: null});
|
if (dms === undefined || dms === null || dms.length === 0)
|
||||||
|
return res.status(200).json({ data: null });
|
||||||
|
|
||||||
let dmsData = [];
|
let dmsData = [];
|
||||||
let dmPromises = [];
|
let dmPromises = [];
|
||||||
|
|
||||||
dms.forEach((dm) => {
|
dms.forEach(dm => {
|
||||||
let dmData = {};
|
let dmData = {};
|
||||||
// Make a new promise for each DM document
|
// Make a new promise for each DM document
|
||||||
dmPromises.push(new Promise((resolve, reject) => {
|
dmPromises.push(
|
||||||
dm // DM document reference
|
new Promise((resolve, reject) => {
|
||||||
.get()
|
dm.get() // DM document reference
|
||||||
.then((doc) => {
|
.then(doc => {
|
||||||
let docData = doc.data();
|
let docData = doc.data();
|
||||||
|
|
||||||
// Recipient is the person you are messaging
|
// Recipient is the person you are messaging
|
||||||
docData.authors[0] === req.userData.handle ?
|
docData.authors[0] === req.userData.handle
|
||||||
dmData.recipient = docData.authors[1] :
|
? (dmData.recipient = docData.authors[1])
|
||||||
dmData.recipient = docData.authors[0]
|
: (dmData.recipient = docData.authors[0]);
|
||||||
|
|
||||||
// Save the createdAt time
|
// Save the createdAt time
|
||||||
dmData.createdAt = docData.createdAt;
|
dmData.createdAt = docData.createdAt;
|
||||||
|
|
||||||
// Get all the messages from this dm document
|
// Get all the messages from this dm document
|
||||||
getMessages(dm)
|
getMessages(dm).then(msgs => {
|
||||||
.then((msgs) => {
|
|
||||||
dmData.messages = msgs;
|
dmData.messages = msgs;
|
||||||
dmData.recentMessage = msgs.length !== 0 ? msgs[msgs.length - 1].message : null;
|
dmData.recentMessage =
|
||||||
dmData.recentMessageTimestamp = msgs.length !== 0 ? msgs[msgs.length - 1].createdAt : null;
|
msgs.length !== 0 ? msgs[msgs.length - 1].message : null;
|
||||||
|
dmData.recentMessageTimestamp =
|
||||||
|
msgs.length !== 0 ? msgs[msgs.length - 1].createdAt : null;
|
||||||
dmData.dmId = doc.id;
|
dmData.dmId = doc.id;
|
||||||
resolve(dmData);
|
resolve(dmData);
|
||||||
|
});
|
||||||
})
|
})
|
||||||
|
.catch(err => {
|
||||||
|
|
||||||
|
|
||||||
}).catch((err) => {
|
|
||||||
console.err(err);
|
console.err(err);
|
||||||
return res.status(400).json({error: {
|
return res.status(400).json({
|
||||||
message: "An error occurred when reading the DM document reference",
|
error: {
|
||||||
|
message:
|
||||||
|
"An error occurred when reading the DM document reference",
|
||||||
error: err
|
error: err
|
||||||
}});
|
}
|
||||||
})
|
});
|
||||||
}).then((dmData) => {
|
});
|
||||||
|
}).then(dmData => {
|
||||||
dmsData.push(dmData);
|
dmsData.push(dmData);
|
||||||
})
|
})
|
||||||
)
|
);
|
||||||
|
});
|
||||||
})
|
|
||||||
|
|
||||||
// Wait for all DM document promises to resolve before returning data
|
// Wait for all DM document promises to resolve before returning data
|
||||||
dmWaitPromise = Promise.all(dmPromises)
|
dmWaitPromise = Promise.all(dmPromises)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
// Sort the DMs so that the ones with the newest messages are at the top
|
// Sort the DMs so that the ones with the newest messages are at the top
|
||||||
dmsData.sort((a, b) => {
|
dmsData.sort((a, b) => {
|
||||||
if (a.recentMessageTimestamp === null && b.recentMessageTimestamp === null) {
|
if (
|
||||||
|
a.recentMessageTimestamp === null &&
|
||||||
|
b.recentMessageTimestamp === null
|
||||||
|
) {
|
||||||
if (b.createdAt < a.createdAt) {
|
if (b.createdAt < a.createdAt) {
|
||||||
return -1;
|
return -1;
|
||||||
} else if (b.createdAt > a.createdAt) {
|
} else if (b.createdAt > a.createdAt) {
|
||||||
@ -691,15 +705,17 @@ exports.getDirectMessages = (req, res) => {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return res.status(200).json({data: dmsData})
|
return res.status(200).json({ data: dmsData });
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
return res.status(500).json({error:{
|
return res.status(500).json({
|
||||||
|
error: {
|
||||||
message: "An error occurred while sorting",
|
message: "An error occurred while sorting",
|
||||||
error: err
|
error: err
|
||||||
}});
|
}
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
|
};
|
||||||
|
|
||||||
// Toggles direct messages on or off depending on the requese
|
// Toggles direct messages on or off depending on the requese
|
||||||
/* Request Parameters
|
/* Request Parameters
|
||||||
@ -708,34 +724,40 @@ exports.getDirectMessages = (req, res) => {
|
|||||||
exports.toggleDirectMessages = (req, res) => {
|
exports.toggleDirectMessages = (req, res) => {
|
||||||
const enable = req.body.enable;
|
const enable = req.body.enable;
|
||||||
const user = req.userData.handle;
|
const user = req.userData.handle;
|
||||||
db.doc(`/users/${user}`).update({dmEnabled: enable})
|
db.doc(`/users/${user}`)
|
||||||
|
.update({ dmEnabled: enable })
|
||||||
.then(() => {
|
.then(() => {
|
||||||
return res.status(201).json({message: "Success"});
|
return res.status(201).json({ message: "Success" });
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
return res.status(500).json({error: err});
|
return res.status(500).json({ error: err });
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
// Returns a promise that resolves if user has DMs enabled
|
// Returns a promise that resolves if user has DMs enabled
|
||||||
// and rejects if there is an error or DMs are disabled
|
// and rejects if there is an error or DMs are disabled
|
||||||
isDirectMessageEnabled = (username) => {
|
isDirectMessageEnabled = username => {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let result = {};
|
let result = {};
|
||||||
result.code = null;
|
result.code = null;
|
||||||
result.message = null;
|
result.message = null;
|
||||||
if (username === null || username === undefined || username === "") {
|
if (username === null || username === undefined || username === "") {
|
||||||
result.code = 400;
|
result.code = 400;
|
||||||
result.message = "No user was sent in the request. The request should have a non-empty 'user' key.";
|
result.message =
|
||||||
|
"No user was sent in the request. The request should have a non-empty 'user' key.";
|
||||||
reject(result);
|
reject(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
db.doc(`/users/${username}`)
|
db.doc(`/users/${username}`)
|
||||||
.get()
|
.get()
|
||||||
.then((doc) => {
|
.then(doc => {
|
||||||
if (doc.exists) {
|
if (doc.exists) {
|
||||||
// console.log(doc.data())
|
// console.log(doc.data())
|
||||||
if (doc.data().dmEnabled === true || doc.data().dmEnabled === null || doc.data().dmEnabled === undefined) {
|
if (
|
||||||
|
doc.data().dmEnabled === true ||
|
||||||
|
doc.data().dmEnabled === null ||
|
||||||
|
doc.data().dmEnabled === undefined
|
||||||
|
) {
|
||||||
// Assume DMs are enabled if they don't have a dmEnabled key
|
// Assume DMs are enabled if they don't have a dmEnabled key
|
||||||
resolve(result);
|
resolve(result);
|
||||||
} else {
|
} else {
|
||||||
@ -750,42 +772,46 @@ isDirectMessageEnabled = (username) => {
|
|||||||
reject(result);
|
reject(result);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
console.log("HI")
|
console.log("HI");
|
||||||
console.error(err);
|
console.error(err);
|
||||||
result.code = 500;
|
result.code = 500;
|
||||||
result.message = err;
|
result.message = err;
|
||||||
reject(result);
|
reject(result);
|
||||||
})
|
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
|
};
|
||||||
|
|
||||||
// Returns a promise that resolves if the data in the DM is valid and
|
// Returns a promise that resolves if the data in the DM is valid and
|
||||||
// rejects if there are any error. Errors are returned in the promise
|
// rejects if there are any error. Errors are returned in the promise
|
||||||
verifyDirectMessageIntegrity = (dmRef) => {
|
verifyDirectMessageIntegrity = dmRef => {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
resolve("Not implemented yet");
|
resolve("Not implemented yet");
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
// Checks if there are any DM channels open with userB on userA's side
|
// Checks if there are any DM channels open with userB on userA's side
|
||||||
oneWayCheck = (userA, userB) => {
|
oneWayCheck = (userA, userB) => {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
|
|
||||||
db.doc(`/users/${userA}`)
|
db.doc(`/users/${userA}`)
|
||||||
.get()
|
.get()
|
||||||
.then((userASnapshot) => {
|
.then(userASnapshot => {
|
||||||
const dmList = userASnapshot.data().dms;
|
const dmList = userASnapshot.data().dms;
|
||||||
const dmRecipients = userASnapshot.data().dmRecipients;
|
const dmRecipients = userASnapshot.data().dmRecipients;
|
||||||
|
|
||||||
if (dmList === null || dmList === undefined || dmRecipients === null || dmRecipients === undefined) {
|
if (
|
||||||
|
dmList === null ||
|
||||||
|
dmList === undefined ||
|
||||||
|
dmRecipients === null ||
|
||||||
|
dmRecipients === undefined
|
||||||
|
) {
|
||||||
// They don't have any DMs yet
|
// They don't have any DMs yet
|
||||||
console.log("No DMs array");
|
console.log("No DMs array");
|
||||||
userASnapshot.ref.set({dms:[], dmRecipients:[]}, {merge: true})
|
userASnapshot.ref
|
||||||
|
.set({ dms: [], dmRecipients: [] }, { merge: true })
|
||||||
.then(() => {
|
.then(() => {
|
||||||
resolve();
|
resolve();
|
||||||
})
|
});
|
||||||
} else if (dmList.length === 0) {
|
} else if (dmList.length === 0) {
|
||||||
// Their DMs are empty
|
// Their DMs are empty
|
||||||
console.log("DMs array is empty");
|
console.log("DMs array is empty");
|
||||||
@ -810,17 +836,16 @@ oneWayCheck = (userA, userB) => {
|
|||||||
// )
|
// )
|
||||||
// })
|
// })
|
||||||
|
|
||||||
dmRecipients.forEach((dmRecipient) => {
|
dmRecipients.forEach(dmRecipient => {
|
||||||
if (dmRecipient === userB) {
|
if (dmRecipient === userB) {
|
||||||
console.log(`You already have a DM with ${userB}`);
|
console.log(`You already have a DM with ${userB}`);
|
||||||
reject(new Error(`You already have a DM with ${userB}`));
|
reject(new Error(`You already have a DM with ${userB}`));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
resolve();
|
resolve();
|
||||||
|
|
||||||
|
|
||||||
// Promise.all(forEachPromises)
|
// Promise.all(forEachPromises)
|
||||||
// .then((dmDocs) => {
|
// .then((dmDocs) => {
|
||||||
// // Check if any of the DMs have for userA have userA and userB as the authors.
|
// // Check if any of the DMs have for userA have userA and userB as the authors.
|
||||||
@ -866,15 +891,10 @@ oneWayCheck = (userA, userB) => {
|
|||||||
// }
|
// }
|
||||||
// })
|
// })
|
||||||
// })
|
// })
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
|
};
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Returns a promise that resolves if there is not already a DM channel
|
// Returns a promise that resolves if there is not already a DM channel
|
||||||
// between the creator and recipient usernames. It rejects if one already
|
// between the creator and recipient usernames. It rejects if one already
|
||||||
@ -885,36 +905,39 @@ checkNoDirectMessageExists = (creator, recipient) => {
|
|||||||
let recipientPromise = oneWayCheck(recipient, creator);
|
let recipientPromise = oneWayCheck(recipient, creator);
|
||||||
let temp_array = [];
|
let temp_array = [];
|
||||||
temp_array.push(creatorPromise);
|
temp_array.push(creatorPromise);
|
||||||
temp_array.push(recipientPromise)
|
temp_array.push(recipientPromise);
|
||||||
|
|
||||||
Promise.all(temp_array)
|
Promise.all(temp_array)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
resolve();
|
resolve();
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
reject(err);
|
reject(err);
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
addDirectMessageToUser = (username, recipient, dmRef) => {
|
addDirectMessageToUser = (username, recipient, dmRef) => {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
db.doc(`/users/${username}`).get()
|
db.doc(`/users/${username}`)
|
||||||
.then((docSnap) => {
|
.get()
|
||||||
|
.then(docSnap => {
|
||||||
let dmList = docSnap.data().dms;
|
let dmList = docSnap.data().dms;
|
||||||
let dmRecipients = docSnap.data().dmRecipients;
|
let dmRecipients = docSnap.data().dmRecipients;
|
||||||
dmList.push(dmRef);
|
dmList.push(dmRef);
|
||||||
dmRecipients.push(recipient);
|
dmRecipients.push(recipient);
|
||||||
return db.doc(`/users/${username}`).update({dms: dmList, dmRecipients});
|
return db
|
||||||
|
.doc(`/users/${username}`)
|
||||||
|
.update({ dms: dmList, dmRecipients });
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
resolve();
|
resolve();
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
reject(err);
|
reject(err);
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
// Sends a DM from the caller to the requested DM document
|
// Sends a DM from the caller to the requested DM document
|
||||||
/* Request Parameters
|
/* Request Parameters
|
||||||
@ -932,66 +955,75 @@ exports.sendDirectMessage = (req, res) => {
|
|||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
message,
|
message,
|
||||||
messageId: null
|
messageId: null
|
||||||
}
|
};
|
||||||
|
|
||||||
db.doc(`/users/${creator}`).get()
|
db.doc(`/users/${creator}`)
|
||||||
.then((userDoc) => {
|
.get()
|
||||||
|
.then(userDoc => {
|
||||||
let dmList = userDoc.data().dms;
|
let dmList = userDoc.data().dms;
|
||||||
|
|
||||||
// Return if the creator doesn't have any DMs.
|
// Return if the creator doesn't have any DMs.
|
||||||
// This means they have not created a DM's channel yet
|
// This means they have not created a DM's channel yet
|
||||||
if (dmList === null || dmList === undefined) return res.status(400).json({error: `There is no DM channel between ${creator} and ${recipient}. Use /api/dms/new.`})
|
if (dmList === null || dmList === undefined)
|
||||||
|
return res.status(400).json({
|
||||||
|
error: `There is no DM channel between ${creator} and ${recipient}. Use /api/dms/new.`
|
||||||
|
});
|
||||||
let dmRefPromises = [];
|
let dmRefPromises = [];
|
||||||
dmList.forEach((dmRef) => {
|
dmList.forEach(dmRef => {
|
||||||
dmRefPromises.push(
|
dmRefPromises.push(
|
||||||
new Promise((resolve, reject) => {
|
new Promise((resolve, reject) => {
|
||||||
dmRef.get()
|
dmRef
|
||||||
.then((dmDoc) => {
|
.get()
|
||||||
|
.then(dmDoc => {
|
||||||
let authors = dmDoc.data().authors;
|
let authors = dmDoc.data().authors;
|
||||||
if (
|
if (
|
||||||
(authors[0] === creator && authors[1] === recipient) ||
|
(authors[0] === creator && authors[1] === recipient) ||
|
||||||
(authors[1] === creator && authors[0] === recipient)
|
(authors[1] === creator && authors[0] === recipient)
|
||||||
) {
|
) {
|
||||||
resolve({correct: true, dmRef});
|
resolve({ correct: true, dmRef });
|
||||||
} else {
|
} else {
|
||||||
resolve({correct: false, dmRef});
|
resolve({ correct: false, dmRef });
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
reject(err);
|
reject(err);
|
||||||
|
});
|
||||||
})
|
})
|
||||||
})
|
);
|
||||||
)
|
});
|
||||||
})
|
|
||||||
|
|
||||||
return Promise.all(dmRefPromises);
|
return Promise.all(dmRefPromises);
|
||||||
})
|
})
|
||||||
.then((results) => {
|
.then(results => {
|
||||||
let correctDMRef = null;
|
let correctDMRef = null;
|
||||||
results.forEach((result) => {
|
results.forEach(result => {
|
||||||
if (result.correct) {
|
if (result.correct) {
|
||||||
correctDMRef = result.dmRef;
|
correctDMRef = result.dmRef;
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
if (correctDMRef === null) {
|
if (correctDMRef === null) {
|
||||||
console.log(`There is no DM channel between ${creator} and ${recipient}. Use /api/dms/new.`);
|
console.log(
|
||||||
return res.status(400).json({error: `There is no DM channel between ${creator} and ${recipient}. Use /api/dms/new.`});
|
`There is no DM channel between ${creator} and ${recipient}. Use /api/dms/new.`
|
||||||
|
);
|
||||||
|
return res.status(400).json({
|
||||||
|
error: `There is no DM channel between ${creator} and ${recipient}. Use /api/dms/new.`
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return db.collection(`/dm/${correctDMRef.id}/messages`).add(newMessage);
|
return db.collection(`/dm/${correctDMRef.id}/messages`).add(newMessage);
|
||||||
})
|
})
|
||||||
.then((newMsgRef) => {
|
.then(newMsgRef => {
|
||||||
return newMsgRef.update({messageId: newMsgRef.id}, {merge: true});
|
return newMsgRef.update({ messageId: newMsgRef.id }, { merge: true });
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
return res.status(200).json({message: "OK"});
|
return res.status(200).json({ message: "OK" });
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
return res.status(500).json({error: err});
|
return res.status(500).json({ error: err });
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
// Creates a DM between the caller and the user in the request
|
// Creates a DM between the caller and the user in the request
|
||||||
/* Request Parameters
|
/* Request Parameters
|
||||||
@ -1002,7 +1034,8 @@ exports.createDirectMessage = (req, res) => {
|
|||||||
const recipient = req.body.user;
|
const recipient = req.body.user;
|
||||||
|
|
||||||
// Check if they are DMing themselves
|
// Check if they are DMing themselves
|
||||||
if (creator === recipient) return res.status(400).json({error: "You can't DM yourself"});
|
if (creator === recipient)
|
||||||
|
return res.status(400).json({ error: "You can't DM yourself" });
|
||||||
|
|
||||||
// Check if this user has DMs enabled
|
// Check if this user has DMs enabled
|
||||||
let creatorEnabled = isDirectMessageEnabled(creator);
|
let creatorEnabled = isDirectMessageEnabled(creator);
|
||||||
@ -1011,56 +1044,63 @@ exports.createDirectMessage = (req, res) => {
|
|||||||
let recipientEnabled = isDirectMessageEnabled(recipient);
|
let recipientEnabled = isDirectMessageEnabled(recipient);
|
||||||
|
|
||||||
// Make sure that they don't already have a DM channel
|
// Make sure that they don't already have a DM channel
|
||||||
let noDMExists = checkNoDirectMessageExists(creator, recipient)
|
let noDMExists = checkNoDirectMessageExists(creator, recipient);
|
||||||
|
|
||||||
|
let dataValidations = [creatorEnabled, recipientEnabled, noDMExists];
|
||||||
let dataValidations = [
|
|
||||||
creatorEnabled,
|
|
||||||
recipientEnabled,
|
|
||||||
noDMExists
|
|
||||||
]
|
|
||||||
|
|
||||||
Promise.all(dataValidations)
|
Promise.all(dataValidations)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
// Create a new DM document
|
// Create a new DM document
|
||||||
return db.collection("dm").add({})
|
return db.collection("dm").add({});
|
||||||
})
|
})
|
||||||
.then((dmDocRef) => {
|
.then(dmDocRef => {
|
||||||
// Fill it with some data.
|
// Fill it with some data.
|
||||||
// Note that there isn't a messages collection by default.
|
// Note that there isn't a messages collection by default.
|
||||||
let dmData = {
|
let dmData = {
|
||||||
dmId: dmDocRef.id,
|
dmId: dmDocRef.id,
|
||||||
authors: [creator, recipient],
|
authors: [creator, recipient],
|
||||||
createdAt: new Date().toISOString()
|
createdAt: new Date().toISOString()
|
||||||
}
|
};
|
||||||
|
|
||||||
// Update DM document
|
// Update DM document
|
||||||
let dmDocPromise = dmDocRef.set(dmData);
|
let dmDocPromise = dmDocRef.set(dmData);
|
||||||
|
|
||||||
// Add the DM reference to the creator
|
// Add the DM reference to the creator
|
||||||
let updateCreatorPromise = addDirectMessageToUser(creator, recipient, dmDocRef);
|
let updateCreatorPromise = addDirectMessageToUser(
|
||||||
|
creator,
|
||||||
|
recipient,
|
||||||
|
dmDocRef
|
||||||
|
);
|
||||||
|
|
||||||
// Add the DM reference to the recipient
|
// Add the DM reference to the recipient
|
||||||
let updateRecipientPromise = addDirectMessageToUser(recipient, creator, dmDocRef);
|
let updateRecipientPromise = addDirectMessageToUser(
|
||||||
|
recipient,
|
||||||
|
creator,
|
||||||
|
dmDocRef
|
||||||
|
);
|
||||||
|
|
||||||
// Wait for all promises
|
// Wait for all promises
|
||||||
return Promise.all([dmDocPromise, updateCreatorPromise, updateRecipientPromise]);
|
return Promise.all([
|
||||||
|
dmDocPromise,
|
||||||
|
updateCreatorPromise,
|
||||||
|
updateRecipientPromise
|
||||||
|
]);
|
||||||
})
|
})
|
||||||
.then (() => {
|
.then(() => {
|
||||||
return res.status(201).json({message: "Success!"});
|
return res.status(201).json({ message: "Success!" });
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
|
|
||||||
if (err.code && err.message && err.code > 0) {
|
if (err.code && err.message && err.code > 0) {
|
||||||
// Specific error that I've created
|
// Specific error that I've created
|
||||||
return res.status(err.code).json({error: err.message});
|
return res.status(err.code).json({ error: err.message });
|
||||||
} else {
|
} else {
|
||||||
// Generic or firebase error
|
// Generic or firebase error
|
||||||
return res.status(500).json({error: err});
|
return res.status(500).json({ error: err });
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
// Checks if the requested user has DMs enable or not
|
// Checks if the requested user has DMs enable or not
|
||||||
/* Request Parameters
|
/* Request Parameters
|
||||||
@ -1069,19 +1109,19 @@ exports.createDirectMessage = (req, res) => {
|
|||||||
exports.checkDirectMessagesEnabled = (req, res) => {
|
exports.checkDirectMessagesEnabled = (req, res) => {
|
||||||
isDirectMessageEnabled(req.body.user)
|
isDirectMessageEnabled(req.body.user)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
return res.status(200).json({enabled: true});
|
return res.status(200).json({ enabled: true });
|
||||||
})
|
})
|
||||||
.catch((result) => {
|
.catch(result => {
|
||||||
console.log(result);
|
console.log(result);
|
||||||
if (result.code === 200) {
|
if (result.code === 200) {
|
||||||
// DMs are disabled
|
// DMs are disabled
|
||||||
return res.status(200).json({enabled: false});
|
return res.status(200).json({ enabled: false });
|
||||||
} else {
|
} else {
|
||||||
// Some other error occured
|
// Some other error occured
|
||||||
return res.status(result.code).json({err: result.message});
|
return res.status(result.code).json({ err: result.message });
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
exports.getUserHandles = (req, res) => {
|
exports.getUserHandles = (req, res) => {
|
||||||
db.doc(`/users/${req.body.userHandle}`)
|
db.doc(`/users/${req.body.userHandle}`)
|
||||||
@ -1105,7 +1145,9 @@ exports.addSubscription = (req, res) => {
|
|||||||
let userRef = db.doc(`/users/${req.userData.handle}`);
|
let userRef = db.doc(`/users/${req.userData.handle}`);
|
||||||
userRef.get().then(doc => {
|
userRef.get().then(doc => {
|
||||||
new_following = doc.data().following;
|
new_following = doc.data().following;
|
||||||
new_following.push(req.body.following);
|
new_following
|
||||||
|
? new_following.push(req.body.following)
|
||||||
|
: (new_following = req.body.following);
|
||||||
|
|
||||||
// add stuff
|
// add stuff
|
||||||
userRef
|
userRef
|
||||||
@ -1118,7 +1160,7 @@ exports.addSubscription = (req, res) => {
|
|||||||
.catch(err => {
|
.catch(err => {
|
||||||
return res.status(500).json({ err });
|
return res.status(500).json({ err });
|
||||||
});
|
});
|
||||||
return res.status(200).json({ message: "ok" });
|
// return res.status(200).json({ message: "ok" });
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -1146,25 +1188,32 @@ exports.uploadProfileImage = (req, res) => {
|
|||||||
|
|
||||||
let imageFileName;
|
let imageFileName;
|
||||||
let imageToBeUploaded = {};
|
let imageToBeUploaded = {};
|
||||||
let oldImageFileName = req.userData.imageUrl ? req.userData.imageUrl.split("/o/")[1].split("?alt")[0] : null;
|
let oldImageFileName = req.userData.imageUrl
|
||||||
|
? req.userData.imageUrl.split("/o/")[1].split("?alt")[0]
|
||||||
|
: null;
|
||||||
// console.log(`old file: ${oldImageFileName}`);
|
// console.log(`old file: ${oldImageFileName}`);
|
||||||
|
|
||||||
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
|
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
|
||||||
if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') {
|
if (mimetype !== "image/jpeg" && mimetype !== "image/png") {
|
||||||
return res.status(400).json({ error: "Wrong filetype submitted" });
|
return res.status(400).json({ error: "Wrong filetype submitted" });
|
||||||
}
|
}
|
||||||
// console.log(fieldname);
|
// console.log(fieldname);
|
||||||
// console.log(filename);
|
// console.log(filename);
|
||||||
// console.log(mimetype);
|
// console.log(mimetype);
|
||||||
const imageExtension = filename.split(".")[filename.split(".").length - 1]; // Get the image file extension
|
const imageExtension = filename.split(".")[filename.split(".").length - 1]; // Get the image file extension
|
||||||
imageFileName = `${Math.round(Math.random() * 100000000000)}.${imageExtension}`; // Get a random filename
|
imageFileName = `${Math.round(
|
||||||
|
Math.random() * 100000000000
|
||||||
|
)}.${imageExtension}`; // Get a random filename
|
||||||
const filepath = path.join(os.tmpdir(), imageFileName);
|
const filepath = path.join(os.tmpdir(), imageFileName);
|
||||||
imageToBeUploaded = { filepath, mimetype };
|
imageToBeUploaded = { filepath, mimetype };
|
||||||
file.pipe(fs.createWriteStream(filepath));
|
file.pipe(fs.createWriteStream(filepath));
|
||||||
});
|
});
|
||||||
busboy.on("finish", () => {
|
busboy.on("finish", () => {
|
||||||
// Save the file to the storage bucket
|
// Save the file to the storage bucket
|
||||||
admin.storage().bucket(config.storageBucket).upload(imageToBeUploaded.filepath, {
|
admin
|
||||||
|
.storage()
|
||||||
|
.bucket(config.storageBucket)
|
||||||
|
.upload(imageToBeUploaded.filepath, {
|
||||||
resumable: false,
|
resumable: false,
|
||||||
metadata: {
|
metadata: {
|
||||||
metadata: {
|
metadata: {
|
||||||
@ -1180,24 +1229,33 @@ exports.uploadProfileImage = (req, res) => {
|
|||||||
.then(() => {
|
.then(() => {
|
||||||
// Delete their old image if they have one
|
// Delete their old image if they have one
|
||||||
if (oldImageFileName !== null && oldImageFileName !== "no-img.png") {
|
if (oldImageFileName !== null && oldImageFileName !== "no-img.png") {
|
||||||
admin.storage().bucket(config.storageBucket).file(oldImageFileName).delete()
|
admin
|
||||||
|
.storage()
|
||||||
|
.bucket(config.storageBucket)
|
||||||
|
.file(oldImageFileName)
|
||||||
|
.delete()
|
||||||
.then(() => {
|
.then(() => {
|
||||||
return res.status(201).json({ message: "Image uploaded successfully1"});
|
return res
|
||||||
|
.status(201)
|
||||||
|
.json({ message: "Image uploaded successfully1" });
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
return res.status(201).json({ message: "Image uploaded successfully2"});
|
return res
|
||||||
})
|
.status(201)
|
||||||
|
.json({ message: "Image uploaded successfully2" });
|
||||||
|
});
|
||||||
// return res.status(201).json({ message: "Image uploaded successfully"});
|
// return res.status(201).json({ message: "Image uploaded successfully"});
|
||||||
} else {
|
} else {
|
||||||
return res.status(201).json({ message: "Image uploaded successfully3"});
|
return res
|
||||||
|
.status(201)
|
||||||
|
.json({ message: "Image uploaded successfully3" });
|
||||||
}
|
}
|
||||||
|
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch(err => {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
return res.status(500).json({ error: err.code})
|
return res.status(500).json({ error: err.code });
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
busboy.end(req.rawBody);
|
busboy.end(req.rawBody);
|
||||||
|
|
||||||
@ -1253,7 +1311,7 @@ exports.uploadProfileImage = (req, res) => {
|
|||||||
// });
|
// });
|
||||||
// });
|
// });
|
||||||
// busboy.end(req.rawBody);
|
// busboy.end(req.rawBody);
|
||||||
}
|
};
|
||||||
|
|
||||||
exports.removeSub = (req, res) => {
|
exports.removeSub = (req, res) => {
|
||||||
let new_following = [];
|
let new_following = [];
|
||||||
|
|||||||
@ -100,13 +100,23 @@ app.post("/addSubscription", fbAuth, addSubscription);
|
|||||||
// remove one subscription
|
// remove one subscription
|
||||||
app.post("/removeSub", fbAuth, removeSub);
|
app.post("/removeSub", fbAuth, removeSub);
|
||||||
|
|
||||||
|
|
||||||
/*------------------------------------------------------------------*
|
/*------------------------------------------------------------------*
|
||||||
* handlers/post.js *
|
* handlers/post.js *
|
||||||
*------------------------------------------------------------------*/
|
*------------------------------------------------------------------*/
|
||||||
|
|
||||||
const { getallPostsforUser, getallPosts, putPost, likePost, unlikePost, getLikes, quoteWithPost, quoteWithoutPost, checkforLikePost, getOtherUsersPosts} = require("./handlers/post");
|
const {
|
||||||
|
getallPostsforUser,
|
||||||
|
getallPosts,
|
||||||
|
putPost,
|
||||||
|
likePost,
|
||||||
|
unlikePost,
|
||||||
|
getLikes,
|
||||||
|
quoteWithPost,
|
||||||
|
quoteWithoutPost,
|
||||||
|
checkforLikePost,
|
||||||
|
getOtherUsersPosts,
|
||||||
|
getAlert
|
||||||
|
} = require("./handlers/post");
|
||||||
|
|
||||||
app.get("/getallPostsforUser", fbAuth, getallPostsforUser);
|
app.get("/getallPostsforUser", fbAuth, getallPostsforUser);
|
||||||
|
|
||||||
@ -125,6 +135,8 @@ app.post("/quoteWithoutPost/:postId", fbAuth, quoteWithoutPost);
|
|||||||
|
|
||||||
app.post("/getOtherUsersPosts", fbAuth, getOtherUsersPosts);
|
app.post("/getOtherUsersPosts", fbAuth, getOtherUsersPosts);
|
||||||
|
|
||||||
|
app.get("/getAlert", fbAuth, getAlert);
|
||||||
|
|
||||||
/*------------------------------------------------------------------*
|
/*------------------------------------------------------------------*
|
||||||
* handlers/topic.js *
|
* handlers/topic.js *
|
||||||
*------------------------------------------------------------------*/
|
*------------------------------------------------------------------*/
|
||||||
@ -132,7 +144,8 @@ const {
|
|||||||
putTopic,
|
putTopic,
|
||||||
getAllTopics,
|
getAllTopics,
|
||||||
deleteTopic,
|
deleteTopic,
|
||||||
getUserTopics
|
getUserTopics,
|
||||||
|
putNewTopic
|
||||||
} = require("./handlers/topic");
|
} = require("./handlers/topic");
|
||||||
|
|
||||||
// add topic to database
|
// add topic to database
|
||||||
@ -147,4 +160,6 @@ app.post("/deleteTopic", fbAuth, deleteTopic);
|
|||||||
// get topic for this user
|
// get topic for this user
|
||||||
app.post("/getUserTopics", fbAuth, getUserTopics);
|
app.post("/getUserTopics", fbAuth, getUserTopics);
|
||||||
|
|
||||||
|
app.post("/putNewTopic", fbAuth, putNewTopic);
|
||||||
|
|
||||||
exports.api = functions.https.onRequest(app);
|
exports.api = functions.https.onRequest(app);
|
||||||
|
|||||||
@ -180,7 +180,7 @@ class Home extends Component {
|
|||||||
<p></p>
|
<p></p>
|
||||||
)
|
)
|
||||||
) : (
|
) : (
|
||||||
<p>Loading</p>
|
<p></p>
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@ -79,6 +79,7 @@ class user extends Component {
|
|||||||
following: null,
|
following: null,
|
||||||
posts: null,
|
posts: null,
|
||||||
myTopics: null,
|
myTopics: null,
|
||||||
|
followingList: null
|
||||||
loading: false
|
loading: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -115,6 +116,24 @@ class user extends Component {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
handleAdd = newTopic => {
|
||||||
|
axios
|
||||||
|
.post("/putNewTopic", {
|
||||||
|
handle: this.state.profile,
|
||||||
|
topic: newTopic
|
||||||
|
})
|
||||||
|
.then(() => {
|
||||||
|
let temp = this.state.myTopics;
|
||||||
|
temp.push(newTopic);
|
||||||
|
this.setState({
|
||||||
|
myTopics: temp
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
console.err(err);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
this.setState({loading: true});
|
this.setState({loading: true});
|
||||||
let otherUserPromise = axios
|
let otherUserPromise = axios
|
||||||
@ -132,11 +151,19 @@ class user extends Component {
|
|||||||
let userPromise = axios
|
let userPromise = axios
|
||||||
.get("/user")
|
.get("/user")
|
||||||
.then(res => {
|
.then(res => {
|
||||||
|
// console.log(res.data.credentials.following);
|
||||||
|
let list = [];
|
||||||
|
let fol = false;
|
||||||
|
res.data.credentials.following.forEach(follow => {
|
||||||
|
console.log(follow);
|
||||||
|
if (this.state.profile === follow.handle) {
|
||||||
|
fol = true;
|
||||||
|
list = follow.topics;
|
||||||
|
}
|
||||||
|
});
|
||||||
this.setState({
|
this.setState({
|
||||||
following: res.data.credentials.following.includes(
|
following: fol,
|
||||||
this.state.profile
|
myTopics: list
|
||||||
),
|
|
||||||
myTopics: res.data.credentials.followedTopics
|
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.catch(err => console.log(err));
|
.catch(err => console.log(err));
|
||||||
@ -153,6 +180,23 @@ class user extends Component {
|
|||||||
})
|
})
|
||||||
.catch(err => console.log(err));
|
.catch(err => console.log(err));
|
||||||
|
|
||||||
|
axios
|
||||||
|
.get("/getAlert")
|
||||||
|
.then(res => {
|
||||||
|
let temp = this.state.posts;
|
||||||
|
// console.log(res.data);
|
||||||
|
res.data.forEach(element => {
|
||||||
|
element ? temp.push(element) : console.err;
|
||||||
|
});
|
||||||
|
// temp.push(res.data[0]);
|
||||||
|
this.setState({
|
||||||
|
posts: temp
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch(function(err) {
|
||||||
|
console.log(err);
|
||||||
|
});
|
||||||
|
|
||||||
Promise.all([otherUserPromise, userPromise, posts])
|
Promise.all([otherUserPromise, userPromise, posts])
|
||||||
.then(() => {
|
.then(() => {
|
||||||
this.setState({loading: false});
|
this.setState({loading: false});
|
||||||
@ -188,8 +232,8 @@ class user extends Component {
|
|||||||
<p>loading username...</p>
|
<p>loading username...</p>
|
||||||
);
|
);
|
||||||
|
|
||||||
console.log(this.state.topics);
|
// console.log(this.state.topics);
|
||||||
console.log(this.state.myTopics);
|
// console.log(this.state.myTopics);
|
||||||
let topicsMarkup = this.state.topics ? (
|
let topicsMarkup = this.state.topics ? (
|
||||||
this.state.topics.map(
|
this.state.topics.map(
|
||||||
topic =>
|
topic =>
|
||||||
@ -206,6 +250,8 @@ class user extends Component {
|
|||||||
label={topic}
|
label={topic}
|
||||||
key={{ topic }.topic.id}
|
key={{ topic }.topic.id}
|
||||||
color="secondary"
|
color="secondary"
|
||||||
|
clickable
|
||||||
|
onClick={key => this.handleAdd(topic)}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
) : (
|
) : (
|
||||||
@ -222,7 +268,7 @@ class user extends Component {
|
|||||||
) : (
|
) : (
|
||||||
<img src={noImage} height="150" width="150" />
|
<img src={noImage} height="150" width="150" />
|
||||||
);
|
);
|
||||||
|
//(this.state.posts);
|
||||||
let postMarkup = this.state.posts ? (
|
let postMarkup = this.state.posts ? (
|
||||||
this.state.posts.map(post => (
|
this.state.posts.map(post => (
|
||||||
<Card className={classes.card}>
|
<Card className={classes.card}>
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user