Compare commits

...

57 Commits

Author SHA1 Message Date
dependabot[bot]
75b3030c88 Merge aae2ccd6c4 into d1f42aa5cd 2024-12-15 19:36:44 +00:00
Clayton Wilson
d1f42aa5cd Update README.md 2022-03-06 11:12:16 -05:00
Clayton Wilson
f118ed76d1 Added screenshots 2022-03-06 10:09:02 -06:00
dependabot[bot]
aae2ccd6c4 Bump lodash from 4.17.15 to 4.17.21 in /functions
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.15 to 4.17.21.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.15...4.17.21)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-11 22:50:43 +00:00
DreamCoder23
b9cbd610a9 Update README.md 2020-10-11 23:17:34 -07:00
daabbf80f6 Actually fix deploy error 2019-12-06 14:58:51 -05:00
f9acefaafb Fixed deploy error 2019-12-06 14:55:01 -05:00
948eff32c2 Fix 2019-12-06 14:26:42 -05:00
6de219505a Fix admin alert posts displaying 2019-12-06 14:25:05 -05:00
7132a2ab45 Fix error in getOtherUsersPosts 2019-12-06 14:10:17 -05:00
5474543af4 add catch in addSubscription 2019-12-06 13:56:48 -05:00
6f77d03e2d Add back verify button for Admin 2019-12-06 13:51:21 -05:00
da6e7436ea Merge branch 'master' of https://github.com/ClaytonWWilson/CS307-Team24 2019-12-06 13:35:32 -05:00
e7afac9a19 Fix post topics being added to followed topics list 2019-12-06 13:35:28 -05:00
Aditya Sankaran
9449d3544b Merge branch 'master' of https://github.com/ClaytonWWilson/CS307-Team24 2019-12-06 13:06:52 -05:00
4f2e07756d tell the user if they aren't following anybody 2019-12-06 13:04:59 -05:00
Aditya Sankaran
f2cf7542a8 fix 2019-12-06 13:04:43 -05:00
ff7677bfb3 Merge pull request #113 from ClaytonWWilson/admin-delete
Admin delete
2019-12-06 12:56:40 -05:00
978af53a74 Merge pull request #114 from ClaytonWWilson/temp-branch
Display disabled DMs as red and fix errors in login and signup
2019-12-06 12:53:57 -05:00
a0a522f1d2 Display disabled DMs as red and fix errors in login and signup 2019-12-06 12:53:27 -05:00
Aditya Sankaran
988c807af2 Merge branch 'master' of https://github.com/ClaytonWWilson/CS307-Team24 2019-12-06 12:27:00 -05:00
Aditya Sankaran
01b449d01d separated list of topics by comma and space 2019-12-06 12:26:29 -05:00
f30a9ae27c Fix merge errors, but posts are not displaying on home.js 2019-12-06 12:07:36 -05:00
a459e6581e Merge branch 'master' into admin-delete 2019-12-06 11:45:50 -05:00
Leon Liang
b769ab930a Merge pull request #112 from ClaytonWWilson/fix_unfollow
Fix unfollow
2019-12-06 02:28:42 -05:00
Leon Liang
116f97bf64 fixed topic.id bug 2019-12-06 02:26:01 -05:00
Leon Liang
a4efc15d58 allow follow topic only when following user 2019-12-06 02:23:28 -05:00
Leon Liang
39613584e7 fixed unfollow user and topics 2019-12-06 02:17:52 -05:00
a1f9a4bef3 Fixing errors on the otherUsers page 2019-12-05 21:39:38 -05:00
c85eeccd4c Display formatted time on otherUser page 2019-12-05 21:16:46 -05:00
Leon Liang
bb50e0fa5d Merge pull request #111 from ClaytonWWilson/filter_timeli
fixed up add subscription method
2019-12-05 19:25:44 -05:00
Leon Liang
f111553827 fixed up add subscription method 2019-12-05 19:24:50 -05:00
Aditya Sankaran
5e935f3508 Merge branch 'master' of https://github.com/ClaytonWWilson/CS307-Team24 2019-12-05 19:20:50 -05:00
Aditya Sankaran
80a2e1894c sorted posts chronologically everywhere 2019-12-05 19:20:05 -05:00
8acd29e842 Merge branch 'master' of https://github.com/ClaytonWWilson/CS307-Team24 2019-12-05 19:14:47 -05:00
b402c96864 Fixing DMs with users who have them disabled 2019-12-05 19:13:00 -05:00
asankaran35
76792148cd Merge pull request #110 from ClaytonWWilson/chronological
can sort posts chronologically in userline and formatted topics listi…
2019-12-05 18:56:18 -05:00
Aditya Sankaran
a92681451f syntax error 2019-12-05 18:54:43 -05:00
Aditya Sankaran
e3522876d7 can sort posts chronologically in userline and formatted topics listing for each post 2019-12-05 18:50:29 -05:00
Leon Liang
c7859e0f0a Merge pull request #109 from ClaytonWWilson/finalfix
fixed user and topic relationship. allow add topic directly
2019-12-05 17:25:53 -05:00
Leon Liang
aad9dc0273 Merge branch 'master' into finalfix 2019-12-05 17:25:19 -05:00
Leon Liang
30df98343e added user post tuple 2019-12-05 17:22:55 -05:00
719294f0ed Fix DM code layout 2019-12-05 16:13:56 -05:00
fc9994d42e fixed circular progress on home 2019-12-05 13:47:10 -05:00
Leon Liang
de72bd9223 added alert to user's page 2019-12-05 13:45:58 -05:00
b85bee7cba Fix merge issue 2019-12-05 13:41:24 -05:00
76330fd234 Merge pull request #108 from ClaytonWWilson/send-microblog-loading
Send microblog loading
2019-12-05 13:38:53 -05:00
b007666317 Merge branch 'master' into send-microblog-loading 2019-12-05 13:38:04 -05:00
a0d2532c22 Add circular progress to home page 2019-12-05 13:35:19 -05:00
739b1cc92a Add circular progress to other user page 2019-12-05 13:22:29 -05:00
57087a5ea3 Add circular progress to user page 2019-12-05 13:08:59 -05:00
Leon Liang
3424a7d34f Merge pull request #107 from ClaytonWWilson/finalfix
filter by followed user
2019-12-05 13:02:52 -05:00
1aff5ba99b Add circular progress to writing_microblogs 2019-12-05 12:56:05 -05:00
Leon Liang
2bcf6bfcb3 filter by followed user 2019-12-05 12:48:26 -05:00
Danny Voltz
bae2947003 Merge branch 'admin-delete' of https://github.com/ClaytonWWilson/CS307-Team24 into admin-delete:x 2019-12-05 12:25:19 -05:00
Danny Voltz
96423cee8a Admin User Stories 2019-12-05 12:12:25 -05:00
Danny Voltz
6924af58a7 progress for admin delete 2019-11-01 15:40:26 -05:00
22 changed files with 2625 additions and 928 deletions

