Compare commits

..

120 Commits

Author SHA1 Message Date
shobhitm23
23f1114cc5 Dark Mode implementation 2019-12-05 13:38:06 -05:00
f9a45ffe07 Merge pull request #84 from ClaytonWWilson/dms
Direct Messages
2019-12-04 22:47:50 -05:00
Aditya Sankaran
17c7e989ef cleared modal for quoting when hitting cancel button 2019-12-04 19:37:53 -05:00
Aditya Sankaran
efecf3b02a fixed stuff 2019-12-04 18:48:08 -05:00
Aditya Sankaran
8b4c32b81f syntax error 2019-12-04 18:20:28 -05:00
Aditya Sankaran
323cb5bcee Revert "module fuse and syntax errors fixed"
This reverts commit 4a4733f593.
2019-12-04 18:15:37 -05:00
Aditya Sankaran
4a4733f593 module fuse and syntax errors fixed 2019-12-04 18:09:36 -05:00
asankaran35
35cec7abf3 Merge pull request #106 from ClaytonWWilson/likes
Likes
2019-12-04 17:42:03 -05:00
asankaran35
6989091fb1 Merge branch 'master' into likes 2019-12-04 17:41:28 -05:00
Aditya Sankaran
699ea23750 quoting fix 2019-12-04 17:16:41 -05:00
0bcfdcdd6c Fix deploy error 2019-12-04 17:10:26 -05:00
4e5b100968 Fix merge issues and change layout of NavBar 2019-12-04 16:57:56 -05:00
374c4d45b0 Merge branch 'master' into dms 2019-12-04 15:56:42 -05:00
7efed257f2 Merge pull request #105 from ClaytonWWilson/display-profile-images-on-posts
Posts on Home now display profile images
2019-12-04 15:37:59 -05:00
99ffbe52a4 Posts on Home now display profile images 2019-12-04 15:37:09 -05:00
Aditya Sankaran
856cb8630e readded post.js. got deleted for some reason 2019-12-04 14:42:43 -05:00
0776728e73 Merge pull request #60 from ClaytonWWilson/edit-profile-image-upload
Edit profile image upload
2019-12-04 00:31:07 -05:00
77a3ba9f69 Fix merge issues 2019-12-04 00:30:23 -05:00
7a0a5725b7 Merge branch 'master' into edit-profile-image-upload 2019-12-04 00:02:03 -05:00
79051f2243 Error checking and deleting old profile image 2019-12-03 23:46:04 -05:00
94db3f451d Merge pull request #104 from ClaytonWWilson/fix-warnings
Fix warnings
2019-12-03 20:55:55 -05:00
fd1718a1f4 Fixing more errors 2019-12-03 20:54:54 -05:00
7fd976d4cb Merge branch 'master' into fix-warnings 2019-12-03 20:34:08 -05:00
72d099e05e Fixing errors and warnings 2019-12-03 20:26:31 -05:00
Leon Liang
f3fcd5ee8d Merge pull request #103 from ClaytonWWilson/others_topic
changed color if user is following the same topic
2019-12-03 19:16:17 -05:00
Leon Liang
7141bf9000 changed color if user is following the same topic 2019-12-03 19:15:23 -05:00
ebca5192e0 Change storageBucket to variable 2019-12-03 18:20:20 -05:00
Leon Liang
acecf704dc Merge pull request #102 from ClaytonWWilson/otheruser_posts
display posts on other user's page
2019-12-03 18:14:40 -05:00
Leon Liang
56e836451d display posts on other user's page 2019-12-03 18:11:10 -05:00
1747a29c2e Fix not image not uploading when deployed 2019-12-03 17:47:09 -05:00
041e53c36f Merge pull request #101 from ClaytonWWilson/confirm-delete
Confirm delete
2019-12-03 16:40:00 -05:00
2d426840c0 Add @ next to handle on editProfile 2019-12-03 16:37:57 -05:00
5b5e785142 Changed the path of the editProfile page 2019-12-03 16:37:04 -05:00
a4cce0b75e Circular progress when the editProfile page is loading 2019-12-03 16:26:54 -05:00
825c126c6c Delete asks you to confirm 2019-12-03 16:26:16 -05:00
49a4d55f1e Rename edit class to editProfile to be more descriptive 2019-12-03 14:04:40 -05:00
b4f4dec9ca Merge pull request #93 from ClaytonWWilson/fix-login-loading
Display loading icon when the user logs in or signs up
2019-12-03 13:50:55 -05:00
f0c4a2974f Fix mismatched parenthesis 2019-12-03 13:49:37 -05:00
c26ff21b20 Merge branch 'master' into fix-login-loading 2019-12-03 13:44:12 -05:00
3092fabfd2 Merge pull request #85 from ClaytonWWilson/microblogs-material-ui
Changing Writing_Microblogs to Material-UI and other UI tweaks
2019-12-03 13:35:27 -05:00
1a6aae6545 Fixed mismatched parenthesis 2019-12-03 13:33:48 -05:00
4abaa13b09 Merge branch 'master' into microblogs-material-ui 2019-12-03 13:24:36 -05:00
09a3ccd12d Merge branch 'master' into dms 2019-12-03 13:21:30 -05:00
f7058a520d Merge pull request #99 from ClaytonWWilson/improve-search
Improved speed of search and made it fuzzy search
2019-12-03 13:19:53 -05:00
1a02b53d0f Improved speed of search and made it fuzzy search 2019-12-03 00:54:06 -05:00
e4ea325fb8 Liking posts with Redux and Material UI 2019-12-02 20:18:44 -05:00
Leon Liang
6e32b25861 Merge pull request #98 from ClaytonWWilson/fix_follow
add topics when publish new post
2019-12-02 18:39:09 -05:00
Leon Liang
684ccd1a85 Merge branch 'master' into fix_follow 2019-12-02 18:38:54 -05:00
Leon Liang
f0ddaa30b1 add topics when publish new post 2019-12-02 18:31:33 -05:00
8244631d4d Fix some code after merge 2019-12-02 16:40:22 -05:00
4d97afcb09 Merge branch 'master' into microblogs-material-ui 2019-12-02 16:29:52 -05:00
88064c55a3 Merge branch 'master' into dms 2019-12-02 16:21:26 -05:00
7c7256acbd Fixed having multiple return statements in post.js 2019-12-02 15:47:26 -05:00
cff0fd4e05 DMs are deleted when the delete function runs 2019-12-02 15:46:13 -05:00
Leon Liang
e218708e0a Merge pull request #95 from ClaytonWWilson/fix_follow
Fix follow
2019-12-02 00:08:07 -05:00
Leon Liang
445c8b39de allow delete without refreshing page 2019-12-02 00:00:25 -05:00
Aditya Sankaran
6e8b7f410a saved liked posts 2019-12-01 15:55:53 -05:00
Aditya Sankaran
07a8f0b7bb userline frontend shows quoted posts 2019-11-30 18:23:46 -05:00
Aditya Sankaran
54cd1c44a7 edited userline database function 2019-11-30 18:11:33 -05:00
Aditya Sankaran
ca7f793d4c likeCount updating auto 2019-11-30 16:50:20 -05:00
Aditya Sankaran
a36212c23d quoting mblogs userline 2019-11-30 12:16:30 -05:00
Aditya Sankaran
b83eb0c897 saved states of post for each user 2019-11-29 20:18:51 -05:00
fee2225745 Disable or enable Direct Messages 2019-11-27 23:06:25 -05:00
0d8850c45d Comment out logging in fbAuth.js 2019-11-27 21:53:02 -05:00
f7ef0cb333 Fix DM message content overflowing 2019-11-27 21:52:14 -05:00
731e01c552 Comment out some lines in users.js that were throwing errors 2019-11-27 21:51:16 -05:00
asankaran35
0c9778949a Merge pull request #94 from ClaytonWWilson/engage_microblog
Engage microblog
2019-11-27 21:09:32 -05:00
asankaran35
1a2af4e9bb Merge branch 'master' into engage_microblog 2019-11-27 21:08:55 -05:00
Aditya Sankaran
c34f06f130 formatted feed and userline 2019-11-27 20:57:42 -05:00
3814377817 Display loading icon when the user logs in or signs up 2019-11-25 13:55:03 -05:00
Leon Liang
9fff6ed81c changed status code for follow/unfollow 2019-11-22 18:23:49 -05:00
445687cc54 Automatically display new Direct Messages 2019-11-22 18:21:52 -05:00
331509da7f Direct Messages sending DMs 2019-11-22 16:44:53 -05:00
Leon Liang
64cc9bd156 Merge pull request #91 from ClaytonWWilson/fix_profile
Fix profile
2019-11-21 20:21:24 -05:00
Leon Liang
6a78d74930 simplified backend get/remove topic function 2019-11-21 20:20:54 -05:00
Leon Liang
4e817c9647 integrated backend change, added pointer cursor 2019-11-21 20:09:47 -05:00
Leon Liang
7976110e2b modified function to add/delete topic only from user 2019-11-21 19:59:04 -05:00
Leon Liang
3da2449050 change topic display to user-specific topics 2019-11-21 18:10:44 -05:00
Leon Liang
607ea3fd55 Merge pull request #83 from ClaytonWWilson/edit-profile-linking
Changing profile page layout
2019-11-21 17:58:56 -05:00
Aditya Sankaran
e8110d643f finished quoting microblogs 2019-11-21 15:42:43 -05:00
e06cc614cb Dynamic front-end adding new DM channels 2019-11-20 20:48:49 -05:00
709df1492d Changed how back-end DMs worked 2019-11-20 20:32:11 -05:00
Leon Liang
c3091cc10a Merge pull request #90 from ClaytonWWilson/auto_complete
completed search page and redirect to user profile page
2019-11-19 22:31:52 -05:00
Leon Liang
81749c19ce completed search page and redirect to user profile page 2019-11-19 22:30:15 -05:00
Aditya Sankaran
1ccc195036 liking and unliking work 2019-11-19 21:09:07 -05:00
Leon Liang
0aaa9014b9 Merge pull request #88 from ClaytonWWilson/user_page
User page
2019-11-19 19:22:48 -05:00
3d9266778d Direct Messages can use redux for creating new DM channels 2019-11-19 19:04:25 -05:00
Leon Liang
2de3da928a added UI for follow and unfollow other user 2019-11-19 19:03:28 -05:00
297619cacb Tweaking DM back-end functions 2019-11-19 19:02:13 -05:00
Leon Liang
42c53fdbc4 Add profile image, topics for other user page 2019-11-19 15:56:39 -05:00
Leon Liang
c8aa1fd050 Added page to display other users' profile 2019-11-19 13:57:24 -05:00
a59c2feb4a Fix sorting so empty DM channels go to the bottom of the list 2019-11-19 01:30:00 -05:00
0f1cfe0393 Front-end layout mostly completed 2019-11-19 01:18:20 -05:00
63e917f54c Fixed the sorting of messages 2019-11-15 15:20:39 -05:00
2f5ec1c5ac Basic style for direct messages 2019-11-12 23:50:53 -05:00
19f8f70bf2 Fixing DMList errors 2019-11-08 18:48:00 -05:00
02197ee940 Sending Direct Messages 2019-11-08 17:54:56 -05:00
5507247a7f Create a new DM channel between two users 2019-11-08 11:42:46 -05:00
5560b6e13c Refactor DM enabled checking to make it re-usable 2019-11-06 01:01:50 -05:00
19d78596b5 Check for DMs enabled or disabled 2019-11-05 22:43:29 -05:00
9372a092ad Fix edit profile button link 2019-11-05 17:43:19 -05:00
7a6ac8499c fix merge 2019-11-05 17:38:11 -05:00
6149e15b35 Profile page kinda works on mobile 2019-11-05 17:35:16 -05:00
80670d054e Main layout of profile page 2019-11-05 17:19:28 -05:00
947e5b01a4 Converted tabs back to spaces 2019-11-05 17:16:34 -05:00
7cc8a3f11f Fixing up profile UI 2019-11-05 17:04:33 -05:00
7476833f0a Main layout of profile page 2019-11-05 16:32:16 -05:00
a2ed627f2b Back-end for getting all the DMs for a user 2019-11-04 13:21:47 -05:00
bbbfc4b750 Editprofile move button positions 2019-11-03 21:10:57 -05:00
38df4ef087 Added styles and spaced cards 2019-11-03 15:29:39 -05:00
2bd1c08c2c Writing_Microblogs to Material-UI and UI improvements 2019-11-03 15:17:14 -05:00
3fa4cd7033 Changing writing microblogs to Material-UI 2019-11-01 13:02:37 -04:00
ab07d45205 Fix loading on image upload, so it waits for new image 2019-11-01 10:12:54 -04:00
3c31db9bf5 Converted tabs back to spaces 2019-10-29 23:02:36 -04:00
c96c77cd9f Debugging upload issues 2019-10-29 15:00:21 -04:00
fb6c1e3d98 Image upload edit some return messages 2019-10-29 12:40:38 -04:00
3d875e2bde Fixing up profile UI 2019-10-28 23:25:12 -04:00
3001ec0b38 Merge branch 'master' into edit-profile-image-upload 2019-10-27 23:46:15 -04:00
e8a403f575 Delete old profile image 2019-10-27 23:43:35 -04:00
44d3450b10 Profile image upload frontend and backend finished 2019-10-27 18:06:47 -04:00
17 changed files with 977 additions and 1854 deletions

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, db } = require("../util/admin"); const admin = require("firebase-admin");
const { db } = require("../util/admin");
exports.putPost = (req, res) => { exports.putPost = (req, res) => {
const newPost = { const newPost = {
@@ -33,18 +33,6 @@ 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()
@@ -58,106 +46,6 @@ 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() {
@@ -172,17 +60,60 @@ exports.getAlert = (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) {
@@ -190,7 +121,6 @@ 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() {
@@ -207,23 +137,21 @@ exports.getOtherUsersPosts = (req, res) => {
exports.quoteWithPost = (req, res) => { exports.quoteWithPost = (req, res) => {
let quoteData; let quoteData;
const quoteDoc = admin const quoteDoc = admin.firestore().collection('quote').
.firestore() where('userHandle', '==', req.user.handle).
.collection("quote") where('quoteId', '==', req.params.postId).limit(1);
.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 postDoc.get()
.get() .then((doc) => {
.then(doc => { if(doc.exists) {
if (doc.exists) {
quoteData = doc.data(); quoteData = doc.data();
return quoteDoc.get(); return quoteDoc.get();
} else { }
return res.status(404).json({ error: "Post not found" }); else
{
return res.status(404).json({error: 'Post not found'});
} }
}) })
.then(data => { .then(data => {
@@ -273,23 +201,21 @@ exports.quoteWithPost = (req, res) => {
exports.quoteWithoutPost = (req, res) => { exports.quoteWithoutPost = (req, res) => {
let quoteData; let quoteData;
const quoteDoc = admin const quoteDoc = admin.firestore().collection('quote').
.firestore() where('userHandle', '==', req.user.handle).
.collection("quote") where('quoteId', '==', req.params.postId).limit(1);
.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 postDoc.get()
.get() .then((doc) => {
.then(doc => { if(doc.exists) {
if (doc.exists) {
quoteData = doc.data(); quoteData = doc.data();
return quoteDoc.get(); return quoteDoc.get();
} else { }
return res.status(404).json({ error: "Post not found" }); else
{
return res.status(404).json({error: 'Post not found'});
} }
}) })
.then(data => { .then(data => {
@@ -346,9 +272,7 @@ exports.checkforLikePost = (req, res) => {
.limit(1); .limit(1);
let result; let result;
likedPostDoc likedPostDoc.get().then(data => {
.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);
@@ -357,49 +281,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 return res.status(400).json({error: "This user has already liked this post"});
.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)
@@ -437,23 +361,24 @@ 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 return res.status(400).json({error: "This user hasn't liked this post yet"});
.status(400)
.json({ error: "This user hasn't liked this post yet" });
} }
let i; let i;
@@ -463,24 +388,25 @@ 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)
@@ -516,28 +442,32 @@ 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,41 +26,6 @@ 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

@@ -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,32 +239,25 @@ 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 ( if (dmRecipients === undefined || dmRecipients === null || dmRecipients.length === 0) {
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 db.doc(`/users/${dmRecipient}`).get()
.doc(`/users/${dmRecipient}`) .then((otherUserDocSnap) => {
.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() let otherUserDMRecipients = otherUserDocSnap.data().dmRecipients;
.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
@@ -279,29 +272,28 @@ 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 db.collection(`/dm/${dmRef.id}/messages`).listDocuments()
.collection(`/dm/${dmRef.id}/messages`) .then((docs) => {
.listDocuments() console.log("second")
.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);
@@ -309,8 +301,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);
}) })
@@ -318,17 +310,18 @@ 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
@@ -341,18 +334,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;
@@ -461,18 +454,17 @@ 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 user_query.get()
.get() .then((allUsers) => {
.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
}); });
}); });
@@ -565,7 +557,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 +569,6 @@ exports.getDirectMessages = (req, res) => {
* messageId: str * messageId: str
* } * }
* recipient: str * recipient: str
* hasDirectMessagesEnabled: bool
* recentMessage: str * recentMessage: str
* recentMessageTimestamp: ISOString * recentMessageTimestamp: ISOString
* } * }
@@ -586,9 +577,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 means 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) {
return; return;
} }
@@ -597,106 +588,90 @@ 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().then(dmQuerySnap => { messagesCollection.get()
dmQuerySnap.forEach(dmQueryDocSnap => { .then((dmQuerySnap) => {
dmQuerySnap.forEach((dmQueryDocSnap) => {
promises.push( promises.push(
dmQueryDocSnap.ref.get().then(messageData => { dmQueryDocSnap.ref.get()
.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 return (b.createdAt > a.createdAt) ? -1 : ((b.createdAt < a.createdAt) ? 1 : 0);
? -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) if (dms === undefined || dms === null || dms.length === 0) return res.status(200).json({data: null});
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( dmPromises.push(new Promise((resolve, reject) => {
new Promise((resolve, reject) => { dm // DM document reference
dm.get() // DM document reference .get()
.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).then(msgs => { getMessages(dm)
.then((msgs) => {
dmData.messages = msgs; dmData.messages = msgs;
dmData.recentMessage = dmData.recentMessage = msgs.length !== 0 ? msgs[msgs.length - 1].message : null;
msgs.length !== 0 ? msgs[msgs.length - 1].message : null; dmData.recentMessageTimestamp = msgs.length !== 0 ? msgs[msgs.length - 1].createdAt : 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({ return res.status(400).json({error: {
error: { message: "An error occurred when reading the DM document reference",
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
Promise.all(dmPromises) dmWaitPromise = 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 ( if (a.recentMessageTimestamp === null && b.recentMessageTimestamp === null) {
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) {
@@ -716,32 +691,15 @@ 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;
}
}) })
.data().dmEnabled === false .catch((err) => {
? false return res.status(500).json({error:{
: 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
@@ -750,44 +708,38 @@ 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}`) db.doc(`/users/${user}`).update({dmEnabled: enable})
.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 = result.message = "No user was sent in the request. The request should have a non-empty 'user' key.";
"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 ( if (doc.data().dmEnabled === true || doc.data().dmEnabled === null || doc.data().dmEnabled === undefined) {
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 = 400; result.code = 200;
result.message = `${username} has DMs disabled`; result.message = `${username} has DMs disabled`;
reject(result); reject(result);
} }
@@ -798,46 +750,42 @@ 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 ( if (dmList === null || dmList === undefined || dmRecipients === null || dmRecipients === undefined) {
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 userASnapshot.ref.set({dms:[], dmRecipients:[]}, {merge: true})
.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");
@@ -862,20 +810,17 @@ 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}`));
reject({
code: 400,
message: `You already have a DM with that user`
});
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.
@@ -921,10 +866,15 @@ 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
@@ -935,39 +885,36 @@ 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}`) db.doc(`/users/${username}`).get()
.get() .then((docSnap) => {
.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 return db.doc(`/users/${username}`).update({dms: dmList, dmRecipients});
.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
@@ -985,92 +932,66 @@ exports.sendDirectMessage = (req, res) => {
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
message, message,
messageId: null messageId: null
};
db.doc(`/users/${recipient}`)
.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}`) db.doc(`/users/${creator}`).get()
.get() .then((userDoc) => {
.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) { if (dmList === null || dmList === undefined) return res.status(400).json({error: `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.`
});
}
let dmRefPromises = []; let dmRefPromises = [];
dmList.forEach(dmRef => { dmList.forEach((dmRef) => {
dmRefPromises.push( dmRefPromises.push(
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
dmRef dmRef.get()
.get() .then((dmDoc) => {
.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( console.log(`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 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
@@ -1081,8 +1002,7 @@ 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) if (creator === recipient) return res.status(400).json({error: "You can't DM yourself"});
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);
@@ -1091,63 +1011,56 @@ 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( let updateCreatorPromise = addDirectMessageToUser(creator, recipient, dmDocRef);
creator,
recipient,
dmDocRef
);
// Add the DM reference to the recipient // Add the DM reference to the recipient
let updateRecipientPromise = addDirectMessageToUser( let updateRecipientPromise = addDirectMessageToUser(recipient, creator, dmDocRef);
recipient,
creator,
dmDocRef
);
// Wait for all promises // Wait for all promises
return Promise.all([ return Promise.all([dmDocPromise, updateCreatorPromise, updateRecipientPromise]);
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
@@ -1156,19 +1069,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}`)
@@ -1192,13 +1105,7 @@ 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;
const struct = { new_following.push(req.body.following);
handle: req.body.following,
topics: ["Admin"]
};
new_following
? new_following.push(struct)
: (new_following = req.body.following);
// add stuff // add stuff
userRef userRef
@@ -1211,11 +1118,8 @@ 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) => {
@@ -1242,32 +1146,25 @@ exports.uploadProfileImage = (req, res) => {
let imageFileName; let imageFileName;
let imageToBeUploaded = {}; let imageToBeUploaded = {};
let oldImageFileName = req.userData.imageUrl let oldImageFileName = req.userData.imageUrl ? req.userData.imageUrl.split("/o/")[1].split("?alt")[0] : null;
? 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( imageFileName = `${Math.round(Math.random() * 100000000000)}.${imageExtension}`; // Get a random filename
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 admin.storage().bucket(config.storageBucket).upload(imageToBeUploaded.filepath, {
.storage()
.bucket(config.storageBucket)
.upload(imageToBeUploaded.filepath, {
resumable: false, resumable: false,
metadata: { metadata: {
metadata: { metadata: {
@@ -1283,33 +1180,24 @@ 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 admin.storage().bucket(config.storageBucket).file(oldImageFileName).delete()
.storage()
.bucket(config.storageBucket)
.file(oldImageFileName)
.delete()
.then(() => { .then(() => {
return res return res.status(201).json({ message: "Image uploaded successfully1"});
.status(201)
.json({ message: "Image uploaded successfully1" });
}) })
.catch(err => { .catch((err) => {
console.log(err); console.log(err);
return res return res.status(201).json({ message: "Image uploaded successfully2"});
.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 return res.status(201).json({ message: "Image uploaded successfully3"});
.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);
@@ -1365,7 +1253,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 = [];
@@ -1374,7 +1262,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.handle === `${req.body.unfollow}`) { if (follower === `${req.body.unfollow}`) {
new_following.splice(index, 1); new_following.splice(index, 1);
} }
}); });

View File

@@ -100,33 +100,18 @@ 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);
@@ -140,8 +125,6 @@ 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 *
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/
@@ -149,8 +132,7 @@ const {
putTopic, putTopic,
getAllTopics, getAllTopics,
deleteTopic, deleteTopic,
getUserTopics, getUserTopics
putNewTopic
} = require("./handlers/topic"); } = require("./handlers/topic");
// add topic to database // add topic to database
@@ -165,6 +147,4 @@ 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);

427
package-lock.json generated
View File

@@ -1,428 +1,3 @@
{ {
"requires": true, "lockfileVersion": 1
"lockfileVersion": 1,
"dependencies": {
"accepts": {
"version": "1.3.7",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz",
"integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==",
"requires": {
"mime-types": "~2.1.24",
"negotiator": "0.6.2"
}
},
"array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI="
},
"axios": {
"version": "0.19.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.19.0.tgz",
"integrity": "sha512-1uvKqKQta3KBxIz14F2v06AEHZ/dIoeKfbTRkK1E5oqjDnuEerLmYTgJB5AiQZHJcljpg1TuRzdjDR06qNk0DQ==",
"requires": {
"follow-redirects": "1.5.10",
"is-buffer": "^2.0.2"
}
},
"body-parser": {
"version": "1.19.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz",
"integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==",
"requires": {
"bytes": "3.1.0",
"content-type": "~1.0.4",
"debug": "2.6.9",
"depd": "~1.1.2",
"http-errors": "1.7.2",
"iconv-lite": "0.4.24",
"on-finished": "~2.3.0",
"qs": "6.7.0",
"raw-body": "2.4.0",
"type-is": "~1.6.17"
}
},
"bytes": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz",
"integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg=="
},
"content-disposition": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz",
"integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==",
"requires": {
"safe-buffer": "5.1.2"
}
},
"content-type": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz",
"integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA=="
},
"cookie": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz",
"integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg=="
},
"cookie-signature": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
},
"cors": {
"version": "2.8.5",
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
"integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
"requires": {
"object-assign": "^4",
"vary": "^1"
}
},
"debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"requires": {
"ms": "2.0.0"
}
},
"depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
"integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak="
},
"destroy": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
"integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
},
"ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0="
},
"encodeurl": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
"integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k="
},
"escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
},
"eslint-plugin-promise": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/eslint-plugin-promise/-/eslint-plugin-promise-4.2.1.tgz",
"integrity": "sha512-VoM09vT7bfA7D+upt+FjeBO5eHIJQBUWki1aPvB+vbNiHS3+oGIJGIeyBtKQTME6UPXXy3vV07OL1tHd3ANuDw=="
},
"etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc="
},
"express": {
"version": "4.17.1",
"resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz",
"integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==",
"requires": {
"accepts": "~1.3.7",
"array-flatten": "1.1.1",
"body-parser": "1.19.0",
"content-disposition": "0.5.3",
"content-type": "~1.0.4",
"cookie": "0.4.0",
"cookie-signature": "1.0.6",
"debug": "2.6.9",
"depd": "~1.1.2",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "~1.1.2",
"fresh": "0.5.2",
"merge-descriptors": "1.0.1",
"methods": "~1.1.2",
"on-finished": "~2.3.0",
"parseurl": "~1.3.3",
"path-to-regexp": "0.1.7",
"proxy-addr": "~2.0.5",
"qs": "6.7.0",
"range-parser": "~1.2.1",
"safe-buffer": "5.1.2",
"send": "0.17.1",
"serve-static": "1.14.1",
"setprototypeof": "1.1.1",
"statuses": "~1.5.0",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
}
},
"finalhandler": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz",
"integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==",
"requires": {
"debug": "2.6.9",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"on-finished": "~2.3.0",
"parseurl": "~1.3.3",
"statuses": "~1.5.0",
"unpipe": "~1.0.0"
}
},
"follow-redirects": {
"version": "1.5.10",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz",
"integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==",
"requires": {
"debug": "=3.1.0"
},
"dependencies": {
"debug": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
"integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
"requires": {
"ms": "2.0.0"
}
}
}
},
"forwarded": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz",
"integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ="
},
"fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac="
},
"http-errors": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz",
"integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==",
"requires": {
"depd": "~1.1.2",
"inherits": "2.0.3",
"setprototypeof": "1.1.1",
"statuses": ">= 1.5.0 < 2",
"toidentifier": "1.0.0"
}
},
"iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
"requires": {
"safer-buffer": ">= 2.1.2 < 3"
}
},
"inherits": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
"integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4="
},
"ipaddr.js": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.0.tgz",
"integrity": "sha512-M4Sjn6N/+O6/IXSJseKqHoFc+5FdGJ22sXqnjTpdZweHK64MzEPAyQZyEU3R/KRv2GLoa7nNtg/C2Ev6m7z+eA=="
},
"is-buffer": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.4.tgz",
"integrity": "sha512-Kq1rokWXOPXWuaMAqZiJW4XxsmD9zGx9q4aePabbn3qCRGedtH7Cm+zV8WETitMfu1wdh+Rvd6w5egwSngUX2A=="
},
"jwt-decode": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-2.2.0.tgz",
"integrity": "sha1-fYa9VmefWM5qhHBKZX3TkruoGnk="
},
"media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g="
},
"merge-descriptors": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz",
"integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E="
},
"methods": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
"integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4="
},
"mime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg=="
},
"mime-db": {
"version": "1.40.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.40.0.tgz",
"integrity": "sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA=="
},
"mime-types": {
"version": "2.1.24",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.24.tgz",
"integrity": "sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ==",
"requires": {
"mime-db": "1.40.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"negotiator": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz",
"integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw=="
},
"object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM="
},
"on-finished": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
"integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=",
"requires": {
"ee-first": "1.1.1"
}
},
"parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="
},
"path-to-regexp": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
"integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w="
},
"proxy-addr": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.5.tgz",
"integrity": "sha512-t/7RxHXPH6cJtP0pRG6smSr9QJidhB+3kXu0KgXnbGYMgzEnUxRQ4/LDdfOwZEMyIh3/xHb8PX3t+lfL9z+YVQ==",
"requires": {
"forwarded": "~0.1.2",
"ipaddr.js": "1.9.0"
}
},
"qs": {
"version": "6.7.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz",
"integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ=="
},
"range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="
},
"raw-body": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz",
"integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==",
"requires": {
"bytes": "3.1.0",
"http-errors": "1.7.2",
"iconv-lite": "0.4.24",
"unpipe": "1.0.0"
}
},
"safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"send": {
"version": "0.17.1",
"resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz",
"integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==",
"requires": {
"debug": "2.6.9",
"depd": "~1.1.2",
"destroy": "~1.0.4",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "0.5.2",
"http-errors": "~1.7.2",
"mime": "1.6.0",
"ms": "2.1.1",
"on-finished": "~2.3.0",
"range-parser": "~1.2.1",
"statuses": "~1.5.0"
},
"dependencies": {
"ms": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz",
"integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg=="
}
}
},
"serve-static": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz",
"integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==",
"requires": {
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "0.17.1"
}
},
"setprototypeof": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
"integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw=="
},
"statuses": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
"integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow="
},
"toidentifier": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz",
"integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw=="
},
"type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"requires": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
}
},
"unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw="
},
"utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM="
},
"vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw="
}
}
} }