View File

@@ -1,2 +1,14 @@
# CS307-Team24 # CS307-Team24
CS307 Team 24 Twistter website. CS307 Team 24 Twistter website
### Images
<p>
<img alt="00.png" src="./screenshots/00.png" width="1000">
<img alt="01.png" src="./screenshots/01.png" width="1000">
<img alt="02.png" src="./screenshots/02.png" width="1000">
<img alt="03.png" src="./screenshots/03.png" width="1000">
<img alt="04.png" src="./screenshots/04.png" width="1000">
<img alt="05.png" src="./screenshots/05.png" width="1000">
<img alt="06.png" src="./screenshots/06.png" width="1000">
<img alt="07.png" src="./screenshots/07.png" width="1000">
</p>

View File

@@ -1,7 +1,7 @@
/* eslint-disable prefer-arrow-callback */ /* eslint-disable prefer-arrow-callback */
/* eslint-disable promise/always-return */ /* eslint-disable promise/always-return */
const admin = require("firebase-admin"); const { admin, db } = require("../util/admin");
const { db } = require("../util/admin");
exports.putPost = (req, res) => { exports.putPost = (req, res) => {
const newPost = { const newPost = {
@@ -33,6 +33,18 @@ exports.putPost = (req, res) => {
}); });
}; };
exports.deletePost = (req, res) => {
let posts = db.collection("posts")
.where("userHandle", "==", req.user.handle)
.get()
.then((query) => {
query.forEach((snap) => {
snap.ref.delete();
});
return;
})
};
exports.getallPostsforUser = (req, res) => { exports.getallPostsforUser = (req, res) => {
var post_query = admin var post_query = admin
.firestore() .firestore()
@@ -46,6 +58,106 @@ exports.getallPostsforUser = (req, res) => {
myPosts.forEach(function(doc) { myPosts.forEach(function(doc) {
posts.push(doc.data()); posts.push(doc.data());
}); });
posts.sort((a, b) => -a.createdAt.localeCompare(b.createdAt));
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({message: "Failed to retrieve user's posts from database.", error: err});
});
};
exports.hidePost = (req, res) => {
/* db
.collection("posts")
.doc(${req.params.postId}) */
const postId = req.body.postId;
db.doc(`/posts/${postId}`)
.update({
hidden: true
})
.then(() => {
return res.status(200).json({message: "ok"});
})
.catch((error) => {
return res.status(500).json(error);
})
};
exports.getallPosts = (req, res) => {
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());
});
posts.sort((a, b) => -a.createdAt.localeCompare(b.createdAt));
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.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());
});
posts.sort((a, b) => -a.createdAt.localeCompare(b.createdAt));
return res.status(200).json(posts); return res.status(200).json(posts);
}) })
.then(function() { .then(function() {
@@ -60,60 +172,17 @@ exports.getallPostsforUser = (req, res) => {
}); });
}; };
exports.getallPosts = (req, res) => {
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());
});
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) => { exports.getOtherUsersPosts = (req, res) => {
var post_query = admin var post_query = admin
.firestore() .firestore()
.collection("posts") .collection("posts")
.where("userHandle", "==", req.body.handle); .where("userHandle", "==", req.body.handle);
// post_query += admin
// .firestore()
// .collection("posts")
// .where("microBlogTitle", "==", "Alert").where("userHandle", "==", "Admin");
post_query post_query
.get() .get()
.then(function(myPosts) { .then(function(myPosts) {
@@ -121,6 +190,7 @@ exports.getOtherUsersPosts = (req, res) => {
myPosts.forEach(function(doc) { myPosts.forEach(function(doc) {
posts.push(doc.data()); posts.push(doc.data());
}); });
posts.sort((a, b) => -a.createdAt.localeCompare(b.createdAt));
return res.status(200).json(posts); return res.status(200).json(posts);
}) })
.then(function() { .then(function() {
@@ -137,21 +207,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()
.then(doc => {
if (doc.exists) { 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 +273,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()
.then(doc => {
if (doc.exists) { 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 +346,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 +357,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 +437,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 +463,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 +516,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", "==");
}; };

View File

@@ -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()

View File

@@ -1,5 +1,6 @@
/* eslint-disable promise/catch-or-return */ /* eslint-disable promise/catch-or-return */
/* eslint-disable promise/always-return */ /* eslint-disable promise/always-return */
/* eslint-disable prefer-promise-reject-error */
const { admin, db } = require("../util/admin"); const { admin, db } = require("../util/admin");
const config = require("../util/config"); const config = require("../util/config");
@@ -226,7 +227,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 +240,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 +280,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 +310,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 +319,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 +342,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,15 +462,16 @@ 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
@@ -569,6 +578,7 @@ exports.getDirectMessages = (req, res) => {
* messageId: str * messageId: str
* } * }
* recipient: str * recipient: str
* hasDirectMessagesEnabled: bool
* recentMessage: str * recentMessage: str
* recentMessageTimestamp: ISOString * recentMessageTimestamp: ISOString
* } * }
@@ -577,9 +587,9 @@ 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 means that there aren't any messages
if (messagesCollection === null || messagesCollection === undefined) { if (messagesCollection === null || messagesCollection === undefined) {
return; return;
} }
@@ -588,90 +598,106 @@ 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;
const dmRecipients = req.userData.dmRecipients;
// 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);
}) })
) );
});
}) // Get all the data from the users to get the data on whether they have DMs enabled or not
let userPromises = [];
dmRecipients.forEach(recipient => {
userPromises.push(db.doc(`/users/${recipient}`).get());
});
// 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) Promise.all(dmPromises)
.then(() => { .then(() => {
return Promise.all(userPromises);
})
.then(userData => {
// 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 +717,32 @@ exports.getDirectMessages = (req, res) => {
return 0; return 0;
} }
}); });
return res.status(200).json({data: dmsData})
dmsData.forEach(dm => {
dm.hasDirectMessagesEnabled =
userData
.find(user => {
if (dm.recipient === user.data().handle) {
return true;
} else {
return false;
}
}) })
.catch((err) => { .data().dmEnabled === false
return res.status(500).json({error:{ ? false
: true;
});
return res.status(200).json({ data: dmsData });
})
.catch(err => {
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,38 +751,44 @@ 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 {
result.code = 200; result.code = 400;
result.message = `${username} has DMs disabled`; result.message = `${username} has DMs disabled`;
reject(result); reject(result);
} }
@@ -750,42 +799,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 +863,20 @@ 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}`));
let e = new Error(`You already have a DM with that user`);
e.code = 400,
e.message = `You already have a DM with that user`
reject(e);
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 +922,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 +936,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,21 +986,43 @@ 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/${recipient}`)
.then((userDoc) => { .get()
.then(recipDoc => {
// Return if the other user has DM's disabled
if (
recipDoc.data().dmEnabled === false &&
recipDoc.data().dmEnabled !== null &&
recipDoc.data().dmEnabled !== undefined
) {
return res.status(400).json({ error: "This user has DMs disabled" });
}
});
db.doc(`/users/${creator}`)
.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) ||
@@ -957,41 +1033,45 @@ exports.sendDirectMessage = (req, res) => {
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 +1082,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,45 +1092,52 @@ 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) {
@@ -1059,8 +1147,8 @@ exports.createDirectMessage = (req, res) => {
// 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
@@ -1071,7 +1159,7 @@ exports.checkDirectMessagesEnabled = (req, res) => {
.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
@@ -1080,8 +1168,8 @@ exports.checkDirectMessagesEnabled = (req, res) => {
// 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 +1193,13 @@ 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); const struct = {
handle: req.body.following,
topics: ["Admin"]
};
new_following
? new_following.push(struct)
: (new_following = req.body.following);
// add stuff // add stuff
userRef userRef
@@ -1118,8 +1212,11 @@ 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" });
}); })
.catch((error) => {
return res.status(400).json({message: "That user doesn't exist", error});
})
}; };
exports.getSubs = (req, res) => { exports.getSubs = (req, res) => {
@@ -1146,25 +1243,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 +1284,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 +1366,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 = [];
@@ -1262,7 +1375,7 @@ exports.removeSub = (req, res) => {
new_following = doc.data().following; new_following = doc.data().following;
// remove username from array // remove username from array
new_following.forEach(function(follower, index) { new_following.forEach(function(follower, index) {
if (follower === `${req.body.unfollow}`) { if (follower.handle === `${req.body.unfollow}`) {
new_following.splice(index, 1); new_following.splice(index, 1);
} }
}); });

View File

@@ -100,18 +100,33 @@ 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,
hidePost,
likePost,
unlikePost,
getLikes,
quoteWithPost,
quoteWithoutPost,
checkforLikePost,
getOtherUsersPosts,
getAlert
} = require("./handlers/post");
app.get("/getallPostsforUser", fbAuth, getallPostsforUser); app.get("/getallPostsforUser", fbAuth, getallPostsforUser);
app.get("/getallPosts", getallPosts); app.get("/getallPosts", getallPosts);
//Hides Post
app.post("/hidePost", fbAuth, hidePost);
// Adds one post to the database // Adds one post to the database
app.post("/putPost", fbAuth, putPost); app.post("/putPost", fbAuth, putPost);
@@ -125,6 +140,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 +149,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 +165,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);

View File

@@ -673,6 +673,14 @@
"readable-stream": "~1.0.32" "readable-stream": "~1.0.32"
} }
}, },
"busboy": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-0.3.1.tgz",
"integrity": "sha512-y7tTxhGKXcyBxRKAni+awqx8uqaJKrSFSNFSeRG5CsWNdmy2BIK+6VGWEW7TZnIO/533mtMEA4rOevQV815YJw==",
"requires": {
"dicer": "0.3.0"
}
},
"bytebuffer": { "bytebuffer": {
"version": "5.0.1", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/bytebuffer/-/bytebuffer-5.0.1.tgz", "resolved": "https://registry.npmjs.org/bytebuffer/-/bytebuffer-5.0.1.tgz",
@@ -2593,9 +2601,9 @@
} }
}, },
"lodash": { "lodash": {
"version": "4.17.15", "version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==" "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="
}, },
"lodash.at": { "lodash.at": {
"version": "4.6.0", "version": "4.6.0",

BIN
screenshots/00.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

BIN
screenshots/01.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

BIN
screenshots/02.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

BIN
screenshots/03.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
screenshots/04.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

BIN
screenshots/05.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

BIN
screenshots/06.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
screenshots/07.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -8,6 +8,7 @@ import TextField from '@material-ui/core/TextField';
// import Typography from '@material-ui/core/Typography'; // import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button'; import Button from '@material-ui/core/Button';
import withStyles from "@material-ui/styles/withStyles"; import withStyles from "@material-ui/styles/withStyles";
import CircularProgress from "@material-ui/core/CircularProgress";
const styles = { const styles = {
container: { container: {
@@ -21,6 +22,13 @@ const styles = {
}, },
textField: { textField: {
marginBottom: 15 marginBottom: 15
},
progress: {
position: "absolute"
},
button: {
positon: "relative",
marginBottom: 30
} }
} }
@@ -31,7 +39,8 @@ class Writing_Microblogs extends Component {
value: "", value: "",
title: "", title: "",
topics: "", topics: "",
characterCount: 250 characterCount: 250,
loading: false
}; };
this.handleChange = this.handleChange.bind(this); this.handleChange = this.handleChange.bind(this);
@@ -56,11 +65,15 @@ class Writing_Microblogs extends Component {
microBlogTitle: this.state.title, microBlogTitle: this.state.title,
microBlogTopics: this.state.topics.split(", ") microBlogTopics: this.state.topics.split(", ")
}; };
this.setState({
loading: true
})
const headers = { const headers = {
headers: { "Content-Type": "application/json" } headers: { "Content-Type": "application/json" }
}; };
axios let postPromise = axios
.post("/putPost", postData, headers) // TODO: add topics .post("/putPost", postData, headers) // TODO: add topics
.then(res => { .then(res => {
// alert("Post was shared successfully!"); // alert("Post was shared successfully!");
@@ -71,20 +84,35 @@ class Writing_Microblogs extends Component {
console.error(err); console.error(err);
}); });
console.log(postData.microBlogTopics); console.log(postData.microBlogTopics);
postData.microBlogTopics.forEach(topic => { // let topicPromises = [];
axios // postData.microBlogTopics.forEach(topic => {
.post("/putTopic", { // topicPromises.push(axios
following: topic // .post("/putTopic", {
}) // following: topic
.then(res => { // })
console.log(res.data); // .then(res => {
}) // console.log(res.data);
.catch(err => { // })
console.error(err); // .catch(err => {
}); // console.error(err);
}); // })
// )
// });
event.preventDefault(); event.preventDefault();
this.setState({ value: "", title: "", characterCount: 250, topics: "" }); // topicPromises.push(postPromise);
Promise.all([postPromise])
.then(() => {
this.setState({
value: "",
title: "",
characterCount: 250,
topics: "",
loading: false
});
})
.catch((error) => {
console.log(error);
})
} }
handleChangeforPost(event) { handleChangeforPost(event) {
@@ -149,12 +177,14 @@ class Writing_Microblogs extends Component {
autoComplete='off' autoComplete='off'
/> />
<Button <Button
className={classes.button}
onClick={this.handleSubmit} onClick={this.handleSubmit}
// disabled={loading} disabled={this.state.loading}
variant="outlined" variant="outlined"
color="primary" color="primary"
> >
Share Post Share Post
{this.state.loading && <CircularProgress size={30} className={classes.progress} />}
</Button> </Button>
</form> </form>
</div> </div>

View File

@@ -6,78 +6,134 @@ import axios from "axios";
// Material UI and React Router // Material UI and React Router
import CircularProgress from '@material-ui/core/CircularProgress'; import CircularProgress from "@material-ui/core/CircularProgress";
import Button from '@material-ui/core/Button'; import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid"; import Grid from "@material-ui/core/Grid";
import Card from "@material-ui/core/Card"; import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent"; import CardContent from "@material-ui/core/CardContent";
import TextField from '@material-ui/core/TextField'; import TextField from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography"; import Typography from "@material-ui/core/Typography";
import withStyles from '@material-ui/styles/withStyles'; import withStyles from "@material-ui/styles/withStyles";
// component // component
import '../App.css'; import "../App.css";
import logo from '../images/twistter-logo.png'; import logo from "../images/twistter-logo.png";
import noImage from '../images/no-img.png'; import noImage from "../images/no-img.png";
import Writing_Microblogs from '../Writing_Microblogs'; import Writing_Microblogs from "../Writing_Microblogs";
import ReactModal from 'react-modal'; import ReactModal from "react-modal";
// Redux // Redux
import { likePost, unlikePost, getLikes } from '../redux/actions/userActions'; import { likePost, unlikePost, getLikes } from "../redux/actions/userActions";
const styles = { const styles = {
card: { card: {
marginBottom: 5 marginBottom: 5
} }
} };
class Home extends Component { class Home extends Component {
state = { state = {
likes: [] likes: [],
loading: false,
following: null,
topics: null
}; };
componentDidMount() { componentDidMount() {
axios this.setState({ loading: true });
.get("/getallPosts") let userPromise = axios
.get("/user")
.then(res => { .then(res => {
// console.log(res.data); console.log(res.data.credentials.following);
let list = [];
res.data.credentials.following.forEach(element => {
list.push(element.handle);
});
this.setState({ this.setState({
posts: res.data following: list,
topics: res.data.credentials.followedTopics
}); });
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
let allPosts;
let postPromise = axios
.get("/getallPosts")
.then(res => {
// console.log(res.data);
// this.setState({
// posts: res.data
// });
allPosts = res.data;
// console.log(allPosts)
return axios.get("/getAlert")
})
.then((res) => {
// console.log(res.data)
// res.data.forEach((adminAlert) => {
// allPosts.push(adminAlert);
// })
this.setState({
posts: allPosts
});
})
.catch(err => console.log(err));
Promise.all([userPromise, postPromise])
.then(() => {
this.setState({
loading: false
});
})
.catch(error => {
console.log(error);
});
this.props.getLikes(); this.props.getLikes();
} }
componentWillReceiveProps(nextProps) { componentWillReceiveProps(nextProps) {
this.setState({ this.setState({
likes: nextProps.user.likes likes: nextProps.user.likes
});
}
flagPost = (event) => {
// Flags a post
let postId = event.target.dataset.key ? event.target.dataset.key : event.target.parentNode.dataset.key;
console.log(postId);
axios.post(`/hidePost`, {postId})
.then((res) => {
console.log(res.data);
}) })
.catch(err => {
console.error(err);
});
// event.preventDefault();
} }
handleClickLikeButton = (event) => { handleClickLikeButton = (event) => {
// Need the ternary if statement because the user can click on the text or body of the // Need the ternary if statement because the user can click on the text or body of the
// Button and they are two different html elements // Button and they are two different html elements
let postId = event.target.dataset.key ? event.target.dataset.key : event.target.parentNode.dataset.key; let postId = event.target.dataset.key
console.log(postId) ? event.target.dataset.key
: event.target.parentNode.dataset.key;
console.log(postId);
let doc = document.getElementById(postId); let doc = document.getElementById(postId);
// console.log(postId); // console.log(postId);
if (this.state.likes.includes(postId)) { if (this.state.likes.includes(postId)) {
this.props.unlikePost(postId, this.state.likes) this.props.unlikePost(postId, this.state.likes);
doc.dataset.likes--; doc.dataset.likes--;
} else { } else {
this.props.likePost(postId, this.state.likes) this.props.likePost(postId, this.state.likes);
doc.dataset.likes++; doc.dataset.likes++;
} }
doc.innerHTML = "Likes " + doc.dataset.likes; doc.innerHTML = "Likes " + doc.dataset.likes;
};
}
formatDate(dateString) { formatDate(dateString) {
let newDate = new Date(Date.parse(dateString)); let newDate = new Date(Date.parse(dateString));
@@ -85,14 +141,21 @@ class Home extends Component {
} }
render() { render() {
const {
const { UI:{ loading } } = this.props; UI: { loading }
} = this.props;
let authenticated = this.props.user.authenticated; let authenticated = this.props.user.authenticated;
let { classes } = this.props; let { classes } = this.props;
let username = this.props.user.credentials.handle; let username = this.props.user.credentials.handle;
console.log(username);
var hiddenBool = true;
if (username === "Admin") {
hiddenBool = false;
}
let postMarkup = this.state.posts ? ( console.log(hiddenBool);
this.state.posts.map(post => let postMarkup = this.state.posts ? ( this.state.following === undefined || this.state.following === null ? <Typography>You aren't following anybody right now</Typography> :
this.state.posts.map(post => !post.hidden && this.state.following && (this.state.following.includes(post.userHandle) || post.userHandle === "Admin") ? (
<Card className={classes.card} key={post.postId}> <Card className={classes.card} key={post.postId}>
<CardContent> <CardContent>
<Typography> <Typography>
@@ -113,8 +176,19 @@ class Home extends Component {
<br /> <br />
<Typography variant="body2">{post.body}</Typography> <Typography variant="body2">{post.body}</Typography>
<br /> <br />
<Typography variant="body2"><b>Topics:</b> {post.microBlogTopics}</Typography> <Typography variant="body2"><b>Topics:</b> {post.microBlogTopics.join(", ")}</Typography>
<br /> <br />
{!hiddenBool &&
<Button
onClick={this.flagPost}
data-key={post.postId}
variant = "contained"
color = "primary"
>
Hide Post
</Button>
}
<Typography id={post.postId} data-likes={post.likeCount} variant="body2" color={"textSecondary"}>Likes {post.likeCount}</Typography> <Typography id={post.postId} data-likes={post.likeCount} variant="body2" color={"textSecondary"}>Likes {post.likeCount}</Typography>
{/* <Like microBlog = {post.postId} count = {post.likeCount} name = {username}></Like> */} {/* <Like microBlog = {post.postId} count = {post.likeCount} name = {username}></Like> */}
<Button <Button
@@ -130,15 +204,25 @@ class Home extends Component {
{/* <button>Quote</button> */} {/* <button>Quote</button> */}
{/* <Typography variant="body2" color={"textSecondary"}>Likes {post.likeCount} Comments {post.commentCount}</Typography> */}
</CardContent> </CardContent>
</Card> </Card>
) : (
<p></p>
)
) )
) : ( ) : (
<p>Loading post...</p> <p>Loading post...</p>
); );
return ( return authenticated ? (
authenticated ? ( this.state.loading ? (
<CircularProgress
size={60}
style={{ marginTop: "300px" }}
></CircularProgress>
) : (
<Grid container> <Grid container>
<Grid item sm={4} xs={8}> <Grid item sm={4} xs={8}>
<Writing_Microblogs /> <Writing_Microblogs />
@@ -147,24 +231,33 @@ class Home extends Component {
{postMarkup} {postMarkup}
</Grid> </Grid>
</Grid> </Grid>
) : loading ? )
(<CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress>) ) : loading ? (
: <CircularProgress
( size={60}
style={{ marginTop: "300px" }}
></CircularProgress>
) : (
<div> <div>
<div> <div>
<img src={logo} className="app-logo" alt="logo" /> <img src={logo} className="app-logo" alt="logo" />
<br/><br/> <br />
<br />
<b>Welcome to Twistter!</b> <b>Welcome to Twistter!</b>
<br/><br/> <br />
<br />
<b>See the most interesting topics people are following right now.</b> <b>See the most interesting topics people are following right now.</b>
</div> </div>
<br/><br/><br/><br/> <br />
<br />
<br />
<br />
<div> <div>
<b>Join today or sign in if you already have an account.</b> <b>Join today or sign in if you already have an account.</b>
<br/><br/> <br />
<br />
<form action="./signup"> <form action="./signup">
<button className="authButtons signup">Sign up</button> <button className="authButtons signup">Sign up</button>
</form> </form>
@@ -174,7 +267,7 @@ class Home extends Component {
</form> </form>
</div> </div>
</div> </div>
)); );
} }
} }
@@ -185,7 +278,7 @@ class Quote extends Component {
characterCount: 250, characterCount: 250,
showModal: false, showModal: false,
value: "" value: ""
} };
this.handleSubmitWithoutPost = this.handleSubmitWithoutPost.bind(this); this.handleSubmitWithoutPost = this.handleSubmitWithoutPost.bind(this);
this.handleOpenModal = this.handleOpenModal.bind(this); this.handleOpenModal = this.handleOpenModal.bind(this);
@@ -195,19 +288,17 @@ class Quote extends Component {
handleSubmitWithoutPost(event) { handleSubmitWithoutPost(event) {
const post = { const post = {
userImage: "bing-url"
userImage: "bing-url", };
}
const headers = { const headers = {
headers: { "Content-Type": "application/json" } headers: { "Content-Type": "application/json" }
}; };
axios.post(`/quoteWithoutPost/${this.props.microblog}`, post, headers) axios
.then((res) => { .post(`/quoteWithoutPost/${this.props.microblog}`, post, headers)
.then(res => {
console.log(res.data); console.log(res.data);
}) })
.catch(err => { .catch(err => {
console.error(err); console.error(err);
}); });
event.preventDefault(); event.preventDefault();
@@ -234,18 +325,17 @@ class Quote extends Component {
handleSubmit(event) { handleSubmit(event) {
const quotedPost = { const quotedPost = {
quoteBody: this.state.value, quoteBody: this.state.value,
userImage: "bing-url", userImage: "bing-url"
}; };
const headers = { const headers = {
headers: { "Content-Type": "application/json" } headers: { "Content-Type": "application/json" }
}; };
axios.post(`/quoteWithPost/${this.props.microblog}`, quotedPost, headers) axios
.then((res) => { .post(`/quoteWithPost/${this.props.microblog}`, quotedPost, headers)
.then(res => {
console.log(res.data); console.log(res.data);
}) })
.catch(err => { .catch(err => {
console.error(err); console.error(err);
}); });
event.preventDefault(); event.preventDefault();
@@ -255,10 +345,25 @@ class Quote extends Component {
render() { render() {
return ( return (
<div> <div>
<Button variant="outlined" color="primary" onClick={this.handleOpenModal}>Quote with Post</Button> <Button
variant="outlined"
color="primary"
onClick={this.handleOpenModal}
>
Quote with Post
</Button>
<ReactModal <ReactModal
isOpen={this.state.showModal} isOpen={this.state.showModal}
style={{content: {height: "50%", width: "25%", marginTop: "auto", marginLeft: "auto", marginRight: "auto", marginBottom : "auto"}}} style={{
content: {
height: "50%",
width: "25%",
marginTop: "auto",
marginLeft: "auto",
marginRight: "auto",
marginBottom: "auto"
}
}}
> >
<div style={{ width: "200px", marginLeft: "50px" }}> <div style={{ width: "200px", marginLeft: "50px" }}>
<form style={{ width: "350px" }}> <form style={{ width: "350px" }}>
@@ -291,85 +396,93 @@ class Quote extends Component {
this.handleChangeforPost(e); this.handleChangeforPost(e);
this.handleChangeforCharacterCount(e); this.handleChangeforCharacterCount(e);
}} }}
autoComplete='off' autoComplete="off"
></TextField> ></TextField>
<div style={{ fontSize: "14px", marginRight: "-100px" }}> <div style={{ fontSize: "14px", marginRight: "-100px" }}>
<p2>Characters Left: {this.state.characterCount}</p2> <p2>Characters Left: {this.state.characterCount}</p2>
</div> </div>
<Button variant="outlined" color="primary" onClick={this.handleSubmit}>Share Quoted Post</Button> <Button
variant="outlined"
<Button variant="outlined" color="primary" onClick={this.handleCloseModal}>Cancel</Button> color="primary"
onClick={this.handleSubmit}
>
Share Quoted Post
</Button>
<Button
variant="outlined"
color="primary"
onClick={this.handleCloseModal}
>
Cancel
</Button>
</form> </form>
</div> </div>
</ReactModal> </ReactModal>
<Button variant="outlined" color="primary" onClick={this.handleSubmitWithoutPost}>Quote without Post</Button> <Button
variant="outlined"
color="primary"
onClick={this.handleSubmitWithoutPost}
>
Quote without Post
</Button>
</div> </div>
) );
} }
} }
class Like extends Component { class Like extends Component {
constructor(props) { constructor(props) {
super(props) super(props);
this.state = { this.state = {
num : this.props.count, num: this.props.count
};
}
this.handleClick = this.handleClick.bind(this); this.handleClick = this.handleClick.bind(this);
} }
componentDidMount() { componentDidMount() {
this.setState({ this.setState({
like: localStorage.getItem(this.props.microBlog + this.props.name) === "false" like:
localStorage.getItem(this.props.microBlog + this.props.name) === "false"
}) });
} }
handleClick(){ handleClick(){
this.setState({ this.setState({
like: !this.state.like like: !this.state.like
}); });
localStorage.setItem(this.props.microBlog + this.props.name, this.state.like.toString()) localStorage.setItem(
this.props.microBlog + this.props.name,
this.state.like.toString()
);
if(this.state.like == false) if (this.state.like == false) {
{
this.setState(() => { this.setState(() => {
return {num: this.state.num + 1} return { num: this.state.num + 1 };
}); });
axios.get(`/like/${this.props.microBlog}`) axios
.then((res) => { .get(`/like/${this.props.microBlog}`)
.then(res => {
console.log(res.data); console.log(res.data);
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
})
}
else
{
this.setState(() => {
return {num: this.state.num - 1}
}); });
axios.get(`/unlike/${this.props.microBlog}`) } else {
.then((res) => { this.setState(() => {
return { num: this.state.num - 1 };
});
axios
.get(`/unlike/${this.props.microBlog}`)
.then(res => {
console.log(res.data); console.log(res.data);
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
}) });
} }
} }
/* componentDidMount() { /* componentDidMount() {
@@ -392,31 +505,28 @@ class Like extends Component {
} */ } */
render() { render() {
const label = this.state.like ? "Unlike" : "Like";
const label = this.state.like ? 'Unlike' : 'Like'
return ( return (
<div> <div>
<Typography variant="body2" color={"textSecondary"}>Likes {this.state.num}</Typography> <Typography variant="body2" color={"textSecondary"}>
Likes {this.state.num}
</Typography>
<button onClick={this.handleClick}>{label}</button> <button onClick={this.handleClick}>{label}</button>
</div> </div>
) );
}
} }
} const mapStateToProps = state => ({
const mapStateToProps = (state) => ({
user: state.user, user: state.user,
UI: state.UI UI: state.UI
}) });
const mapActionsToProps = { const mapActionsToProps = {
likePost, likePost,
unlikePost, unlikePost,
getLikes getLikes
} };
Home.propTypes = { Home.propTypes = {
user: PropTypes.object.isRequired, user: PropTypes.object.isRequired,
@@ -425,16 +535,17 @@ Home.propTypes = {
getLikes: PropTypes.func.isRequired, getLikes: PropTypes.func.isRequired,
classes: PropTypes.object.isRequired, classes: PropTypes.object.isRequired,
UI: PropTypes.object.isRequired UI: PropTypes.object.isRequired
} };
Like.propTypes = { Like.propTypes = {
user: PropTypes.object.isRequired user: PropTypes.object.isRequired
} };
Quote.propTypes = { Quote.propTypes = {
user: PropTypes.object.isRequired user: PropTypes.object.isRequired
} };
export default connect(mapStateToProps, mapActionsToProps)(withStyles(styles)(Home, Like, Quote));
export default connect(
mapStateToProps,
mapActionsToProps
)(withStyles(styles)(Home, Like, Quote));

View File

@@ -83,6 +83,10 @@ const styles = {
wordBreak: "break-all", wordBreak: "break-all",
color: 'black' color: 'black'
}, },
dmRecentMessageDisabled: {
wordBreak: "break-all",
color: 'red'
},
dmListItemContainer: { dmListItemContainer: {
height: 100 height: 100
}, },
@@ -426,13 +430,19 @@ export class directMessages extends Component {
<Typography <Typography
className={ className={
this.state.selectedChannel && this.state.selectedChannel.dmId === channel.dmId ? ( this.state.selectedChannel && this.state.selectedChannel.dmId === channel.dmId ? (
channel.hasDirectMessagesEnabled ?
classes.dmRecentMessageSelected classes.dmRecentMessageSelected
:
classes.dmRecentMessageDisabled
) : ( ) : (
channel.hasDirectMessagesEnabled ?
classes.dmRecentMessageUnselected classes.dmRecentMessageUnselected
:
classes.dmRecentMessageDisabled
) )
} }
> >
{ {!channel.hasDirectMessagesEnabled ? "This user has DMs disabled" :
!channel.recentMessage ? !channel.recentMessage ?
'No messages' 'No messages'
: :
@@ -548,8 +558,8 @@ export class directMessages extends Component {
> >
Create Create
{creatingDirectMessage && {creatingDirectMessage &&
<CircularProgress size={30} style={{position: "absolute"}}/>
// Won't accept classes style for some reason // Won't accept classes style for some reason
<CircularProgress size={30} style={{position: "absolute"}}/>
} }
</Button> </Button>
</Grid> </Grid>
@@ -597,7 +607,16 @@ export class directMessages extends Component {
multiline multiline
rows={2} rows={2}
margin="dense" margin="dense"
value={this.state.drafts[this.state.selectedChannel.dmId] ? this.state.drafts[this.state.selectedChannel.dmId] : ""} disabled={!this.state.selectedChannel.hasDirectMessagesEnabled}
value={
!this.state.selectedChannel.hasDirectMessagesEnabled ?
"This user has DMs disabled"
:
this.state.drafts[this.state.selectedChannel.dmId] ?
this.state.drafts[this.state.selectedChannel.dmId]
:
""
}
onChange={this.handleChangeMessage} onChange={this.handleChangeMessage}
/> />
<Fab <Fab

View File

@@ -22,6 +22,7 @@ import AddCircle from "@material-ui/icons/AddCircle";
import TextField from "@material-ui/core/TextField"; import TextField from "@material-ui/core/TextField";
import VerifiedIcon from "@material-ui/icons/CheckSharp"; import VerifiedIcon from "@material-ui/icons/CheckSharp";
import DoneIcon from "@material-ui/icons/Done"; import DoneIcon from "@material-ui/icons/Done";
import CircularProgress from "@material-ui/core/CircularProgress";
// component // component
import "../App.css"; import "../App.css";
@@ -77,7 +78,9 @@ class user extends Component {
user: null, user: null,
following: null, following: null,
posts: null, posts: null,
myTopics: null myTopics: null,
followingList: null,
loading: false
}; };
} }
@@ -90,7 +93,8 @@ class user extends Component {
.then(res => { .then(res => {
console.log("removed sub"); console.log("removed sub");
this.setState({ this.setState({
following: false following: false,
myTopics: []
}); });
}) })
.catch(function(err) { .catch(function(err) {
@@ -113,8 +117,27 @@ class user extends Component {
} }
}; };
componentDidMount() { handleAdd = newTopic => {
axios 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() {
this.setState({ loading: true });
let otherUserPromise = axios
.post("/getUserDetails", { .post("/getUserDetails", {
handle: this.state.profile handle: this.state.profile
}) })
@@ -126,19 +149,26 @@ class user extends Component {
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
axios let userPromise = axios
.get("/user") .get("/user")
.then(res => { .then(res => {
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));
axios let posts = axios
.post("/getOtherUsersPosts", { .post("/getOtherUsersPosts", {
handle: this.state.profile handle: this.state.profile
}) })
@@ -149,6 +179,44 @@ class user extends Component {
}); });
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
// Only add Admin posts if this is not the Admin account
let alertPromise;
if (this.state.profile !== "Admin") {
alertPromise = 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);
});
} else {
alertPromise = new Promise((resolve, reject) => {
resolve();
});
}
Promise.all([otherUserPromise, userPromise, posts, alertPromise])
.then(() => {
this.setState({ loading: false });
})
.catch(error => {
console.log(error);
});
}
formatDate(dateString) {
let newDate = new Date(Date.parse(dateString));
return newDate.toDateString();
} }
render() { render() {
@@ -177,8 +245,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 =>
@@ -186,16 +254,20 @@ class user extends Component {
this.state.myTopics.includes(topic) ? ( this.state.myTopics.includes(topic) ? (
<MyChip <MyChip
label={topic} label={topic}
key={{ topic }.topic.id} key={{ topic }.id}
onDelete onDelete
deleteIcon={<DoneIcon />} deleteIcon={<DoneIcon />}
/> />
) : ( ) : this.state.following ? (
<MyChip <MyChip
label={topic} label={topic}
key={{ topic }.topic.id} key={{ topic }.id}
color="secondary" color="secondary"
clickable
onClick={key => this.handleAdd(topic)}
/> />
) : (
<MyChip label={topic} key={{ topic }.id} color="secondary" />
) )
) : ( ) : (
<p></p> <p></p>
@@ -211,10 +283,10 @@ 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} key={post.postId} data-key={post.postId}>
<CardContent> <CardContent>
<Typography> <Typography>
{this.state.imageUrl ? ( {this.state.imageUrl ? (
@@ -223,11 +295,11 @@ class user extends Component {
<img src={noImage} height="50" width="50" /> <img src={noImage} height="50" width="50" />
)} )}
</Typography> </Typography>
<Typography variant="h7"> <Typography variant="h4">
<b>{post.userHandle}</b> <b>{post.userHandle}</b>
</Typography> </Typography>
<Typography variant="body2" color={"textSecondary"}> <Typography variant="body2" color={"textSecondary"}>
{post.createdAt} {this.formatDate(post.createdAt)}
</Typography> </Typography>
<br /> <br />
@@ -240,7 +312,7 @@ class user extends Component {
<Typography variant="body2">{post.body}</Typography> <Typography variant="body2">{post.body}</Typography>
<br /> <br />
<Typography variant="body2"> <Typography variant="body2">
<b>Topics:</b> {post.microBlogTopics} <b>Topics:</b> {post.microBlogTopics.join(", ")}
</Typography> </Typography>
<br /> <br />
<Typography variant="body2" color={"textSecondary"}> <Typography variant="body2" color={"textSecondary"}>
@@ -253,8 +325,13 @@ class user extends Component {
<p>Posts</p> <p>Posts</p>
); );
return ( return this.state.loading ? (
<Grid container spacing={24}> <CircularProgress
size={60}
style={{ marginTop: "300px" }}
></CircularProgress>
) : (
<Grid container spacing={10}>
<Grid item sm={4} xs={8}> <Grid item sm={4} xs={8}>
{imageMarkup} {imageMarkup}
{profileMarkup} {profileMarkup}

View File

@@ -13,6 +13,7 @@ import CardMedia from "@material-ui/core/CardMedia";
import CardContent from "@material-ui/core/CardContent"; import CardContent from "@material-ui/core/CardContent";
import Button from "@material-ui/core/Button"; import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid"; import Grid from "@material-ui/core/Grid";
import CircularProgress from "@material-ui/core/CircularProgress";
import Chip from "@material-ui/core/Chip"; import Chip from "@material-ui/core/Chip";
import Typography from "@material-ui/core/Typography"; import Typography from "@material-ui/core/Typography";
@@ -76,7 +77,8 @@ class user extends Component {
profile: null, profile: null,
imageUrl: null, imageUrl: null,
topics: null, topics: null,
newTopic: "" newTopic: "",
loading: false
}; };
} }
@@ -127,7 +129,8 @@ class user extends Component {
} }
componentDidMount() { componentDidMount() {
axios this.setState({loading: true})
let userPromise = axios
.get("/user") .get("/user")
.then(res => { .then(res => {
this.setState({ this.setState({
@@ -141,7 +144,7 @@ class user extends Component {
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
axios let postsPromise = axios
.get("/getallPostsforUser") .get("/getallPostsforUser")
.then(res => { .then(res => {
// console.log(res.data); // console.log(res.data);
@@ -150,6 +153,14 @@ class user extends Component {
}); });
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
Promise.all([userPromise, postsPromise])
.then(() => {
this.setState({loading: false});
})
.catch((error) => {
console.log(error)
})
} }
formatDate(dateString) { formatDate(dateString) {
@@ -219,7 +230,7 @@ class user extends Component {
<b>{post.userHandle}</b> <b>{post.userHandle}</b>
</Typography> </Typography>
<Typography variant="body2" color={"textSecondary"}> <Typography variant="body2" color={"textSecondary"}>
{post.createdAt} {this.formatDate(post.createdAt) }
</Typography> </Typography>
<br /> <br />
@@ -232,7 +243,7 @@ class user extends Component {
<Typography variant="body2">{post.body}</Typography> <Typography variant="body2">{post.body}</Typography>
<br /> <br />
<Typography variant="body2"> <Typography variant="body2">
<b>Topics:</b> {post.microBlogTopics} <b>Topics:</b> {post.microBlogTopics.join(", ")}
</Typography> </Typography>
<br /> <br />
<Typography variant="body2" color={"textSecondary"}> <Typography variant="body2" color={"textSecondary"}>
@@ -258,7 +269,17 @@ class user extends Component {
</Link> </Link>
) : null; ) : null;
let verifyButtonMarkup = this.state.profile === "Admin" ?
<Link to="/verify">
<Button className={classes.button} variant="outlined" color="primary">
Verify Users
</Button>
</Link>
:
null
return ( return (
this.state.loading ? <CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress> :
<div> <div>
{/* <Paper className={classes.paper}> */} {/* <Paper className={classes.paper}> */}
<Grid container direction="column"> <Grid container direction="column">
@@ -266,6 +287,7 @@ class user extends Component {
<Grid container> <Grid container>
<Grid item sm> <Grid item sm>
{editButtonMarkup} {editButtonMarkup}
{verifyButtonMarkup}
</Grid> </Grid>
<Grid item sm> <Grid item sm>
{/* <Grid container direction="column"> */} {/* <Grid container direction="column"> */}

View File

@@ -142,5 +142,6 @@ export const sendDirectMessage = (user, message) => (dispatch) => {
sendDirectMessage: err.response.data sendDirectMessage: err.response.data
} }
}) })
dispatch({type: SET_NOT_LOADING_UI_4});
}) })
} }

View File

@@ -36,6 +36,7 @@ export const getUserData = () => (dispatch) => {
// Sends login data to firebase and sets the user data in Redux // Sends login data to firebase and sets the user data in Redux
export const loginUser = (loginData, history) => (dispatch) => { export const loginUser = (loginData, history) => (dispatch) => {
dispatch({type: CLEAR_ERRORS});
dispatch({ type: LOADING_UI }); dispatch({ type: LOADING_UI });
axios axios
.post("/login", loginData) .post("/login", loginData)
@@ -57,6 +58,7 @@ export const loginUser = (loginData, history) => (dispatch) => {
// Sends signup data to firebase and sets the user data in Redux // Sends signup data to firebase and sets the user data in Redux
export const signupUser = (newUserData, history) => (dispatch) => { export const signupUser = (newUserData, history) => (dispatch) => {
dispatch({type: CLEAR_ERRORS});
dispatch({ type: LOADING_UI }); dispatch({ type: LOADING_UI });
axios axios
.post("/signup", newUserData) .post("/signup", newUserData)