View File

@@ -2417,11 +2417,6 @@
"resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz",
"integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs=" "integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs="
}, },
"dayjs": {
"version": "1.8.17",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.8.17.tgz",
"integrity": "sha512-47VY/htqYqr9GHd7HW/h56PpQzRBSJcxIQFwqL3P20bMF/3az5c3PWdVY3LmPXFl6cQCYHL7c79b9ov+2bOBbw=="
},
"debug": { "debug": {
"version": "2.6.9", "version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
@@ -9792,11 +9787,6 @@
"resolved": "https://registry.npmjs.org/uid-number/-/uid-number-0.0.6.tgz", "resolved": "https://registry.npmjs.org/uid-number/-/uid-number-0.0.6.tgz",
"integrity": "sha1-DqEOgDXo61uOREnwbaHHMGY7qoE=" "integrity": "sha1-DqEOgDXo61uOREnwbaHHMGY7qoE="
}, },
"underscore": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/underscore/-/underscore-1.9.1.tgz",
"integrity": "sha512-5/4etnCkd9c8gwgowi5/om/mYO5ajCaOgdzj/oW+0eQV9WxKBDZw5+ycmKmeaTXjInS/W0BzpGLo2xR2aBwZdg=="
},
"union-value": { "union-value": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz", "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz",

View File

@@ -45,5 +45,5 @@
"last 1 safari version" "last 1 safari version"
] ]
}, },
"proxy": "https://us-central1-twistter-e4649.cloudfunctions.net/api" "proxy": "http://localhost:5001/twistter-e4649/us-central1/api"
} }

View File

@@ -0,0 +1,20 @@
import { createGlobalStyle } from 'styled-components';
export const GlobalStyles = createGlobalStyle`
*,
*::after,
*::before {
box-sizing: border-box;
}
body {
align-items: center;
background: ${({ theme }) => theme.body};
color: ${({ theme }) => theme.text};
display: flex;
flex-direction: column;
justify-content: center;
height: 100vh;
margin: 0;
padding: 0;
}

View File

@@ -0,0 +1,14 @@
export const lightTheme = {
body: '#E2E2E2',
text: '#363537',
toggleBorder: '#FFF',
gradient: 'linear-gradient(#39598A, #79D7ED)',
}
export const darkTheme = {
body: '#363537',
text: '#FAFAFA',
toggleBorder: '#6B8096',
gradient: 'linear-gradient(#091236, #1E215D)',
}

View File

@@ -8,7 +8,6 @@ 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: {
@@ -22,13 +21,6 @@ const styles = {
}, },
textField: { textField: {
marginBottom: 15 marginBottom: 15
},
progress: {
position: "absolute"
},
button: {
positon: "relative",
marginBottom: 30
} }
} }
@@ -39,8 +31,7 @@ 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);
@@ -65,15 +56,11 @@ 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" }
}; };
let postPromise = axios 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!");
@@ -84,35 +71,20 @@ class Writing_Microblogs extends Component {
console.error(err); console.error(err);
}); });
console.log(postData.microBlogTopics); console.log(postData.microBlogTopics);
// let topicPromises = []; postData.microBlogTopics.forEach(topic => {
// postData.microBlogTopics.forEach(topic => { axios
// topicPromises.push(axios .post("/putTopic", {
// .post("/putTopic", { following: topic
// following: topic })
// }) .then(res => {
// .then(res => { console.log(res.data);
// console.log(res.data); })
// }) .catch(err => {
// .catch(err => { console.error(err);
// console.error(err);
// })
// )
// });
event.preventDefault();
// topicPromises.push(postPromise);
Promise.all([postPromise])
.then(() => {
this.setState({
value: "",
title: "",
characterCount: 250,
topics: "",
loading: false
}); });
}) });
.catch((error) => { event.preventDefault();
console.log(error); this.setState({ value: "", title: "", characterCount: 250, topics: "" });
})
} }
handleChangeforPost(event) { handleChangeforPost(event) {
@@ -177,14 +149,12 @@ class Writing_Microblogs extends Component {
autoComplete='off' autoComplete='off'
/> />
<Button <Button
className={classes.button}
onClick={this.handleSubmit} onClick={this.handleSubmit}
disabled={this.state.loading} // disabled={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

@@ -0,0 +1,23 @@
import React from 'react'
import { func, string } from 'prop-types';
import styled from 'styled-components';
// Import a couple of SVG files we'll use in the design: https://www.flaticon.com
import { ReactComponent as MoonIcon } from 'icons/moon.svg';
import { ReactComponent as SunIcon } from 'icons/sun.svg';
const Toggle = ({ theme, toggleTheme }) => {
const isLight = theme === 'light';
return (
<button onClick={toggleTheme} >
<SunIcon />
<MoonIcon />
</button>
);
};
Toggle.propTypes = {
theme: string.isRequired,
toggleTheme: func.isRequired,
}
export default Toggle;

View File

@@ -6,134 +6,78 @@ 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() {
this.setState({ loading: true });
let userPromise = axios
.get("/user")
.then(res => {
console.log(res.data.credentials.following);
let list = [];
res.data.credentials.following.forEach(element => {
list.push(element.handle);
});
this.setState({
following: list,
topics: res.data.credentials.followedTopics
});
})
.catch(err => console.log(err));
let allPosts; componentDidMount() {
let postPromise = axios axios
.get("/getallPosts") .get("/getallPosts")
.then(res => { .then(res => {
// console.log(res.data); // 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({ this.setState({
posts: allPosts posts: res.data
}); });
}) })
.catch(err => console.log(err)); .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 let postId = event.target.dataset.key ? event.target.dataset.key : event.target.parentNode.dataset.key;
? event.target.dataset.key console.log(postId)
: 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));
@@ -141,21 +85,14 @@ class Home extends Component {
} }
render() { render() {
const {
UI: { loading }
} = this.props;
let authenticated = this.props.user.authenticated;
let { classes } = this.props;
let username = this.props.user.credentials.handle;
console.log(username);
var hiddenBool = true;
if (username === "Admin") {
hiddenBool = false;
}
console.log(hiddenBool); const { UI:{ loading } } = this.props;
let postMarkup = this.state.posts ? ( this.state.following === undefined || this.state.following === null ? <Typography>You aren't following anybody right now</Typography> : let authenticated = this.props.user.authenticated;
this.state.posts.map(post => !post.hidden && this.state.following && (this.state.following.includes(post.userHandle) || post.userHandle === "Admin") ? ( let {classes} = this.props;
let username = this.props.user.credentials.handle;
let postMarkup = this.state.posts ? (
this.state.posts.map(post =>
<Card className={classes.card} key={post.postId}> <Card className={classes.card} key={post.postId}>
<CardContent> <CardContent>
<Typography> <Typography>
@@ -176,19 +113,8 @@ 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.join(", ")}</Typography> <Typography variant="body2"><b>Topics:</b> {post.microBlogTopics}</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
@@ -204,25 +130,15 @@ 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 authenticated ? ( return (
this.state.loading ? ( authenticated ? (
<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 />
@@ -231,43 +147,34 @@ class Home extends Component {
{postMarkup} {postMarkup}
</Grid> </Grid>
</Grid> </Grid>
) ) : loading ?
) : loading ? ( (<CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress>)
<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>
<br /> <br/>
<form action="./login"> <form action="./login">
<button className="authButtons login">Sign in</button> <button className="authButtons login">Sign in</button>
</form> </form>
</div> </div>
</div> </div>
); ));
} }
} }
@@ -278,7 +185,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);
@@ -288,17 +195,19 @@ 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 axios.post(`/quoteWithoutPost/${this.props.microblog}`, post, headers)
.post(`/quoteWithoutPost/${this.props.microblog}`, post, headers) .then((res) => {
.then(res => {
console.log(res.data); console.log(res.data);
}) })
.catch(err => { .catch(err => {
console.error(err); console.error(err);
}); });
event.preventDefault(); event.preventDefault();
@@ -325,17 +234,18 @@ 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 axios.post(`/quoteWithPost/${this.props.microblog}`, quotedPost, headers)
.post(`/quoteWithPost/${this.props.microblog}`, quotedPost, headers) .then((res) => {
.then(res => {
console.log(res.data); console.log(res.data);
}) })
.catch(err => { .catch(err => {
console.error(err); console.error(err);
}); });
event.preventDefault(); event.preventDefault();
@@ -345,28 +255,13 @@ class Quote extends Component {
render() { render() {
return ( return (
<div> <div>
<Button <Button variant="outlined" color="primary" onClick={this.handleOpenModal}>Quote with Post</Button>
variant="outlined"
color="primary"
onClick={this.handleOpenModal}
>
Quote with Post
</Button>
<ReactModal <ReactModal
isOpen={this.state.showModal} isOpen={this.state.showModal}
style={{ style={{content: {height: "50%", width: "25%", marginTop: "auto", marginLeft: "auto", marginRight: "auto", marginBottom : "auto"}}}
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"}}>
{/* <textarea {/* <textarea
value={this.state.value} value={this.state.value}
required required
@@ -381,7 +276,7 @@ class Quote extends Component {
rows={20} rows={20}
/> */} /> */}
<TextField <TextField
style={{ width: 300 }} style={{width: 300}}
value={this.state.value} value={this.state.value}
label="Write Quoted Post here..." label="Write Quoted Post here..."
required required
@@ -396,93 +291,85 @@ 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 <Button variant="outlined" color="primary" onClick={this.handleSubmit}>Share Quoted Post</Button>
variant="outlined"
color="primary" <Button variant="outlined" color="primary" onClick={this.handleCloseModal}>Cancel</Button>
onClick={this.handleSubmit}
>
Share Quoted Post
</Button>
<Button
variant="outlined"
color="primary"
onClick={this.handleCloseModal}
>
Cancel
</Button>
</form> </form>
</div> </div>
</ReactModal> </ReactModal>
<Button <Button variant="outlined" color="primary" onClick={this.handleSubmitWithoutPost}>Quote without Post</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: like: localStorage.getItem(this.props.microBlog + this.props.name) === "false"
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( localStorage.setItem(this.props.microBlog + this.props.name, this.state.like.toString())
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 axios.get(`/like/${this.props.microBlog}`)
.get(`/like/${this.props.microBlog}`) .then((res) => {
.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}`)
.then(res => {
console.log(res.data);
}) })
.catch(err => {
console.log(err);
});
} }
else
{
this.setState(() => {
return {num: this.state.num - 1}
});
axios.get(`/unlike/${this.props.microBlog}`)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
})
}
} }
/* componentDidMount() { /* componentDidMount() {
@@ -505,28 +392,31 @@ class Like extends Component {
} */ } */
render() { render() {
const label = this.state.like ? "Unlike" : "Like";
return ( const label = this.state.like ? 'Unlike' : 'Like'
return(
<div> <div>
<Typography variant="body2" color={"textSecondary"}> <Typography variant="body2" color={"textSecondary"}>Likes {this.state.num}</Typography>
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,
@@ -535,17 +425,16 @@ 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,10 +83,6 @@ const styles = {
wordBreak: "break-all", wordBreak: "break-all",
color: 'black' color: 'black'
}, },
dmRecentMessageDisabled: {
wordBreak: "break-all",
color: 'red'
},
dmListItemContainer: { dmListItemContainer: {
height: 100 height: 100
}, },
@@ -430,19 +426,13 @@ 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'
: :
@@ -558,8 +548,8 @@ export class directMessages extends Component {
> >
Create Create
{creatingDirectMessage && {creatingDirectMessage &&
// Won't accept classes style for some reason
<CircularProgress size={30} style={{position: "absolute"}}/> <CircularProgress size={30} style={{position: "absolute"}}/>
// Won't accept classes style for some reason
} }
</Button> </Button>
</Grid> </Grid>
@@ -607,16 +597,7 @@ export class directMessages extends Component {
multiline multiline
rows={2} rows={2}
margin="dense" margin="dense"
disabled={!this.state.selectedChannel.hasDirectMessagesEnabled} value={this.state.drafts[this.state.selectedChannel.dmId] ? this.state.drafts[this.state.selectedChannel.dmId] : ""}
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,7 +22,6 @@ 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";
@@ -78,9 +77,7 @@ class user extends Component {
user: null, user: null,
following: null, following: null,
posts: null, posts: null,
myTopics: null, myTopics: null
followingList: null,
loading: false
}; };
} }
@@ -93,8 +90,7 @@ 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) {
@@ -117,27 +113,8 @@ 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 }); axios
let otherUserPromise = axios
.post("/getUserDetails", { .post("/getUserDetails", {
handle: this.state.profile handle: this.state.profile
}) })
@@ -149,26 +126,19 @@ class user extends Component {
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
let userPromise = axios 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: fol, following: res.data.credentials.following.includes(
myTopics: list this.state.profile
),
myTopics: res.data.credentials.followedTopics
}); });
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
let posts = axios axios
.post("/getOtherUsersPosts", { .post("/getOtherUsersPosts", {
handle: this.state.profile handle: this.state.profile
}) })
@@ -179,44 +149,6 @@ 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() {
@@ -245,8 +177,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 =>
@@ -254,20 +186,16 @@ class user extends Component {
this.state.myTopics.includes(topic) ? ( this.state.myTopics.includes(topic) ? (
<MyChip <MyChip
label={topic} label={topic}
key={{ topic }.id} key={{ topic }.topic.id}
onDelete onDelete
deleteIcon={<DoneIcon />} deleteIcon={<DoneIcon />}
/> />
) : this.state.following ? ( ) : (
<MyChip <MyChip
label={topic} label={topic}
key={{ topic }.id} key={{ topic }.topic.id}
color="secondary" color="secondary"
clickable
onClick={key => this.handleAdd(topic)}
/> />
) : (
<MyChip label={topic} key={{ topic }.id} color="secondary" />
) )
) : ( ) : (
<p></p> <p></p>
@@ -283,10 +211,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} key={post.postId} data-key={post.postId}> <Card className={classes.card}>
<CardContent> <CardContent>
<Typography> <Typography>
{this.state.imageUrl ? ( {this.state.imageUrl ? (
@@ -295,11 +223,11 @@ class user extends Component {
<img src={noImage} height="50" width="50" /> <img src={noImage} height="50" width="50" />
)} )}
</Typography> </Typography>
<Typography variant="h4"> <Typography variant="h7">
<b>{post.userHandle}</b> <b>{post.userHandle}</b>
</Typography> </Typography>
<Typography variant="body2" color={"textSecondary"}> <Typography variant="body2" color={"textSecondary"}>
{this.formatDate(post.createdAt)} {post.createdAt}
</Typography> </Typography>
<br /> <br />
@@ -312,7 +240,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.join(", ")} <b>Topics:</b> {post.microBlogTopics}
</Typography> </Typography>
<br /> <br />
<Typography variant="body2" color={"textSecondary"}> <Typography variant="body2" color={"textSecondary"}>
@@ -325,13 +253,8 @@ class user extends Component {
<p>Posts</p> <p>Posts</p>
); );
return this.state.loading ? ( return (
<CircularProgress <Grid container spacing={24}>
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,7 +13,6 @@ 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";
@@ -77,8 +76,7 @@ class user extends Component {
profile: null, profile: null,
imageUrl: null, imageUrl: null,
topics: null, topics: null,
newTopic: "", newTopic: ""
loading: false
}; };
} }
@@ -129,8 +127,7 @@ class user extends Component {
} }
componentDidMount() { componentDidMount() {
this.setState({loading: true}) axios
let userPromise = axios
.get("/user") .get("/user")
.then(res => { .then(res => {
this.setState({ this.setState({
@@ -144,7 +141,7 @@ class user extends Component {
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
let postsPromise = axios axios
.get("/getallPostsforUser") .get("/getallPostsforUser")
.then(res => { .then(res => {
// console.log(res.data); // console.log(res.data);
@@ -153,14 +150,6 @@ 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) {
@@ -230,7 +219,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"}>
{this.formatDate(post.createdAt) } {post.createdAt}
</Typography> </Typography>
<br /> <br />
@@ -243,7 +232,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.join(", ")} <b>Topics:</b> {post.microBlogTopics}
</Typography> </Typography>
<br /> <br />
<Typography variant="body2" color={"textSecondary"}> <Typography variant="body2" color={"textSecondary"}>
@@ -269,17 +258,7 @@ 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">
@@ -287,7 +266,6 @@ 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,6 +142,5 @@ export const sendDirectMessage = (user, message) => (dispatch) => {
sendDirectMessage: err.response.data sendDirectMessage: err.response.data
} }
}) })
dispatch({type: SET_NOT_LOADING_UI_4});
}) })
} }

View File

@@ -36,7 +36,6 @@ 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)
@@ -58,7 +57,6 @@ 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)