Compare commits

...

95 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
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
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
3d9266778d Direct Messages can use redux for creating new DM channels 2019-11-19 19:04:25 -05:00
297619cacb Tweaking DM back-end functions 2019-11-19 19:02:13 -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
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
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
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
30 changed files with 3374 additions and 1002 deletions

View File

@@ -1,78 +1,145 @@
/* eslint-disable prefer-arrow-callback */
/* eslint-disable promise/always-return */
const admin = require('firebase-admin');
const { db } = require('../util/admin');
const admin = require("firebase-admin");
const { db } = require("../util/admin");
exports.putPost = (req, res) => {
const newPost = {
body: req.body.body,
userHandle: req.user.handle,
userImage: req.body.userImage,
userID: req.user.uid,
microBlogTitle: req.body.microBlogTitle,
createdAt: new Date().toISOString(),
likeCount: 0,
commentCount: 0,
microBlogTopics: req.body.microBlogTopics
};
const newPost = {
body: req.body.body,
userHandle: req.user.handle,
userImage: req.body.userImage,
userID: req.user.uid,
microBlogTitle: req.body.microBlogTitle,
createdAt: new Date().toISOString(),
likeCount: 0,
commentCount: 0,
microBlogTopics: req.body.microBlogTopics,
quoteBody: null
};
admin.firestore().collection('posts').add(newPost)
.then((doc) => {
doc.update({postId: doc.id})
const resPost = newPost;
resPost.postId = doc.id;
return res.status(200).json(resPost);
admin
.firestore()
.collection("posts")
.add(newPost)
.then(doc => {
doc.update({ postId: doc.id });
const resPost = newPost;
resPost.postId = doc.id;
return res.status(200).json(resPost);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: 'something went wrong'});
.catch(err => {
console.error(err);
return res.status(500).json({ error: "something went wrong" });
});
};
exports.getallPostsforUser = (req, res) => {
var post_query = admin.firestore().collection("posts").where("userHandle", "==", req.user.handle);
post_query.get()
var post_query = admin
.firestore()
.collection("posts")
.where("userHandle", "==", req.user.handle);
post_query
.get()
.then(function(myPosts) {
let posts = [];
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
return res.status(200).json(posts);
let posts = [];
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
return res.status(200).json(posts);
})
.then(function() {
return res.status(200).json("Successfully retrieved all user's posts from database.");
return res
.status(200)
.json("Successfully retrieved all user's posts from database.");
})
.catch(function(err) {
return res.status(500).json("Failed to retrieve user's posts from database.", err);
return res
.status(500)
.json("Failed to retrieve user's posts from database.", err);
});
};
exports.getallPosts = (req, res) => {
var post_query = admin.firestore().collection("posts");
post_query.get()
.then(function(allPosts) {
let posts = [];
allPosts.forEach(function(doc) {
posts.push(doc.data());
let posts = [];
let users = {};
// Get all the posts
var postsPromise = new Promise((resolve, reject) => {
db.collection("posts").get()
.then((allPosts) => {
allPosts.forEach((post) => {
posts.push(post.data());
});
return res.status(200).json(posts);
resolve();
})
.catch((error) => {
reject(error);
})
});
// Get all users
var usersPromise = new Promise((resolve, reject) => {
db.collection("users").get()
.then((allUsers) => {
allUsers.forEach((user) => {
users[user.data().handle] = user.data();
})
resolve();
})
.catch((error) => {
reject(error);
})
});
// Wait for the two promises
Promise.all([postsPromise, usersPromise])
.then(() => {
let newPosts = []
// Add the image url of the person who made the post to all of the post objects
posts.forEach((post) => {
post.profileImage = users[post.userHandle].imageUrl ? users[post.userHandle].imageUrl : null;
newPosts.push(post);
});
return res.status(200).json(newPosts);
})
.catch((error) => {
return res.status(500).json({error});
})
};
exports.getOtherUsersPosts = (req, res) => {
var post_query = admin
.firestore()
.collection("posts")
.where("userHandle", "==", req.body.handle);
post_query
.get()
.then(function(myPosts) {
let posts = [];
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
return res.status(200).json(posts);
})
.then(function() {
return res.status(200).json("Successfully retrieved every post from database.");
return res
.status(200)
.json("Successfully retrieved all user's posts from database.");
})
.catch(function(err) {
return res.status(500).json("Failed to retrieve posts from database.", err);
return res
.status(500)
.json("Failed to retrieve user's posts from database.", err);
});
};
exports.quoteWithPost = (req, res) => {
let quoteData;
const quoteDoc = admin.firestore().collection('quote').
where('userHandle', '==', req.user.handle).
where('postId', '==', req.params.postId).limit(1);
where('quoteId', '==', req.params.postId).limit(1);
const postDoc = db.doc(`/posts/${req.params.postId}`);
@@ -87,39 +154,56 @@ exports.quoteWithPost = (req, res) => {
return res.status(404).json({error: 'Post not found'});
}
})
.then((data) => {
if(data.empty) {
return admin.firestore().collection('quote').add({
postId : req.params.postId,
userHandle : req.user.handle,
quotePost : req.body.quotePost
})
.then(() => {
return admin.firestore().collection('posts').add({
quoteData,
quoteUser : req.user.handle,
quotePost : req.body.quotePost,
quotedAt : new Date().toISOString()
})
})
}
else {
return res.status(400).json({ error: 'Post has already been quoted.' });
}
})
.catch((err) => {
return res.status(500).json({error: err});
.then(data => {
if (data.empty) {
return admin
.firestore()
.collection("quote")
.add({
quoteId: req.params.postId,
userHandle: req.user.handle,
quoteBody: req.body.quoteBody
})
.then(() => {
const post = {
body: quoteData.body,
userHandle: req.user.handle,
quoteBody: req.body.quoteBody,
createdAt: new Date().toISOString(),
userImage: req.body.userImage,
likeCount: 0,
commentCount: 0,
userID: req.user.uid,
microBlogTitle: quoteData.microBlogTitle,
microBlogTopics: quoteData.microBlogTopics,
quoteId: req.params.postId
};
return admin
.firestore()
.collection("posts")
.add(post)
.then(doc => {
doc.update({ postId: doc.id });
const resPost = post;
resPost.postId = doc.id;
return res.status(200).json(resPost);
});
});
} else {
return res.status(400).json({ error: "Post has already been quoted." });
}
})
}
.catch(err => {
return res.status(500).json({ error: err });
});
};
exports.quoteWithoutPost = (req, res) => {
let quoteData;
const quoteDoc = admin.firestore().collection('quote').
where('userHandle', '==', req.user.handle).
where('postId', '==', req.params.postId).limit(1);
where('quoteId', '==', req.params.postId).limit(1);
const postDoc = db.doc(`/posts/${req.params.postId}`);
@@ -134,112 +218,256 @@ exports.quoteWithoutPost = (req, res) => {
return res.status(404).json({error: 'Post not found'});
}
})
.then((data) => {
if(data.empty) {
return admin.firestore().collection('quote').add({
postId : req.params.postId,
userHandle : req.user.handle,
})
.then(() => {
return admin.firestore().collection('posts').add({
quoteData,
quoteUser : req.user.handle,
quotedAt : new Date().toISOString()
})
})
}
else {
return res.status(400).json({ error: 'Post has already been quoted.' });
.then(data => {
if (data.empty) {
return admin
.firestore()
.collection("quote")
.add({
quoteId: req.params.postId,
userHandle: req.user.handle,
quoteBody: null
})
.then(() => {
const post = {
userHandle: req.user.handle,
body: quoteData.body,
quoteBody: null,
createdAt: new Date().toISOString(),
likeCount: 0,
commentCount: 0,
userID: req.user.uid,
userImage: req.body.userImage,
microBlogTitle: quoteData.microBlogTitle,
microBlogTopics: quoteData.microBlogTopics,
quoteId: req.params.postId
};
return admin
.firestore()
.collection("posts")
.add(post)
.then(doc => {
doc.update({ postId: doc.id });
const resPost = post;
resPost.postId = doc.id;
return res.status(200).json(resPost);
});
});
} else {
return res.status(400).json({ error: "Post has already been quoted." });
}
})
.catch((err) => {
return res.status(500).json({error: 'Something is wrong'});
.catch(err => {
// return res.status(500).json({ error: "Something is wrong" });
return res.status(500).json({ error: err });
});
};
})
}
exports.checkforLikePost = (req, res) => {
const likedPostDoc = admin
.firestore()
.collection("likes")
.where("userHandle", "==", req.user.handle)
.where("postId", "==", req.params.postId)
.limit(1);
let result;
likedPostDoc.get().then(data => {
if (data.empty) {
result = false;
return res.status(200).json(result);
} else {
result = true;
return res.status(200).json(result);
}
})
.catch((err) => {
console.log(err);
return res.status(500).json({error: err});
})
};
exports.likePost = (req, res) => {
let postData;
const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
.where('postId', '==', req.params.postId).limit(1);
const postDoc = db.doc(`/posts/${req.params.postId}`);
const postId = req.params.postId;
let likedPostDoc;
db.doc(`/users/${req.userData.handle}`)
.get()
.then((userDoc) => {
let likes = userDoc.data().likes;
if (likes === undefined || likes === null) {
likes = [];
}
postDoc.get()
.then((doc) => {
if(doc.exists) {
postData = doc.data();
return likeDoc.get();
}
else
{
return res.status(404).json({error: 'Post not found'});
}
})
.then((data) => {
if (data.empty) {
return admin.firestore().collection('likes').add({
postId : req.params.postId,
userHandle: req.user.handle
if (likes.includes(postId)) {
return res.status(400).json({error: "This user has already liked this post"});
}
})
.then(() => {
postData.likeCount++;
return postDoc.update({likeCount : postData.likeCount})
})
.then(() => {
return res.status(200).json(postData);
})
}
})
.catch((err) => {
return res.status(500).json({error: 'Something is wrong'});
})
likes.push(postId);
return userDoc.ref.update({likes})
})
.then(() => {
return db.doc(`/posts/${postId}`).get()
})
.then((postDoc) => {
let postData = postDoc.data();
postData.likeCount++;
likedPostDoc = postData;
return postDoc.ref.update({likeCount : postData.likeCount})
})
.then(() => {
return res.status(201).json(likedPostDoc);
})
.catch((err) => {
console.log(err);
return res.status(500).json({error: err});
})
// let postData;
// const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
// .where('postId', '==', req.params.postId).limit(1);
// const postDoc = db.doc(`/posts/${req.params.postId}`);
// postDoc.get()
// .then((doc) => {
// if(doc.exists) {
// postData = doc.data();
// return likeDoc.get();
// }
// else
// {
// return res.status(404).json({error: 'Post not found'});
// }
// })
// .then((data) => {
// if (data.empty) {
// return admin.firestore().collection('likes').add({
// postId : req.params.postId,
// userHandle: req.user.handle
// })
// .then(() => {
// postData.likeCount++;
// return postDoc.update({likeCount : postData.likeCount})
// })
// .then(() => {
// return res.status(200).json(postData);
// })
// }
// })
// .catch((err) => {
// return res.status(500).json({error: 'Something is wrong'});
// })
}
exports.unlikePost = (req, res) => {
let postData;
const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
.where('postId', '==', req.params.postId).limit(1);
const postId = req.params.postId;
let likedPostDoc;
db.doc(`/users/${req.userData.handle}`)
.get()
.then((userDoc) => {
let likes = userDoc.data().likes;
if (likes === undefined || likes === null) {
likes = [];
}
const postDoc = db.doc(`/posts/${req.params.postId}`);
if (!likes.includes(postId)) {
return res.status(400).json({error: "This user hasn't liked this post yet"});
}
postDoc.get()
.then((doc) => {
if(doc.exists) {
postData = doc.data();
return likeDoc.get();
}
else
{
return res.status(404).json({error: 'Post not found'});
}
})
.then((data) => {
return db
.doc(`/likes/${data.docs[0].id}`)
.delete()
.then(() => {
postData.likeCount--;
return postDoc.update({ likeCount: postData.likeCount });
})
.then(() => {
res.status(200).json(postData);
});
let i;
for (i = 0; i < likes.length; i++) {
if (likes[i] === postId) {
likes.splice(i, 1);
}
}
return userDoc.ref.update({likes})
})
.then(() => {
return db.doc(`/posts/${postId}`).get()
})
.then((postDoc) => {
let postData = postDoc.data();
postData.likeCount--;
likedPostDoc = postData;
return postDoc.ref.update({likeCount : postData.likeCount})
})
.then(() => {
return res.status(201).json(likedPostDoc);
})
.catch((err) => {
console.log(err);
return res.status(500).json({error: err});
})
// let postData;
// const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
// .where('postId', '==', req.params.postId).limit(1);
// const postDoc = db.doc(`/posts/${req.params.postId}`);
// postDoc.get()
// .then((doc) => {
// if(doc.exists) {
// postData = doc.data();
// return likeDoc.get();
// }
// else
// {
// return res.status(404).json({error: 'Post not found'});
// }
// })
// .then((data) => {
// return db
// .doc(`/likes/${data.docs[0].id}`)
// .delete()
// .then(() => {
// postData.likeCount--;
// return postDoc.update({ likeCount: postData.likeCount });
// })
// .then(() => {
// res.status(200).json(postData);
// });
})
.catch((err) => {
console.error(err);
return res.status(500).json({error: 'Something is wrong'});
})
// })
// .catch((err) => {
// console.error(err);
// return res.status(500).json({error: 'Something is wrong'});
// })
}
exports.getLikes = (req, res) => {
db.doc(`/users/${req.userData.handle}`)
.get()
.then((doc) => {
let likes = doc.data().likes;
if (likes === undefined || likes === null) {
likes = [];
}
return res.status(200).json({likes});
})
.catch((err) => {
console.log(err);
return res.status(500).json({error: err});
})
}
exports.getFilteredPosts = (req, res) => {
admin.firestore().collection('posts').where('userHandle', '==', 'new user').where('microBlogTopics', '==')
admin
.firestore()
.collection("posts")
.where("userHandle", "==", "new user")
.where("microBlogTopics", "==");
};

View File

@@ -1,4 +1,6 @@
/* eslint-disable promise/catch-or-return */
/* eslint-disable promise/always-return */
const { admin, db } = require("../util/admin");
const config = require("../util/config");
const { validateUpdateProfileInfo } = require("../util/validator");
@@ -161,11 +163,13 @@ exports.login = (req, res) => {
return;
})
.catch(function(err) {
if (!doc.exists) {
return res
.status(403)
.json({ general: "Invalid credentials. Please try again." });
}
// FIX: doc variable is out of scope
// if (!doc.exists) {
// return res
// .status(403)
// .json({ general: "Invalid credentials. Please try again." });
// }
console.log(err);
return res.status(500).send(err);
});
}
@@ -209,7 +213,7 @@ exports.deleteUser = (req, res) => {
let errors = {};
function thenFunction(data) {
console.log(`${data} data for ${req.userData.handle} has been deleted.`);
console.log(`${data} for ${req.userData.handle} has been deleted.`);
}
function catchFunction(data, err) {
@@ -217,14 +221,131 @@ exports.deleteUser = (req, res) => {
errors[data] = err;
}
function deleteDirectMessages() {
return new Promise((resolve, reject) => {
const deleteUsername = req.userData.handle;
db.doc(`/users/${deleteUsername}`)
.get()
.then((deleteUserDocSnap) => {
const dms = deleteUserDocSnap.data().dms;
const dmRecipients = deleteUserDocSnap.data().dmRecipients;
if (!dms) {
resolve();
return;
}
// Iterate over the list of users who this person has DM'd
let otherUsersPromises = [];
// Resolve if they don't have a dmRecipients list
if (dmRecipients === undefined || dmRecipients === null || dmRecipients.length === 0) {
resolve();
return;
}
dmRecipients.forEach((dmRecipient) => {
otherUsersPromises.push(
// Get each users data
db.doc(`/users/${dmRecipient}`).get()
.then((otherUserDocSnap) => {
// Get the index of deleteUsername so that we can remove the dangling
// reference to the DM document
let otherUserDMRecipients = otherUserDocSnap.data().dmRecipients;
let otherUserDMs = otherUserDocSnap.data().dms;
let index = -1;
otherUserDMRecipients.forEach((dmRecip, i) => {
if (dmRecip === deleteUsername) {
index = i;
}
})
if (index !== -1) {
// Remove deleteUsername from their dmRecipients list
otherUserDMRecipients.splice(index, 1);
// Remove the DM channel with deleteUsername
otherUserDMs.splice(index, 1);
// Update the users data
return otherUserDocSnap.ref.update({
dmRecipients: otherUserDMRecipients,
dms: otherUserDMs
});
}
})
)
})
// Wait for the removal of DM data stored on other users to be deleted
Promise.all(otherUsersPromises)
.then(() => {
// Iterate through DM references and delete them from the dm collection
let dmRefsPromises = [];
dms.forEach((dmRef) => {
// Create a delete queue
let batch = db.batch();
dmRefsPromises.push(
// Add the messages to the delete queue
db.collection(`/dm/${dmRef.id}/messages`).listDocuments()
.then((docs) => {
console.log("second")
console.log(docs);
docs.map((doc) => {
batch.delete(doc);
})
// Add the doc that the DM is stored in to the delete queue
batch.delete(dmRef);
// Commit the writes
return batch.commit();
})
)
})
return Promise.all(dmRefsPromises);
})
.then(() => {
resolve();
return;
})
.catch((err) => {
console.log("error " + err);
reject(err);
return;
})
})
.catch((err) => {
console.log(err);
return res.status(500).json({error: err});
})
})
}
// Deletes user from authentication
let auth = admin.auth().deleteUser(userId);
// Deletes database data
let data = db
.collection("users")
.doc(`${req.user.handle}`)
.delete();
let data = new Promise((resolve, reject) => {
deleteDirectMessages()
.then(() => {
return db
.collection("users")
.doc(`${req.user.handle}`)
.delete()
})
.then(() => {
resolve();
return;
})
.catch((err) => {
console.log(err);
reject(err);
return;
})
})
// Deletes any custom profile image
let image;
@@ -298,7 +419,7 @@ exports.updateProfileInfo = (req, res) => {
// Update the database entry for this user
db.collection("users")
.doc(req.user.handle)
.set(profileData, { merge: true })
.set(profileData)
.then(() => {
console.log(`${req.user.handle}'s profile info has been updated.`);
return res.status(201).json({
@@ -331,6 +452,25 @@ exports.getUserDetails = (req, res) => {
});
};
exports.getAllHandles = (req, res) => {
var user_query = admin.firestore().collection("users");
user_query.get()
.then((allUsers) => {
let users = [];
allUsers.forEach((user) => {
users.push(user.data().handle);
});
return res.status(200).json(users);
})
.catch((err) => {
return res.status(500).json({
message:"Failed to retrieve posts from database.",
error: err
});
});
};
// Returns all data stored for a user
exports.getAuthenticatedUser = (req, res) => {
let credentials = {};
db.doc(`/users/${req.user.handle}`)
@@ -414,6 +554,535 @@ exports.unverifyUser = (req, res) => {
return res.status(500).json({ error: err.code });
});
};
// Returns all the DMs that the user is currently participating in
exports.getDirectMessages = (req, res) => {
/* Return value
* data: [DMs]
* dm : {
* dmId: str
* messages: [msgs]
* msg: {
* author: str
* createdAt: ISOString
* message: str
* messageId: str
* }
* recipient: str
* recentMessage: str
* recentMessageTimestamp: ISOString
* }
*/
// Returns all the messages in a dm documentSnapshot
function getMessages(dm) {
let promise = new Promise((resolve, reject) => {
let messagesCollection = dm.collection('messages');
// If the messagesCollection is missing, that mean that there aren't any messages
if (messagesCollection === null || messagesCollection === undefined) {
return;
}
let msgs = [];
let promises = [];
// Get all of the messages in the DM
messagesCollection.get()
.then((dmQuerySnap) => {
dmQuerySnap.forEach((dmQueryDocSnap) => {
promises.push(
dmQueryDocSnap.ref.get()
.then((messageData) => {
msgs.push(messageData.data());
return;
})
)
})
let waitPromise = Promise.all(promises);
waitPromise.then(() => {
// 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
msgs.sort((a, b) => {
return (b.createdAt > a.createdAt) ? -1 : ((b.createdAt < a.createdAt) ? 1 : 0);
})
resolve(msgs);
});
})
});
return promise;
}
const dms = req.userData.dms;
// Return null if this user has no DMs
if (dms === undefined || dms === null || dms.length === 0) return res.status(200).json({data: null});
let dmsData = [];
let dmPromises = [];
dms.forEach((dm) => {
let dmData = {};
// Make a new promise for each DM document
dmPromises.push(new Promise((resolve, reject) => {
dm // DM document reference
.get()
.then((doc) => {
let docData = doc.data();
// Recipient is the person you are messaging
docData.authors[0] === req.userData.handle ?
dmData.recipient = docData.authors[1] :
dmData.recipient = docData.authors[0]
// Save the createdAt time
dmData.createdAt = docData.createdAt;
// Get all the messages from this dm document
getMessages(dm)
.then((msgs) => {
dmData.messages = msgs;
dmData.recentMessage = msgs.length !== 0 ? msgs[msgs.length - 1].message : null;
dmData.recentMessageTimestamp = msgs.length !== 0 ? msgs[msgs.length - 1].createdAt : null;
dmData.dmId = doc.id;
resolve(dmData);
})
}).catch((err) => {
console.err(err);
return res.status(400).json({error: {
message: "An error occurred when reading the DM document reference",
error: err
}});
})
}).then((dmData) => {
dmsData.push(dmData);
})
)
})
// Wait for all DM document promises to resolve before returning data
dmWaitPromise = Promise.all(dmPromises)
.then(() => {
// Sort the DMs so that the ones with the newest messages are at the top
dmsData.sort((a, b) => {
if (a.recentMessageTimestamp === null && b.recentMessageTimestamp === null) {
if (b.createdAt < a.createdAt) {
return -1;
} else if (b.createdAt > a.createdAt) {
return 1;
} else {
return 0;
}
} else if (a.recentMessageTimestamp === null) {
return 1;
} else if (b.recentMessageTimestamp === null) {
return -1;
} else if (b.recentMessageTimestamp < a.recentMessageTimestamp) {
return -1;
} else if (b.recentMessageTimestamp > a.recentMessageTimestamp) {
return 1;
} else {
return 0;
}
});
return res.status(200).json({data: dmsData})
})
.catch((err) => {
return res.status(500).json({error:{
message: "An error occurred while sorting",
error: err
}});
});
}
// Toggles direct messages on or off depending on the requese
/* Request Parameters
* enable: bool
*/
exports.toggleDirectMessages = (req, res) => {
const enable = req.body.enable;
const user = req.userData.handle;
db.doc(`/users/${user}`).update({dmEnabled: enable})
.then(() => {
return res.status(201).json({message: "Success"});
})
.catch((err) => {
return res.status(500).json({error: err});
})
}
// Returns a promise that resolves if user has DMs enabled
// and rejects if there is an error or DMs are disabled
isDirectMessageEnabled = (username) => {
return new Promise((resolve, reject) => {
let result = {};
result.code = null;
result.message = null;
if (username === null || username === undefined || username === "") {
result.code = 400;
result.message = "No user was sent in the request. The request should have a non-empty 'user' key.";
reject(result);
}
db.doc(`/users/${username}`)
.get()
.then((doc) => {
if (doc.exists) {
// console.log(doc.data())
if (doc.data().dmEnabled === true || doc.data().dmEnabled === null || doc.data().dmEnabled === undefined) {
// Assume DMs are enabled if they don't have a dmEnabled key
resolve(result);
} else {
result.code = 200;
result.message = `${username} has DMs disabled`;
reject(result);
}
} else {
console.log(`${username} is not in the database`);
result.code = 400;
result.message = `${username} is not in the database`;
reject(result);
}
})
.catch((err) => {
console.log("HI")
console.error(err);
result.code = 500;
result.message = err;
reject(result);
})
});
}
// 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
verifyDirectMessageIntegrity = (dmRef) => {
return new Promise((resolve, reject) => {
resolve("Not implemented yet");
})
}
// Checks if there are any DM channels open with userB on userA's side
oneWayCheck = (userA, userB) => {
return new Promise((resolve, reject) => {
db.doc(`/users/${userA}`)
.get()
.then((userASnapshot) => {
const dmList = userASnapshot.data().dms;
const dmRecipients = userASnapshot.data().dmRecipients;
if (dmList === null || dmList === undefined || dmRecipients === null || dmRecipients === undefined) {
// They don't have any DMs yet
console.log("No DMs array");
userASnapshot.ref.set({dms:[], dmRecipients:[]}, {merge: true})
.then(() => {
resolve();
})
} else if (dmList.length === 0) {
// Their DMs are empty
console.log("DMs array is empty");
resolve();
} else {
// let dmDocs = [];
// let forEachPromises = [];
// dmList.forEach((dmRef) => {
// forEachPromises.push(
// dmRef.get()
// // .then((dmDoc) => {
// // TODO: Figure out why dmDoc.exists() isn't working
// // Make sure all of the docs exist and none of the references
// // are broken
// // if (dmDoc.exists()) {
// // dmDocs.push(dmDoc);
// // } else {
// // console.log(`DM reference /dm/${dmDoc.id} is invalid`);
// // reject(`DM reference /dm/${dmDoc.id} is invalid`);
// // }
// // })
// )
// })
dmRecipients.forEach((dmRecipient) => {
if (dmRecipient === userB) {
console.log(`You already have a DM with ${userB}`);
reject(new Error(`You already have a DM with ${userB}`));
return;
}
})
resolve();
// Promise.all(forEachPromises)
// .then((dmDocs) => {
// // Check if any of the DMs have for userA have userA and userB as the authors.
// // This would mean that they already have a DM channel
// dmDocs.forEach((dmDoc) => {
// // Checking if any of the authors key in any of their DMs are missing
// let authors = dmDoc.data().authors;
// // if (authors[0] === "keanureeves") {
// // console.log("it is")
// // resolve();
// // } else {
// // console.log("it is not")
// // reject("not my keanu");
// // }
// // if (authors === null || authors === undefined || authors.length !== 2) {
// // // console.log(`The authors key in /dm/${dmDoc.id} is undefined or missing values`);
// // // reject(`The authors key in /dm/${dmDoc.id} is undefined or missing values`);
// // console.log('a')
// // reject("a")
// // } else if ((authors[0] === userA && authors[1] === userB) || (authors[1] === userA && authors[0] === userB)) {
// // // console.log(`${userA} already has a DM channel between ${userA} and ${userB}`);
// // // reject(`${userA} already has a DM channel between ${userA} and ${userB}`);
// // console.log('b')
// // reject('b')
// // } else {
// // // BUG: For some reason the promise.all is resolving even though there are multiple rejects
// // // and only one resolve
// // console.log("c");
// // resolve();
// // }
// // console.log(authors)
// // console.log([userA, userB])
// if (authors[0] === null || authors === undefined || authors.length !== 2) {
// console.log('a');
// reject('a');
// } else if (authors[0] === userA && authors[1] === userB) {
// console.log("b");
// reject('b');
// } else {
// console.log('c');
// resolve();
// }
// })
// })
}
})
})
}
// Returns a promise that resolves if there is not already a DM channel
// between the creator and recipient usernames. It rejects if one already
// exists or there is an error.
checkNoDirectMessageExists = (creator, recipient) => {
return new Promise((resolve, reject) => {
let creatorPromise = oneWayCheck(creator, recipient);
let recipientPromise = oneWayCheck(recipient, creator);
let temp_array = [];
temp_array.push(creatorPromise);
temp_array.push(recipientPromise)
Promise.all(temp_array)
.then(() => {
resolve();
})
.catch((err) => {
reject(err);
})
})
}
addDirectMessageToUser = (username, recipient, dmRef) => {
return new Promise((resolve, reject) => {
db.doc(`/users/${username}`).get()
.then((docSnap) => {
let dmList = docSnap.data().dms;
let dmRecipients = docSnap.data().dmRecipients;
dmList.push(dmRef);
dmRecipients.push(recipient);
return db.doc(`/users/${username}`).update({dms: dmList, dmRecipients});
})
.then(() => {
resolve();
})
.catch((err) => {
reject(err);
})
})
}
// Sends a DM from the caller to the requested DM document
/* Request Parameters
* message: str
* user: str
*/
exports.sendDirectMessage = (req, res) => {
// TODO: add error checking for if message or user is null
const creator = req.userData.handle;
const recipient = req.body.user;
const message = req.body.message;
const newMessage = {
author: creator,
createdAt: new Date().toISOString(),
message,
messageId: null
}
db.doc(`/users/${creator}`).get()
.then((userDoc) => {
let dmList = userDoc.data().dms;
// Return if the creator doesn't have any DMs.
// This means they have not created a DM's channel yet
if (dmList === null || dmList === undefined) return res.status(400).json({error: `There is no DM channel between ${creator} and ${recipient}. Use /api/dms/new.`})
let dmRefPromises = [];
dmList.forEach((dmRef) => {
dmRefPromises.push(
new Promise((resolve, reject) => {
dmRef.get()
.then((dmDoc) => {
let authors = dmDoc.data().authors;
if (
(authors[0] === creator && authors[1] === recipient) ||
(authors[1] === creator && authors[0] === recipient)
) {
resolve({correct: true, dmRef});
} else {
resolve({correct: false, dmRef});
}
})
.catch((err) => {
reject(err);
})
})
)
})
return Promise.all(dmRefPromises);
})
.then((results) => {
let correctDMRef = null;
results.forEach((result) => {
if (result.correct) {
correctDMRef = result.dmRef;
}
})
if (correctDMRef === null) {
console.log(`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);
})
.then((newMsgRef) => {
return newMsgRef.update({messageId: newMsgRef.id}, {merge: true});
})
.then(() => {
return res.status(200).json({message: "OK"});
})
.catch((err) => {
console.log(err);
return res.status(500).json({error: err});
})
}
// Creates a DM between the caller and the user in the request
/* Request Parameters
* user: str
*/
exports.createDirectMessage = (req, res) => {
const creator = req.userData.handle;
const recipient = req.body.user;
// Check if they are DMing themselves
if (creator === recipient) return res.status(400).json({error: "You can't DM yourself"});
// Check if this user has DMs enabled
let creatorEnabled = isDirectMessageEnabled(creator);
// Check if the requested user has DMs enabled
let recipientEnabled = isDirectMessageEnabled(recipient);
// Make sure that they don't already have a DM channel
let noDMExists = checkNoDirectMessageExists(creator, recipient)
let dataValidations = [
creatorEnabled,
recipientEnabled,
noDMExists
]
Promise.all(dataValidations)
.then(() => {
// Create a new DM document
return db.collection("dm").add({})
})
.then((dmDocRef) => {
// Fill it with some data.
// Note that there isn't a messages collection by default.
let dmData = {
dmId: dmDocRef.id,
authors: [creator, recipient],
createdAt: new Date().toISOString()
}
// Update DM document
let dmDocPromise = dmDocRef.set(dmData);
// Add the DM reference to the creator
let updateCreatorPromise = addDirectMessageToUser(creator, recipient, dmDocRef);
// Add the DM reference to the recipient
let updateRecipientPromise = addDirectMessageToUser(recipient, creator, dmDocRef);
// Wait for all promises
return Promise.all([dmDocPromise, updateCreatorPromise, updateRecipientPromise]);
})
.then (() => {
return res.status(201).json({message: "Success!"});
})
.catch((err) => {
console.log(err);
if (err.code && err.message && err.code > 0) {
// Specific error that I've created
return res.status(err.code).json({error: err.message});
} else {
// Generic or firebase error
return res.status(500).json({error: err});
}
})
}
// Checks if the requested user has DMs enable or not
/* Request Parameters
* user: str
*/
exports.checkDirectMessagesEnabled = (req, res) => {
isDirectMessageEnabled(req.body.user)
.then(() => {
return res.status(200).json({enabled: true});
})
.catch((result) => {
console.log(result);
if (result.code === 200) {
// DMs are disabled
return res.status(200).json({enabled: false});
} else {
// Some other error occured
return res.status(result.code).json({err: result.message});
}
})
}
exports.getUserHandles = (req, res) => {
db.doc(`/users/${req.body.userHandle}`)
.get()
@@ -449,7 +1118,7 @@ exports.addSubscription = (req, res) => {
.catch(err => {
return res.status(500).json({ err });
});
return res.status(500).json({ error: "shouldn't execute" });
return res.status(200).json({ message: "ok" });
});
};
@@ -466,6 +1135,126 @@ exports.getSubs = (req, res) => {
});
};
// Uploads a profile image
exports.uploadProfileImage = (req, res) => {
const BusBoy = require("busboy");
const path = require("path");
const os = require("os");
const fs = require("fs");
const busboy = new BusBoy({ headers: req.headers });
let imageFileName;
let imageToBeUploaded = {};
let oldImageFileName = req.userData.imageUrl ? req.userData.imageUrl.split("/o/")[1].split("?alt")[0] : null;
// console.log(`old file: ${oldImageFileName}`);
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') {
return res.status(400).json({ error: "Wrong filetype submitted" });
}
// console.log(fieldname);
// console.log(filename);
// console.log(mimetype);
const imageExtension = filename.split(".")[filename.split(".").length - 1]; // Get the image file extension
imageFileName = `${Math.round(Math.random() * 100000000000)}.${imageExtension}`; // Get a random filename
const filepath = path.join(os.tmpdir(), imageFileName);
imageToBeUploaded = { filepath, mimetype };
file.pipe(fs.createWriteStream(filepath));
});
busboy.on("finish", () => {
// Save the file to the storage bucket
admin.storage().bucket(config.storageBucket).upload(imageToBeUploaded.filepath, {
resumable: false,
metadata: {
metadata: {
contentType: imageToBeUploaded.mimetype
}
}
})
.then(() => {
// Add the new URL to the user's profile
const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`;
return db.doc(`/users/${req.user.handle}`).update({ imageUrl });
})
.then(() => {
// Delete their old image if they have one
if (oldImageFileName !== null && oldImageFileName !== "no-img.png") {
admin.storage().bucket(config.storageBucket).file(oldImageFileName).delete()
.then(() => {
return res.status(201).json({ message: "Image uploaded successfully1"});
})
.catch((err) => {
console.log(err);
return res.status(201).json({ message: "Image uploaded successfully2"});
})
// return res.status(201).json({ message: "Image uploaded successfully"});
} else {
return res.status(201).json({ message: "Image uploaded successfully3"});
}
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code})
})
});
busboy.end(req.rawBody);
// const BusBoy = require('busboy');
// const path = require('path');
// const os = require('os');
// const fs = require('fs');
// const busboy = new BusBoy({ headers: req.headers });
// let imageToBeUploaded = {};
// let imageFileName;
// busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
// // console.log(fieldname, file, filename, encoding, mimetype);
// if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') {
// return res.status(400).json({ error: 'Wrong file type submitted' });
// }
// // my.image.png => ['my', 'image', 'png']
// const imageExtension = filename.split('.')[filename.split('.').length - 1];
// // 32756238461724837.png
// imageFileName = `${Math.round(
// Math.random() * 1000000000000
// ).toString()}.${imageExtension}`;
// const filepath = path.join(os.tmpdir(), imageFileName);
// imageToBeUploaded = { filepath, mimetype };
// file.pipe(fs.createWriteStream(filepath));
// });
// busboy.on('finish', () => {
// admin
// .storage()
// .bucket(config.storageBucket)
// .upload(imageToBeUploaded.filepath, {
// resumable: false,
// metadata: {
// metadata: {
// contentType: imageToBeUploaded.mimetype
// }
// }
// })
// .then(() => {
// const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${
// config.storageBucket
// }/o/${imageFileName}?alt=media`;
// return db.doc(`/users/${req.user.handle}`).update({ imageUrl });
// })
// .then(() => {
// return res.json({ message: 'image uploaded successfully' });
// })
// .catch((err) => {
// console.error(err);
// return res.status(500).json({ error: 'something went wrong' });
// });
// });
// busboy.end(req.rawBody);
}
exports.removeSub = (req, res) => {
let new_following = [];
let userRef = db.doc(`/users/${req.userData.handle}`);
@@ -489,6 +1278,7 @@ exports.removeSub = (req, res) => {
.catch(err => {
return res.status(500).json({ err });
});
return res.status(500).json({ error: "shouldn't execute" });
return res.status(200).json({ message: "ok" });
});
};

View File

@@ -11,12 +11,19 @@ app.use(cors());
*------------------------------------------------------------------*/
const {
getAuthenticatedUser,
getDirectMessages,
sendDirectMessage,
createDirectMessage,
checkDirectMessagesEnabled,
toggleDirectMessages,
getAllHandles,
getUserDetails,
getProfileInfo,
login,
signup,
deleteUser,
updateProfileInfo,
uploadProfileImage,
verifyUser,
unverifyUser,
getUserHandles,
@@ -37,16 +44,42 @@ app.post("/login", login);
//Deletes user account
app.delete("/delete", fbAuth, deleteUser);
// Returns all direct messages that the user is participating in
app.get("/dms", fbAuth, getDirectMessages);
// Send a message in a DM from one user to another
app.post("/dms/send", fbAuth, sendDirectMessage);
// Create a new DM between two users
app.post("/dms/new", fbAuth, createDirectMessage);
// Checks if the user provided has DMs enabled or not
app.post("/dms/enabled", checkDirectMessagesEnabled);
// Used to toggle DMs on or off for the current user
app.post("/dms/toggle", fbAuth, toggleDirectMessages);
app.get("/getUser", fbAuth, getUserDetails);
app.post("/getUserDetails", fbAuth, getUserDetails);
// Returns a list of all usernames
// Used for searching
app.get("/getAllHandles", fbAuth, getAllHandles);
// Returns all profile data of the currently logged in user
app.get("/getProfileInfo", fbAuth, getProfileInfo);
// Updates the currently logged in user's profile information
app.post("/updateProfileInfo", fbAuth, updateProfileInfo);
// Returns all user data for the logged in user.
// Used when setting the state in Redux.
app.get("/user", fbAuth, getAuthenticatedUser);
// Uploads a profile image
app.post("/user/image", fbAuth, uploadProfileImage);
// Verifies the user sent to the request
// Must be run by the Admin user
app.post("/verifyUser", fbAuth, verifyUser);
@@ -67,10 +100,13 @@ app.post("/addSubscription", fbAuth, addSubscription);
// remove one subscription
app.post("/removeSub", fbAuth, removeSub);
/*------------------------------------------------------------------*
* handlers/post.js *
*------------------------------------------------------------------*/
const { getallPostsforUser, getallPosts, putPost, likePost, unlikePost, quoteWithPost, quoteWithoutPost} = require("./handlers/post");
const { getallPostsforUser, getallPosts, putPost, likePost, unlikePost, getLikes, quoteWithPost, quoteWithoutPost, checkforLikePost, getOtherUsersPosts} = require("./handlers/post");
app.get("/getallPostsforUser", fbAuth, getallPostsforUser);
@@ -79,13 +115,15 @@ app.get("/getallPosts", getallPosts);
// Adds one post to the database
app.post("/putPost", fbAuth, putPost);
app.get("/likes", fbAuth, getLikes);
app.get("/like/:postId", fbAuth, likePost);
app.get("/unlike/:postId", fbAuth, unlikePost);
app.get("/checkforLikePost/:postId", fbAuth, checkforLikePost);
app.post("/quoteWithPost/:postId", fbAuth, quoteWithPost);
app.post("/quoteWithoutPost/:postId", fbAuth, quoteWithoutPost);
app.post("/getOtherUsersPosts", fbAuth, getOtherUsersPosts);
/*------------------------------------------------------------------*
* handlers/topic.js *

View File

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

View File

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

427
package-lock.json generated
View File

@@ -1,428 +1,3 @@
{
"requires": true,
"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="
}
}
"lockfileVersion": 1
}

View File

@@ -3092,6 +3092,11 @@
"merge": "^1.2.0"
}
},
"exenv": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/exenv/-/exenv-1.2.2.tgz",
"integrity": "sha1-KueOhdmJQVhnCwPUe+wfA72Ru50="
},
"exit-hook": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/exit-hook/-/exit-hook-1.1.1.tgz",
@@ -3957,6 +3962,11 @@
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
"integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A=="
},
"fuse.js": {
"version": "3.4.6",
"resolved": "https://registry.npmjs.org/fuse.js/-/fuse.js-3.4.6.tgz",
"integrity": "sha512-H6aJY4UpLFwxj1+5nAvufom5b2BT2v45P1MkPvdGIK8fWjQx/7o6tTT1+ALV0yawQvbmvCF0ufl2et8eJ7v7Cg=="
},
"gauge": {
"version": "2.7.4",
"resolved": "https://registry.npmjs.org/gauge/-/gauge-2.7.4.tgz",
@@ -7167,6 +7177,22 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.9.0.tgz",
"integrity": "sha512-tJBzzzIgnnRfEm046qRcURvwQnZVXmuCbscxUO5RWrGTXpon2d4c8mI0D8WE6ydVIm29JiLB6+RslkIvym9Rjw=="
},
"react-lifecycles-compat": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz",
"integrity": "sha512-fBASbA6LnOU9dOU2eW7aQ8xmYBSXUIWr+UmF9b1efZBazGNO+rcXT/icdKnYm2pTwcRylVUYwW7H1PHfLekVzA=="
},
"react-modal": {
"version": "3.11.1",
"resolved": "https://registry.npmjs.org/react-modal/-/react-modal-3.11.1.tgz",
"integrity": "sha512-8uN744Yq0X2lbfSLxsEEc2UV3RjSRb4yDVxRQ1aGzPo86QjNOwhQSukDb8U8kR+636TRTvfMren10fgOjAy9eA==",
"requires": {
"exenv": "^1.2.0",
"prop-types": "^15.5.10",
"react-lifecycles-compat": "^3.0.0",
"warning": "^4.0.3"
}
},
"react-redux": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-7.1.1.tgz",
@@ -9991,6 +10017,14 @@
"makeerror": "1.0.x"
}
},
"warning": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/warning/-/warning-4.0.3.tgz",
"integrity": "sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==",
"requires": {
"loose-envify": "^1.0.0"
}
},
"watch": {
"version": "0.10.0",
"resolved": "https://registry.npmjs.org/watch/-/watch-0.10.0.tgz",

View File

@@ -10,17 +10,21 @@
"axios": "^0.19.0",
"clsx": "^1.0.4",
"create-react-app": "^3.1.2",
"dayjs": "^1.8.17",
"fuse.js": "^3.4.6",
"install": "^0.13.0",
"jwt-decode": "^2.2.0",
"node-pre-gyp": "^0.13.0",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-modal": "^3.11.1",
"react-redux": "^7.1.1",
"react-router-dom": "^5.1.0",
"react-scripts": "0.9.5",
"redux": "^4.0.4",
"redux-thunk": "^2.3.0",
"typeface-roboto": "0.0.75"
"typeface-roboto": "0.0.75",
"underscore": "^1.9.1"
},
"devDependencies": {},
"scripts": {

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

@@ -31,6 +31,7 @@ import editProfile from "./pages/editProfile";
import userLine from "./Userline.js";
import verify from "./pages/verify";
import Search from "./pages/Search.js";
import directMessages from "./pages/directMessages";
import otherUser from "./pages/otherUser";
const theme = createMuiTheme(themeObject);
@@ -62,7 +63,7 @@ class App extends Component {
<div className="container">
<Navbar />
</div>
<div className="app">
<div className="app" style={{height: "700"}}>
<Switch>
{/* AuthRoute checks if the user is logged in and if they are it redirects them to /home */}
<AuthRoute exact path="/signup" component={signup} />
@@ -74,9 +75,10 @@ class App extends Component {
<Route exact path="/home" component={home} />
<Route exact path="/user" component={user} />
<Route exact path="/edit" component={editProfile} />
<Route exact path="/user/edit" component={editProfile} />
<Route exact path="/verify" component={verify} />
<Route exact path="/search" component={Search} />
<Route exact path="/dm" component={directMessages} />
<Route exact path="/user/:userhandle" component={otherUser} />
<AuthRoute exact path="/" component={home} />

View File

@@ -1,10 +1,10 @@
import React, { Component } from "react";
import { BrowserRouter as Router } from 'react-router-dom';
import Route from 'react-router-dom/Route';
// import { BrowserRouter as Router } from 'react-router-dom';
// import Route from 'react-router-dom/Route';
import axios from 'axios';
import Box from '@material-ui/core/Box'
import {borders} from '@material-ui/system';
import { sizing } from '@material-ui/system';
// import {borders} from '@material-ui/system';
// import { sizing } from '@material-ui/system';
// var moment = require('moment');
@@ -41,7 +41,7 @@ class Userline extends Component {
<div style={{fontsize: "13px", textAlign: "left", marginLeft: "14px"}}>
<p>Userline</p>
</div>
<Box border={1} width="25%" flex="1" height="auto" m={2} fontSize="13px" textAlign= "left" padding="5px" flexWrap= "wrap" flexDirection= "row" >
<Box border={1} width="25%" flex="1" height="auto" m={2} fontSize="13px" textAlign="left" padding="5px" flexWrap="wrap" flexDirection="row" >
<div style={{flexWrap: "wrap", flex: "1", flexDirection: "row", wordBreak: "break-word"}}>
<p>
{sortedPosts.map((microBlog) => <p>Microblog Title: {microBlog.microBlogTitle}
@@ -50,7 +50,7 @@ class Userline extends Component {
<br></br>Number of comments: {microBlog.commentCount}
<br></br>Number of likes: {microBlog.likeCount}
<br></br>Body of post: {microBlog.body}
<br></br>Tagged topics: {microBlog.microBlogTopics.join("," + " ")}
<br></br>Tagged topics: {microBlog.microBlogTopics.join(", ")}
</p>)}
</p>
</div>

View File

@@ -1,8 +1,29 @@
import React, { Component } from "react";
import { BrowserRouter as Router } from "react-router-dom";
import Route from "react-router-dom/Route";
// import { BrowserRouter as Router } from "react-router-dom";
// import Route from "react-router-dom/Route";
import axios from "axios";
// Material-UI
import TextField from '@material-ui/core/TextField';
// import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import withStyles from "@material-ui/styles/withStyles";
const styles = {
container: {
position: "fixed"
},
form: {
width: "300px",
height: "50px",
marginTop: "180px",
marginLeft: "50px"
},
textField: {
marginBottom: 15
}
}
class Writing_Microblogs extends Component {
constructor(props) {
super(props);
@@ -27,7 +48,7 @@ class Writing_Microblogs extends Component {
this.setState({ topics: event.target.value });
}
handleSubmit(event) {
handleSubmit = (event) => {
// alert('A title for the microblog was inputted: ' + this.state.title + '\nA microblog was posted: ' + this.state.value);
const postData = {
body: this.state.value,
@@ -40,20 +61,34 @@ class Writing_Microblogs extends Component {
};
axios
.post("/putPost", postData, headers)
.post("/putPost", postData, headers) // TODO: add topics
.then(res => {
alert("Post was shared successfully!");
// alert("Post was shared successfully!");
console.log(res.data);
})
.catch(err => {
alert("An error occured.");
console.error(err);
});
console.log(postData.microBlogTopics);
postData.microBlogTopics.forEach(topic => {
axios
.post("/putTopic", {
following: topic
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.error(err);
});
});
event.preventDefault();
this.setState({ value: "", title: "", characterCount: 250, topics: "" });
}
handleChangeforPost(event) {
this.setState({ value: event.target.value });
}
@@ -64,65 +99,67 @@ class Writing_Microblogs extends Component {
}
render() {
const { classes } = this.props;
return (
<div>
<div
style={{
width: "200px",
height: "50px",
marginTop: "180px",
marginLeft: "50px"
}}
>
<form>
<textarea
placeholder="Enter Microblog Title"
value={this.state.title}
required
onChange={this.handleChange}
cols={30}
rows={1}
/>
</form>
</div>
<div style={{ width: "200px", height: "50px", marginLeft: "50px" }}>
<form>
<textarea
placeholder="Enter topics seperated by a comma"
value={this.state.topics}
required
onChange={this.handleChangeforTopics}
cols={40}
rows={1}
/>
</form>
</div>
<div className={classes.container}>
<form noValidate className={classes.form}>
<TextField
id="title"
name="title"
label="Title"
className={classes.textField}
value={this.state.title}
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<div style={{ width: "200px", marginLeft: "50px" }}>
<form onSubmit={this.handleSubmit}>
<textarea
value={this.state.value}
required
maxLength="250"
placeholder="Write Microblog here..."
onChange={e => {
this.handleChangeforPost(e);
this.handleChangeforCharacterCount(e);
}}
cols={40}
rows={20}
/>
<div style={{ fontSize: "14px", marginRight: "-100px" }}>
<p2>Characters Left: {this.state.characterCount}</p2>
</div>
<div style={{ marginRight: "-100px" }}>
<button onClick>Share Post</button>
</div>
</form>
</div>
<TextField
id="topics"
name="topics"
label="Topics"
className={classes.textField}
value={this.state.topics}
variant="outlined"
onChange={this.handleChangeforTopics}
color="primary"
fullWidth
autoComplete='off'
/>
<TextField
id="content"
name="content"
label="Content"
color="primary"
className={classes.textField}
value={this.state.value}
helperText={`${this.state.characterCount} characters left`}
multiline
rows="9"
variant="outlined"
inputProps={{
maxLength: 250
}}
onChange={(e) => {
this.handleChangeforPost(e);
this.handleChangeforCharacterCount(e);
}}
fullWidth
autoComplete='off'
/>
<Button
onClick={this.handleSubmit}
// disabled={loading}
variant="outlined"
color="primary"
>
Share Post
</Button>
</form>
</div>
);
}
}
export default Writing_Microblogs;
export default withStyles(styles)(Writing_Microblogs);

View File

@@ -46,6 +46,11 @@ export class Navbar extends Component {
Profile
</Button>
)}
{authenticated && (
<Button component={Link} to="/dm">
DMs
</Button>
)}
{!authenticated && (
<Button component={Link} to="/login">
Login
@@ -62,7 +67,7 @@ export class Navbar extends Component {
</Button>
)}
{authenticated && (
<Button component={Link} to="/logout">
<Button style={{position: "absolute", right: 30}} component={Link} to="/logout">
Logout
</Button>
)}

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

@@ -1,14 +1,20 @@
/* eslint-disable */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import axios from 'axios';
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import axios from "axios";
// Material UI and React Router
import Grid from '@material-ui/core/Grid';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import CircularProgress from '@material-ui/core/CircularProgress';
import Button from '@material-ui/core/Button';
import Grid from "@material-ui/core/Grid";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import TextField from '@material-ui/core/TextField';
import Typography from "@material-ui/core/Typography";
import withStyles from '@material-ui/styles/withStyles';
// component
import '../App.css';
@@ -17,10 +23,19 @@ import noImage from '../images/no-img.png';
import Writing_Microblogs from '../Writing_Microblogs';
import ReactModal from 'react-modal';
// Redux
import { likePost, unlikePost, getLikes } from '../redux/actions/userActions';
const styles = {
card: {
marginBottom: 5
}
}
class Home extends Component {
state = {
likes: []
};
@@ -28,51 +43,103 @@ class Home extends Component {
axios
.get("/getallPosts")
.then(res => {
console.log(res.data);
// console.log(res.data);
this.setState({
posts: res.data
})
this.setState({posts: (this.state.posts).sort((a,b) =>
-a.createdAt.localeCompare(b.createdAt))
})
});
})
.catch(err => console.log(err));
this.props.getLikes();
}
componentWillReceiveProps(nextProps) {
this.setState({
likes: nextProps.user.likes
})
}
handleClickLikeButton = (event) => {
// 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
let postId = event.target.dataset.key ? event.target.dataset.key : event.target.parentNode.dataset.key;
console.log(postId)
let doc = document.getElementById(postId);
// console.log(postId);
if (this.state.likes.includes(postId)) {
this.props.unlikePost(postId, this.state.likes)
doc.dataset.likes--;
} else {
this.props.likePost(postId, this.state.likes)
doc.dataset.likes++;
}
doc.innerHTML = "Likes " + doc.dataset.likes;
}
formatDate(dateString) {
let newDate = new Date(Date.parse(dateString));
return newDate.toDateString();
}
render() {
let authenticated = this.props.user.authenticated;
const { UI:{ loading } } = this.props;
let authenticated = this.props.user.authenticated;
let {classes} = this.props;
let username = this.props.user.credentials.handle;
let postMarkup = this.state.posts ? (
this.state.posts.map(post =>
<Card>
<Card className={classes.card} key={post.postId}>
<CardContent>
<Typography>
{
this.state.imageUrl ? (<img src={this.state.imageUrl} height="250" width="250" />) :
{/* {
this.state.imageUrl ? (<img src={this.state.imageUrl} height="50" width="50" />) :
(<img src={noImage} height="50" width="50"/>)
} */}
{
post.profileImage ? (<img src={post.profileImage} height="50" width="50" />) :
(<img src={noImage} height="50" width="50"/>)
}
</Typography>
<Typography variant="h7"><b>{post.userHandle}</b></Typography>
<Typography variant="body2" color={"textSecondary"}>{post.createdAt.substring(0,10) +
" " + post.createdAt.substring(11,19)}</Typography>
<Typography variant="h5"><b>{post.userHandle}</b></Typography>
<Typography variant="body2" color={"textSecondary"}>{this.formatDate(post.createdAt)}</Typography>
<br />
<Typography variant="body1"><b>{post.microBlogTitle}</b></Typography>
<Typography variant="body2">{post.quoteBody}</Typography>
<br />
<Typography variant="body2">{post.body}</Typography>
<br />
<Typography variant="body2"><b>Topics:</b> {post.microBlogTopics.join("," + " ")}</Typography>
<Typography variant="body2"><b>Topics:</b> {post.microBlogTopics}</Typography>
<br />
<Typography variant="body2" color={"textSecondary"}>Likes {post.likeCount}</Typography>
<Like microBlog = {post.postId}></Like>
<Quote microblog = {post.postId}></Quote>
<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> */}
<Button
onClick={this.handleClickLikeButton}
data-key={post.postId}
disabled={loading}
variant="outlined"
color="primary"
>{
this.state.likes && this.state.likes.includes(post.postId) ? 'Unlike' : 'Like'
}</Button>
<Quote microblog = {post.postId}></Quote>
{/* <button>Quote</button> */}
</CardContent>
</Card>
)
) : (<p>My Posts</p>);
) : (
<p>Loading post...</p>
);
return (
authenticated ?
<Grid container spacing={16}>
authenticated ? (
<Grid container>
<Grid item sm={4} xs={8}>
<Writing_Microblogs />
</Grid>
@@ -80,43 +147,37 @@ class Home extends Component {
{postMarkup}
</Grid>
</Grid>
:
<div>
<div>
<img src={logo} className="app-logo" alt="logo" />
<br/><br/>
<b>Welcome to Twistter!</b>
<br/><br/>
<b>See the most interesting topics people are following right now.</b>
</div>
) : loading ?
(<CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress>)
:
(
<div>
<div>
<img src={logo} className="app-logo" alt="logo" />
<br/><br/>
<b>Welcome to Twistter!</b>
<br/><br/>
<b>See the most interesting topics people are following right now.</b>
</div>
<br/><br/><br/><br/>
<br/><br/><br/><br/>
<div>
<b>Join today or sign in if you already have an account.</b>
<br/><br/>
<form action="./signup">
<button className="authButtons signup">Sign up</button>
</form>
<br/>
<form action="./login">
<button className="authButtons login">Sign in</button>
</form>
</div>
</div>
);
<div>
<b>Join today or sign in if you already have an account.</b>
<br/><br/>
<form action="./signup">
<button className="authButtons signup">Sign up</button>
</form>
<br/>
<form action="./login">
<button className="authButtons login">Sign in</button>
</form>
</div>
</div>
));
}
}
const mapStateToProps = (state) => ({
user: state.user
})
Home.propTypes = {
user: PropTypes.object.isRequired
}
class Quote extends Component {
constructor(props) {
super(props);
@@ -133,10 +194,14 @@ class Quote extends Component {
}
handleSubmitWithoutPost(event) {
const post = {
userImage: "bing-url",
}
const headers = {
headers: { "Content-Type": "application/json" }
};
axios.post(`/quoteWithoutPost/${this.props.microblog}`, headers)
axios.post(`/quoteWithoutPost/${this.props.microblog}`, post, headers)
.then((res) => {
console.log(res.data);
@@ -153,7 +218,7 @@ class Quote extends Component {
}
handleCloseModal() {
this.setState({ showModal: false });
this.setState({ showModal: false, characterCount: 250, value: "" });
}
handleChangeforPost(event) {
@@ -168,7 +233,8 @@ class Quote extends Component {
handleSubmit(event) {
const quotedPost = {
quotePost: this.state.value,
quoteBody: this.state.value,
userImage: "bing-url",
};
const headers = {
headers: { "Content-Type": "application/json" }
@@ -189,14 +255,14 @@ class Quote extends Component {
render() {
return (
<div>
<button onClick={this.handleOpenModal}>Quote with Post</button>
<Button variant="outlined" color="primary" onClick={this.handleOpenModal}>Quote with Post</Button>
<ReactModal
isOpen={this.state.showModal}
style={{content: {height: "50%", width: "25%", marginTop: "auto", marginLeft: "auto", marginRight: "auto", marginBottom : "auto"}}}
>
<div style={{ width: "200px", marginLeft: "50px" }}>
<form>
<textarea
<form style={{ width: "350px"}}>
{/* <textarea
value={this.state.value}
required
maxLength="250"
@@ -208,21 +274,39 @@ class Quote extends Component {
}}
cols={40}
rows={20}
/>
/> */}
<TextField
style={{width: 300}}
value={this.state.value}
label="Write Quoted Post here..."
required
multiline
color="primary"
rows="14"
variant="outlined"
inputProps={{
maxLength: 250
}}
onChange={e => {
this.handleChangeforPost(e);
this.handleChangeforCharacterCount(e);
}}
autoComplete='off'
></TextField>
<div style={{ fontSize: "14px", marginRight: "-100px" }}>
<p2>Characters Left: {this.state.characterCount}</p2>
</div>
<button onClick={this.handleSubmit}>Share Quoted Post</button>
<Button variant="outlined" color="primary" onClick={this.handleSubmit}>Share Quoted Post</Button>
<button onClick={this.handleCloseModal}>Cancel</button>
<Button variant="outlined" color="primary" onClick={this.handleCloseModal}>Cancel</Button>
</form>
</div>
</ReactModal>
<button onClick={this.handleSubmitWithoutPost}>Quote without Post</button>
<Button variant="outlined" color="primary" onClick={this.handleSubmitWithoutPost}>Quote without Post</Button>
</div>
)
@@ -234,21 +318,35 @@ class Like extends Component {
constructor(props) {
super(props)
this.state = {
like: false
num : this.props.count,
}
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
this.setState({
like: localStorage.getItem(this.props.microBlog + this.props.name) === "false"
})
}
handleClick(){
this.setState({
like: !this.state.like
});
localStorage.setItem(this.props.microBlog + this.props.name, this.state.like.toString())
if(this.state.like == false)
{
this.setState(() => {
return {num: this.state.num + 1}
});
axios.get(`/like/${this.props.microBlog}`)
.then((res) => {
console.log(res.data);
@@ -259,6 +357,9 @@ class Like extends Component {
}
else
{
this.setState(() => {
return {num: this.state.num - 1}
});
axios.get(`/unlike/${this.props.microBlog}`)
.then((res) => {
console.log(res.data);
@@ -267,12 +368,37 @@ class Like extends Component {
console.log(err);
})
}
}
/* componentDidMount() {
axios.get(`/checkforLikePost/${this.props.microBlog}`)
.then((res) => {
this.setState({
like2: res.data
})
console.log(res.data);
})
.catch((err) => {
console.log(err)
})
if (this.state.like2 === this.state.like)
{
this.setState({
like: false
})
}
} */
render() {
const label = this.state.like ? 'Unlike' : 'Like'
return(
<div>
<Typography variant="body2" color={"textSecondary"}>Likes {this.state.num}</Typography>
<button onClick={this.handleClick}>{label}</button>
</div>
)
@@ -280,4 +406,35 @@ class Like extends Component {
}
export default connect(mapStateToProps)(Home);
const mapStateToProps = (state) => ({
user: state.user,
UI: state.UI
})
const mapActionsToProps = {
likePost,
unlikePost,
getLikes
}
Home.propTypes = {
user: PropTypes.object.isRequired,
likePost: PropTypes.func.isRequired,
unlikePost: PropTypes.func.isRequired,
getLikes: PropTypes.func.isRequired,
classes: PropTypes.object.isRequired,
UI: PropTypes.object.isRequired
}
Like.propTypes = {
user: PropTypes.object.isRequired
}
Quote.propTypes = {
user: PropTypes.object.isRequired
}
export default connect(mapStateToProps, mapActionsToProps)(withStyles(styles)(Home, Like, Quote));

View File

@@ -110,7 +110,7 @@ export class Login extends Component {
<Grid item sm>
<img src={logo} className="app-logo" alt="logo" />
<br></br>
<Typography variant="p" className={classes.pageTitle} fontFamily = "Georgia, serif">
<Typography variant="h6" className={classes.pageTitle} fontFamily = "Georgia, serif">
<b>Log in to Twistter</b>
<br></br>
</Typography>
@@ -119,7 +119,7 @@ export class Login extends Component {
<TextField
id="email"
name="email"
label="Email*"
label="Email or Username*"
className={classes.textField}
value={this.state.email}
helperText={errors.email}
@@ -127,6 +127,7 @@ export class Login extends Component {
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<TextField
id="password"
@@ -140,6 +141,7 @@ export class Login extends Component {
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<Button
type="submit"

View File

@@ -1,39 +1,77 @@
import React, { Component } from "react";
// import props
import { TextField, Button } from "@material-ui/core";
// import { TextField, Button } from "@material-ui/core";
import TextField from "@material-ui/core/TextField"
import Grid from "@material-ui/core/Grid";
import Axios from "axios";
import axios from "axios";
import Fuse from "fuse.js";
import { BrowserRouter as Router } from "react-router-dom";
import CircularProgress from "@material-ui/core/CircularProgress";
const fuseOptions = {
shouldSort: true,
threshold: 0.6,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: []
};
let fuse;
export class Search extends Component {
state = {
searchPhase: null,
searchResult: null
handles: [],
// searchPhrase: null,
searchResult: null,
loading: false
};
handleSearch = () => {
console.log(this.state.searchPhase);
Axios.post("/getUserHandles", {
userHandle: this.state.searchPhase
})
.then(res => {
console.log(res);
this.setState({
searchResult: res.data
});
componentDidMount() {
this.setState({loading: true});
axios.get("/getAllHandles")
.then((res) => {
this.setState({
handles: res.data,
loading: false
}, () => {
// console.log(res.data);
fuse = new Fuse(this.state.handles, fuseOptions); // "list" is the item array
})
.catch(err => {
console.log(err);
});
};
})
}
handleInput(event) {
// handleSearch = () => {
// console.log(this.state.searchPhase);
// axios.post("/getUserHandles", {
// userHandle: this.state.searchPhase
// })
// .then(res => {
// console.log(res);
// this.setState({
// searchResult: res.data
// });
// })
// .catch(err => {
// console.log(err);
// });
// };
handleChange = (event) => {
let result = fuse.search(event.target.value);
let parsed = [];
result.forEach((res) => {
// console.log(res)
parsed.push(this.state.handles[res])
})
this.setState({
searchPhase: event.target.value
});
console.log(this.state.searchPhase);
searchResult: parsed.length !== 0 ? parsed : "No Results"
})
}
handleRedirect() {
@@ -41,38 +79,50 @@ export class Search extends Component {
}
render() {
let resultMarkup = this.state.searchResult ? (
<Router>
<div>
<a href={`/user/${this.state.searchResult}`}>
{this.state.searchResult}
</a>
</div>
</Router>
) : (
// console.log(this.state.searchResult)
<p> No result </p>
);
let resultMarkup = this.state.searchResult && this.state.searchResult !== "No Results" ? (
this.state.searchResult.map(res =>
<Router key={res}>
<div>
<a href={`/user/${res}`}>
{res}
</a>
</div>
</Router>
)
)
:
this.state.searchResult === "No Results" ?
(
<p> No results </p>
)
:
(
null
)
return (
<Grid>
this.state.loading
?
<CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress>
:
<Grid>
<TextField
id="standard-required"
label="Search"
defaultValue="username"
margin="normal"
value={this.state.searchPhase}
onChange={event => this.handleInput(event)}
/>
<Grid>
<TextField
id="standard-required"
label="Username"
margin="normal"
// value={this.state.searchPhrase}
onChange={this.handleChange}
/>
</Grid>
<Grid>
{/* <Button color="primary" onClick={this.handleSearch}>
Search
</Button> */}
</Grid>
<Grid>{resultMarkup}</Grid>
</Grid>
<Grid>
<Button color="primary" onClick={this.handleSearch}>
Search
</Button>
</Grid>
<Grid>{resultMarkup}</Grid>
</Grid>
);
}
}

View File

@@ -122,6 +122,7 @@ export class Signup extends Component {
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<TextField
id="email"
@@ -134,6 +135,7 @@ export class Signup extends Component {
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<TextField
id="password"
@@ -147,6 +149,7 @@ export class Signup extends Component {
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<TextField
id="confirmPassword"
@@ -160,6 +163,7 @@ export class Signup extends Component {
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<br></br>
<br></br>

View File

@@ -0,0 +1,658 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import _ from "underscore";
// Material UI
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import Card from '@material-ui/core/Card';
import CircularProgress from '@material-ui/core/CircularProgress';
import Fab from '@material-ui/core/Fab';
import Grid from '@material-ui/core/Grid';
import Popover from '@material-ui/core/Popover';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';
import withStyles from '@material-ui/core/styles/withStyles';
// Material UI Icons
import AddCircleIcon from '@material-ui/icons/AddBox';
import CheckMarkIcon from '@material-ui/icons/Check';
import ErrorIcon from '@material-ui/icons/ErrorOutline';
import SendIcon from '@material-ui/icons/Send';
// Redux
import { connect } from 'react-redux';
import {
getDirectMessages,
createNewDirectMessage,
getNewDirectMessages,
reloadDirectMessageChannels,
sendDirectMessage
} from '../redux/actions/dataActions';
const styles = {
pageContainer: {
minHeight: 'calc(100vh - 50px - 60px)'
},
sidePadding: {
maxWidth: 350
},
dmList: {
width: 300,
marginLeft: 15
},
dmItemsUpper: {
marginBottom: 1,
// height: 'calc(100vh - 50px - 142px)',
minHeight: 100,
maxHeight: 'calc(100vh - 50px - 142px)',
overflow: "auto"
},
dmItemsLower: {
},
dmItemUsernameSelected: {
fontSize: 20,
color: 'white'
},
dmItemUsernameUnselected: {
fontSize: 20,
color: '#1da1f2'
},
dmItemTimeSelected: {
color: '#D6D6D6',
fontSize: 12,
float: 'right',
marginRight: 5,
marginTop: 5
},
dmItemTimeUnselected: {
color: 'black',
fontSize: 12,
float: 'right',
marginRight: 5,
marginTop: 5
},
dmRecentMessageSelected: {
wordBreak: "break-all",
color: '#D6D6D6'
},
dmRecentMessageUnselected: {
wordBreak: "break-all",
color: 'black'
},
dmListItemContainer: {
height: 100
},
dmListLayoutContainer: {
height: "100%"
},
dmListRecentMessage: {
marginLeft: 10,
marginRight: 10
},
dmListTextLayout: {
height: 30
},
dmCardUnselected: {
fontSize: 20,
backgroundColor: '#FFFFFF',
width: 300
},
dmCardSelected: {
fontSize: 20,
backgroundColor: '#1da1f2',
width: 300
},
messagesGrid: {
// // margin: "auto"
// height: "auto",
// width: "auto"
},
messagesBox: {
width: 450
},
messagesContainer: {
height: 'calc(100vh - 50px - 110px)',
overflow: 'auto',
width: 450,
marginLeft: 2,
marginRight: 17
},
fromMessage: {
minWidth: 150,
maxWidth: 350,
minHeight: 40,
marginRight: 2,
marginTop: 2,
marginBottom: 10,
backgroundColor: '#008394',
color: '#FFFFFF',
float: 'right'
},
toMessage: {
minWidth: 150,
maxWidth: 350,
minHeight: 40,
marginLeft: 15,
marginTop: 2,
marginBottom: 10,
backgroundColor: '#008394',
color: '#FFFFFF',
float: 'left'
},
messageContent: {
// maxWidth: 330,
// width: 330,
wordBreak: "break-all",
textAlign: 'left',
marginLeft: 5,
marginRight: 5
},
messageTime: {
color: '#D6D6D6',
textAlign: 'left',
marginLeft: 5,
fontSize: 12
},
writeMessage: {
backgroundColor: '#FFFFFF',
boxShadow: '0px 0px 5px 0px grey',
width: 450
},
messageTextField: {
width: 388
},
messageButton: {
backgroundColor: '#1da1f2',
marginTop: 8,
marginLeft: 2
},
loadingUsernameChecks: {
height: 55,
width: 55,
marginLeft: 5
},
errorIcon: {
height: 55,
width: 55,
marginLeft: 5,
color: '#ff3d00'
},
checkMarkIcon: {
height: 55,
width: 55,
marginLeft: 5,
color: '#1da1f2'
},
createButton: {
// textAlign: "center",
// display: "block",
marginLeft: 96,
marginRight: 96,
position: "relative"
}
};
export class directMessages extends Component {
constructor() {
super();
this.state = {
hasChannelSelected: false,
selectedChannel: null,
dmData: null,
anchorEl: null,
createDMUsername: '',
usernameValid: false,
// message: '',
drafts: {},
errors: null
};
}
componentDidUpdate() {
if (this.state.hasChannelSelected) {
document.getElementById('messagesContainer').scrollTop = document.getElementById(
'messagesContainer'
).scrollHeight;
}
}
componentDidMount() {
this.props.getDirectMessages();
// this.updatePage();
}
// Updates the state whenever redux is updated
componentWillReceiveProps(nextProps) {
if (nextProps.directMessages && !_.isEqual(nextProps.directMessages, this.state.dmData)) {
this.setState({ dmData: nextProps.directMessages}, () => {
if (this.state.selectedChannel) {
this.state.dmData.forEach((channel) => {
if (channel.dmId === this.state.selectedChannel.dmId) {
this.setState({
selectedChannel: channel
});
}
});
}
});
}
}
updatePage = async() => {
while (true) {
await this.sleep(15000);
// console.log("getting new DMs");
this.props.getNewDirectMessages();
}
}
sleep = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Handles selecting different DM channels
handleClickChannel = (event) => {
this.setState({
hasChannelSelected: true
});
const dmItemsUpper = document.getElementById("dmItemsUpper");
let target = event.target;
let dmChannelKey;
// Determine which DM channel was clicked by finding the data-key.
// A while loop is necessary, because the user can click on any part of the
// DM list item. dmItemsUpper is the list container of the dmItems
while (target !== dmItemsUpper) {
dmChannelKey = target.dataset.key;
if (dmChannelKey) {
break;
} else {
target = target.parentNode;
}
}
// Save the entire DM channel in the state so that it is easier to load the messages
this.state.dmData.forEach((channel) => {
if (channel.dmId === dmChannelKey) {
this.setState({
selectedChannel: channel
});
}
});
};
formatDateToString(dateString) {
let newDate = new Date(Date.parse(dateString));
return newDate.toDateString();
}
formatDateToTimeDiff(dateString) {
return dayjs(dateString).fromNow();
}
shortenText = (text, length) => {
// Shorten the text
let shortened = text.slice(0, length + 1);
// Trim whitespace from the end of the text
if (shortened[shortened.length - 1] === ' ') {
shortened = shortened.trimRight();
}
// Add ... to the end
shortened = `${shortened}...`;
return shortened;
}
handleOpenAddDMPopover = (event) => {
this.setState({
anchorEl: event.currentTarget
});
};
handleCloseAddDMPopover = () => {
this.setState({
anchorEl: null,
createDMUsername: '',
usernameValid: false
});
};
handleChangeAddDMUsername = (event) => {
this.setState({
createDMUsername: event.target.value
});
};
handleClickCreate = () => {
this.props.createNewDirectMessage(this.state.createDMUsername)
.then(() => {
return this.props.reloadDirectMessageChannels();
})
.then(() => {
this.handleCloseAddDMPopover();
return;
})
.catch(() => {
return;
})
}
handleChangeMessage = (event) => {
let drafts = this.state.drafts;
drafts[this.state.selectedChannel.dmId] = event.target.value;
this.setState({
drafts
});
}
handleClickSend = () => {
// console.log(this.state.drafts[this.state.selectedChannel.dmId]);
let drafts = this.state.drafts;
if (this.state.hasChannelSelected && drafts[this.state.selectedChannel.dmId]) {
this.props.sendDirectMessage(this.state.selectedChannel.recipient, drafts[this.state.selectedChannel.dmId]);
drafts[this.state.selectedChannel.dmId] = null;
this.setState({
drafts
});
}
}
render() {
const { classes, user: { credentials: { dmEnabled } } } = this.props;
const loadingDirectMessages = this.props.UI.loading2;
const creatingDirectMessage = this.props.UI.loading3;
const sendingDirectMessage = this.props.UI.loading4;
let errors = this.props.UI.errors ? this.props.UI.errors : {};
dayjs.extend(relativeTime);
// Used for the add button on the dmList
const open = Boolean(this.state.anchorEl);
const id = open ? 'simple-popover' : undefined;
let dmListMarkup = this.state.dmData ? (
this.state.dmData.map((channel) => (
<Card
onClick={this.handleClickChannel}
key={channel.dmId}
data-key={channel.dmId}
className={
this.state.selectedChannel && this.state.selectedChannel.dmId === channel.dmId ? classes.dmCardSelected : classes.dmCardUnselected
}
>
<Box className={classes.dmListItemContainer}>
<Grid container direction="column" className={classes.dmListLayoutContainer} spacing={1}>
<Grid item>
<Grid container className={classes.dmListTextLayout}>
<Grid item sm />
<Grid item sm>
<Typography
className={
this.state.selectedChannel && this.state.selectedChannel.dmId === channel.dmId ? (
classes.dmItemUsernameSelected
) : (
classes.dmItemUsernameUnselected
)
}
>
{channel.recipient}
</Typography>
</Grid>
<Grid item sm>
<Typography
className={
this.state.selectedChannel && this.state.selectedChannel.dmId === channel.dmId ? (
classes.dmItemTimeSelected
) : (
classes.dmItemTimeUnselected
)
}
>
{channel.recentMessageTimestamp ? (
this.formatDateToTimeDiff(channel.recentMessageTimestamp)
) : null}
</Typography>
</Grid>
</Grid>
</Grid>
<Grid item className={classes.dmListRecentMessage}>
<Typography
className={
this.state.selectedChannel && this.state.selectedChannel.dmId === channel.dmId ? (
classes.dmRecentMessageSelected
) : (
classes.dmRecentMessageUnselected
)
}
>
{
!channel.recentMessage ?
'No messages'
:
channel.recentMessage.length > 65 ?
this.shortenText(channel.recentMessage, 65)
:
channel.recentMessage
}
</Typography>
</Grid>
</Grid>
</Box>
</Card>
))
) : (
<p>You don't have any DMs yet</p>
)
let messagesMarkup =
this.state.selectedChannel !== null ? this.state.selectedChannel.messages.length > 0 ? (
this.state.selectedChannel.messages.map((messageObj) => (
<Grid item key={messageObj.messageId}>
<Card
className={
messageObj.author === this.state.selectedChannel.recipient ? (
classes.toMessage
) : (
classes.fromMessage
)
}
>
<Typography className={classes.messageContent}>{messageObj.message}</Typography>
<Typography className={classes.messageTime}>
{this.formatDateToString(messageObj.createdAt)}
</Typography>
</Card>
</Grid>
))
) : (
<p>No DMs here</p>
) : (
<p>Select a DM channel</p>
);
let addDMMarkup = (
<div>
<AddCircleIcon
style={{
color: '#1da1f2',
height: 82,
width: 82,
marginTop: 9,
cursor: 'pointer'
}}
aria-describedby={id}
onClick={this.handleOpenAddDMPopover}
/>
<Popover
id={id}
open={open}
anchorEl={this.state.anchorEl}
onClose={this.handleCloseAddDMPopover}
anchorOrigin={{
vertical: 'center',
horizontal: 'center'
}}
transformOrigin={{
vertical: 'top',
horizontal: 'center'
}}
>
<Box
style={{
height: 200,
width: 400
}}
>
<Grid container>
<Grid item sm />
<Grid item style={{ height: 200, width: 285 }}>
<Grid container direction="column" spacing={2}>
<Grid item>
<Typography style={{ marginTop: 15 }}>
Who would you like to start a DM with?
</Typography>
</Grid>
<Grid item>
<TextField
onChange={this.handleChangeAddDMUsername}
value={this.state.createDMUsername}
label="Username"
variant="outlined"
helperText={errors.createDirectMessage}
error={errors.createDirectMessage ? true : false}
style={{
width: 265,
marginRight: 10,
marginLeft: 10,
textAlign: 'center',
}}
/>
</Grid>
<Grid item>
<Button
className={classes.createButton}
variant="outlined"
color="primary"
onClick={this.handleClickCreate}
disabled={
creatingDirectMessage ||
this.state.createDMUsername === ""
}
>
Create
{creatingDirectMessage &&
<CircularProgress size={30} style={{position: "absolute"}}/>
// Won't accept classes style for some reason
}
</Button>
</Grid>
</Grid>
</Grid>
<Grid item sm />
</Grid>
</Box>
</Popover>
</div>
);
return (
loadingDirectMessages ? <CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress> :
(dmEnabled !== undefined && dmEnabled !== null && !dmEnabled ? <Typography>Oops! It looks like you have DMs disabled. You can enable them on the Edit Profile page.</Typography> :
<Grid container className={classes.pageContainer}>
<Grid item className={classes.sidePadding} sm />
<Grid item className={classes.dmList}>
<Grid container direction="column">
<Grid item className={classes.dmItemsUpper} id="dmItemsUpper">
{dmListMarkup}
</Grid>
<Grid item className={classes.dmItemsLower}>
<Card key="5555" data-key="5555" className={classes.dmCardUnselected}>
<Box className={classes.dmListItemContainer}>
{addDMMarkup}
</Box>
</Card>
</Grid>
</Grid>
</Grid>
<Grid item className={classes.messagesGrid} sm>
<Box>
{this.state.hasChannelSelected && (
<Card className={classes.messagesBox}>
<Box className={classes.messagesContainer} id="messagesContainer">
<Grid container direction="column">
{messagesMarkup}
</Grid>
</Box>
<Box className={classes.writeMessage}>
<TextField
className={classes.messageTextField}
variant="outlined"
multiline
rows={2}
margin="dense"
value={this.state.drafts[this.state.selectedChannel.dmId] ? this.state.drafts[this.state.selectedChannel.dmId] : ""}
onChange={this.handleChangeMessage}
/>
<Fab
className={classes.messageButton}
onClick={this.handleClickSend}
disabled={
sendingDirectMessage ||
!this.state.drafts[this.state.selectedChannel.dmId] ||
this.state.drafts[this.state.selectedChannel.dmId] === ""
}
>
<SendIcon style={{ color: '#FFFFFF' }} />
{
sendingDirectMessage &&
<CircularProgress size={30} style={{position: "absolute"}}/>
// Won't accept classes style for some reason
}
</Fab>
</Box>
</Card>
)}
{!this.state.hasChannelSelected &&
this.state.dmData && <Typography>Select a DM on the left</Typography>}
</Box>
</Grid>
<Grid item className={classes.sidePadding} sm />
</Grid>
)
);
}
}
directMessages.propTypes = {
classes: PropTypes.object.isRequired,
getDirectMessages: PropTypes.func.isRequired,
createNewDirectMessage: PropTypes.func.isRequired,
getNewDirectMessages: PropTypes.func.isRequired,
reloadDirectMessageChannels: PropTypes.func.isRequired,
sendDirectMessage: PropTypes.func.isRequired,
user: PropTypes.object.isRequired,
UI: PropTypes.object.isRequired
};
const mapStateToProps = (state) => ({
user: state.user,
UI: state.UI,
directMessages: state.data.directMessages
});
const mapActionsToProps = {
getDirectMessages,
createNewDirectMessage,
getNewDirectMessages,
reloadDirectMessageChannels,
sendDirectMessage
};
export default connect(mapStateToProps, mapActionsToProps)(withStyles(styles)(directMessages));

View File

@@ -1,17 +1,28 @@
import React, { Component } from "react";
import { Link } from 'react-router-dom';
import axios from "axios";
import PropTypes from "prop-types";
// TODO: Add a read-only '@' in the left side of the handle input
// TODO: Add a cancel button, that takes the user back to their profile page
import noImage from '../images/no-img.png';
// Material-UI stuff
import Box from "@material-ui/core/Box"
import Button from "@material-ui/core/Button";
import { Link } from 'react-router-dom';
import CircularProgress from "@material-ui/core/CircularProgress";
import Grid from "@material-ui/core/Grid";
import Popover from "@material-ui/core/Popover";
import TextField from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography";
import withStyles from "@material-ui/core/styles/withStyles";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Switch from "@material-ui/core/Switch";
import IconButton from "@material-ui/core/IconButton";
import EditIcon from "@material-ui/icons/Edit";
import Tooltip from "@material-ui/core/Tooltip";
// Redux stuff
import { connect } from "react-redux";
import { uploadImage } from "../redux/actions/userActions";
const styles = {
form: {
@@ -28,34 +39,77 @@ const styles = {
positon: "relative",
marginBottom: 30
},
box: {
position: "relative"
},
back: {
float: "left",
marginLeft: 15
},
delete: {
float: "right",
marginRight: 15
},
progress: {
position: "absolute"
},
uploadProgress: {
position: "absolute",
marginLeft: -155,
marginTop: 95
},
popoverBackground: {
marginTop: "-100px",
width: "calc(100vw)",
height: 'calc(100vh + 100px)',
backgroundColor: "gray",
position: "absolute",
opacity: "70%"
}
};
export class edit extends Component {
export class editProfile extends Component {
// mapReduxToState = (credentials) => {
// this.setState({
// imageUrl: credentials.imageUrl ? credentials.imageUrl : noImage,
// firstName: credentials.firstName ? credentials.firstName : '',
// lastName: credentials.lastName ? credentials.lastName : '',
// email: credentials.email ? credentials.email : 'error, email doesn\'t exist',
// handle: credentials.handle ? credentials.handle : 'error, handle doesn\'t exist',
// bio: credentials.bio ? credentials.bio : ''
// });
// };
// Runs as soon as the page loads.
// Sets the default values of all the textboxes to the data
// that is stored in the database for the user.
componentDidMount() {
// const { credentials } = this.props;
// console.log(this.props.user);
// this.mapReduxToState(credentials);
this.setState({pageLoading: true})
axios
.get("/getProfileInfo")
.then((res) => {
// Need to have the ternary if statements, because react throws an error if
// any of the res.data keys are undefined
this.setState({
firstName: res.data.firstName,
lastName: res.data.lastName,
imageUrl: res.data.imageUrl,
firstName: res.data.firstName ? res.data.firstName : "",
lastName: res.data.lastName ? res.data.lastName : "",
email: res.data.email,
handle: res.data.handle,
bio: res.data.bio
bio: res.data.bio ? res.data.bio : "",
dmEnabled: res.data.dmEnabled === false ? false : true,
pageLoading: false
});
})
.catch((err) => {
console.error(err);
if (err.response.status === 403) {
alert("You are not logged in");
// TODO: Redirect them, to the profile they are trying to edit
// If they are on /itsjimmy/edit, they will be redirected to /itsjimmy
this.props.history.push('../');
// This user is not logged in
this.props.history.push('/');
}
});
}
@@ -64,12 +118,17 @@ export class edit extends Component {
constructor() {
super();
this.state = {
imageUrl: "",
firstName: "",
lastName: "",
email: "",
handle: "",
bio: "",
dmEnabled: false,
togglingDirectMessages: false,
anchorEl: null,
loading: false,
pageLoading: false,
errors: {}
};
}
@@ -104,11 +163,11 @@ export class edit extends Component {
this.setState({
loading: false
});
// this.props.history.push('/');
// TODO: Need to redirect user to their profile page
this.props.history.push('/user');
})
.catch((err) => {
console.log(err);
// TODO: Should redirect to login page if they get a 403
this.setState({
errors: err.response.data,
loading: false
@@ -129,136 +188,324 @@ export class edit extends Component {
});
};
handleDMSwitch = () => {
let enable;
if (this.state.dmEnabled) {
enable = {enable: false};
} else {
enable = {enable: true};
}
this.setState({
dmEnabled: enable.enable,
togglingDirectMessages: true
});
axios.post("/dms/toggle", enable)
.then(() => {
this.setState({
togglingDirectMessages: false
});
})
}
handleImageChange = (event) => {
if (event.target.files[0]) {
const image = event.target.files[0];
const formData = new FormData();
formData.append('image', image, image.name);
this.props.uploadImage(formData);
}
}
handleEditPicture = () => {
const fileInput = document.getElementById('imageUpload');
fileInput.click();
}
// logging = () => {
// console.log(this.state);
// console.log(this.props);
// this.mapReduxToState(this.props.credentials);
// }
handleOpenConfirmDelete = (event) => {
this.setState({
// anchorEl: event.currentTarget
anchorEl: document.getElementById("container-grid")
});
};
handleCloseConfirmDelete = () => {
this.setState({
anchorEl: null,
createDMUsername: ''
});
};
render() {
const { classes } = this.props;
const uploading = this.props.UI.loading;
const { errors, loading } = this.state;
let imageMarkup = this.props.user.credentials.imageUrl ? (
<Box
// className={classes.box}
>
<img
src={this.props.user.credentials.imageUrl}
height="250"
width="250"
className={classes.box}/>
{uploading && (
<CircularProgress size={60} className={classes.uploadProgress} />
)}
</Box>
) : (
<Box
// className={classes.box}
>
<img
src={noImage}
height="250"
width="250"
className={classes.box}/>
{uploading && (
<CircularProgress size={60} className={classes.uploadProgress} />
)}
</Box>
)
// Used for the delete button
const open = Boolean(this.state.anchorEl);
const id = open ? 'simple-popover' : undefined;
return (
<Grid container className={classes.form}>
<Grid item sm />
<Grid item sm>
<Typography variant="h2" className={classes.pageTitle}>
Edit Profile
</Typography>
<form noValidate onSubmit={this.handleSubmit}>
<Grid container className={classes.form} spacing={4}>
<Grid item sm>
<TextField
id="firstName"
name="firstName"
label="First Name"
className={classes.textField}
value={this.state.firstName}
helperText={errors.firstName}
error={errors.firstName ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
/>
</Grid>
<Grid item sm>
<TextField
id="lastName"
name="lastName"
label="Last Name"
className={classes.textField}
value={this.state.lastName}
helperText={errors.lastname}
error={errors.lastName ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
/>
</Grid>
</Grid>
<TextField
id="email"
name="email"
label="Email*"
className={classes.textField}
value={this.state.email}
disabled
helperText="(disabled)"
// INFO: These will be uncommented if changing emails is allowed
// helperText={errors.email}
// error={errors.email ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
/>
<TextField
id="handle"
name="handle"
label="Handle*"
className={classes.textField}
value={this.state.handle}
disabled
helperText="(disabled)"
// INFO: These will be uncommented if changing usernames is allowed
// helperText={errors.handle}
// error={errors.handle ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
/>
<TextField
id="bio"
name="bio"
label="Bio"
className={classes.textField}
value={this.state.bio}
helperText={errors.bio}
error={errors.bio ? true : false}
multiline
rows="8"
variant="outlined"
onChange={this.handleChange}
fullWidth
/>
this.state.pageLoading ?
<CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress>
:
<Grid container className={classes.form} id="container-grid">
<Grid item sm >
<Button
type="submit"
variant="contained"
variant="outlined"
color="primary"
className={classes.button}
disabled={loading}
//component={ Link }
//to='/user'
>
Submit
{loading && (
<CircularProgress size={30} className={classes.progress} />
)}
</Button>
<br />
<Button
//variant="contained"
color="primary"
className={classes.button}
// className={classes.button}
disabled={loading || uploading}
className={classes.back}
component={ Link }
to='/user'
>
Back to Profile
</Button>
<br />
</Grid>
<Grid item sm>
<Typography variant="h2" className={classes.pageTitle}>
Edit Profile
</Typography>
<form noValidate onSubmit={this.handleSubmit}>
{imageMarkup}
<input type="file" id="imageUpload" onChange={this.handleImageChange} hidden = "hidden"/>
<Tooltip title="Edit profile picture" placement="top">
<IconButton onClick={this.handleEditPicture} className="button">
<EditIcon color="primary"/>
</IconButton></Tooltip>
<Grid container className={classes.form} spacing={4}>
<Grid item sm>
<TextField
id="firstName"
name="firstName"
label="First Name"
className={classes.textField}
value={this.state.firstName}
helperText={errors.firstName}
error={errors.firstName ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
</Grid>
<Grid item sm>
<TextField
id="lastName"
name="lastName"
label="Last Name"
className={classes.textField}
value={this.state.lastName}
helperText={errors.lastname}
error={errors.lastName ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
</Grid>
</Grid>
<TextField
id="email"
name="email"
label="Email*"
className={classes.textField}
value={this.state.email}
disabled
helperText="(disabled)"
// INFO: These will be uncommented if changing emails is allowed
// helperText={errors.email}
// error={errors.email ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<TextField
id="handle"
name="handle"
label="Handle*"
className={classes.textField}
value={"@" + this.state.handle}
disabled
helperText="(disabled)"
// INFO: These will be uncommented if changing usernames is allowed
// helperText={errors.handle}
// error={errors.handle ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<TextField
id="bio"
name="bio"
label="Bio"
className={classes.textField}
value={this.state.bio}
helperText={errors.bio}
error={errors.bio ? true : false}
multiline
rows="8"
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<FormControlLabel
control={
<Switch
color="primary"
disabled={this.state.togglingDirectMessages}
checked={this.state.dmEnabled}
onChange={this.handleDMSwitch}
/>
}
label="Enable Direct Messages"
/>
<br></br>
<Button
type="submit"
variant="contained"
color="primary"
className={classes.button}
disabled={loading}
//component={ Link }
//to='/user'
>
Submit
{loading && (
<CircularProgress size={30} className={classes.progress} />
)}
</Button>
</form>
</Grid>
<Grid item sm>
<Button
variant="contained"
variant="outlined"
color="secondary"
className={classes.button}
component={ Link }
to='/delete'
className={classes.delete}
onClick={this.handleOpenConfirmDelete}
>
Delete Account
</Button>
</form>
</Grid>
<Box hidden={!Boolean(this.state.anchorEl)} className={classes.popoverBackground}></Box>
<Popover
id={id}
open={open}
anchorEl={this.state.anchorEl}
onClose={this.handleCloseConfirmDelete}
anchorOrigin={{
vertical: 'center',
horizontal: 'center'
}}
transformOrigin={{
vertical: 'top',
horizontal: 'center'
}}
style={{
marginTop: "-200px"
}}
>
<Box
style={{
height: 200,
width: 400
}}
>
<Grid container direction="column" spacing={3}>
<Grid item>
<Typography style={{marginTop: 30, marginLeft: 50, marginRight: 50, textAlign: "center", fontSize: 24}}>Are you sure you want to delete your account?</Typography>
</Grid>
<Grid item>
<Button
color="secondary"
variant="contained"
component={ Link }
to='/delete'
style={{
marginBottom: "-40px",
marginLeft: 10,
width: 90
}}
>
Yes
</Button>
<Button
color="primary"
variant="outlined"
onClick={this.handleCloseConfirmDelete}
style={{
marginBottom: "-40px",
marginLeft: 195
}}
>
Cancel
</Button>
</Grid>
</Grid>
</Box>
</Popover>
</Grid>
<Grid item sm />
</Grid>
);
}
}
edit.propTypes = {
classes: PropTypes.object.isRequired
const mapStateToProps = (state) => ({
user: state.user,
UI: state.UI,
// credentials: state.user.credentials
});
const mapActionsToProps = { uploadImage }
editProfile.propTypes = {
uploadImage: PropTypes.func.isRequired,
classes: PropTypes.object.isRequired,
user: PropTypes.object.isRequired,
UI: PropTypes.object.isRequired
};
export default withStyles(styles)(edit);
// export default withStyles(styles)(edit);
export default connect(mapStateToProps, mapActionsToProps)(withStyles(styles)(editProfile));

View File

@@ -7,6 +7,8 @@ import axios from "axios";
// Material UI and React Router
import { makeStyles, styled } from "@material-ui/core/styles";
import withStyles from "@material-ui/core/styles/withStyles";
import { Link } from "react-router-dom";
import Card from "@material-ui/core/Card";
import CardMedia from "@material-ui/core/CardMedia";
@@ -19,6 +21,7 @@ import Typography from "@material-ui/core/Typography";
import AddCircle from "@material-ui/icons/AddCircle";
import TextField from "@material-ui/core/TextField";
import VerifiedIcon from "@material-ui/icons/CheckSharp";
import DoneIcon from "@material-ui/icons/Done";
// component
import "../App.css";
@@ -30,14 +33,53 @@ const MyChip = styled(Chip)({
color: "primary"
});
const styles = {
button: {
positon: "relative",
float: "left",
marginLeft: 30,
marginTop: 20
},
paper: {
// marginLeft: "10%",
// marginRight: "10%"
},
card: {
marginBottom: 5
},
profileImage: {
marginTop: 20
},
topicsContainer: {
border: "lightgray solid 1px",
marginTop: 20,
paddingTop: 10,
paddingBottom: 10,
height: 300
},
addCircle: {
width: 65,
height: 65,
marginTop: 10
},
username: {
marginBottom: 100
}
};
class user extends Component {
state = {
profile: window.location.pathname.split("/").pop(),
imageUrl: null,
topics: null,
user: null,
following: null
};
constructor() {
super();
this.state = {
profile: window.location.pathname.split("/").pop(),
imageUrl: null,
topics: null,
user: null,
following: null,
posts: null,
myTopics: null
};
}
handleSub = () => {
if (this.state.following === true) {
@@ -88,38 +130,29 @@ class user extends Component {
.get("/user")
.then(res => {
this.setState({
following: res.data.credentials.following.includes(this.state.profile)
following: res.data.credentials.following.includes(
this.state.profile
),
myTopics: res.data.credentials.followedTopics
});
})
.catch(err => console.log(err));
axios
.post("/getOtherUsersPosts", {
handle: this.state.profile
})
.then(res => {
// console.log(res.data);
this.setState({
posts: res.data
});
})
.catch(err => console.log(err));
}
render() {
let profileMarkup = this.state.profile ? (
<div>
<Typography variant="h5">
@{this.state.profile}{" "}
{this.state.verified ? (
<VerifiedIcon style={{ fill: "#1397D5" }} />
) : null}
</Typography>
</div>
) : (
<p>loading username...</p>
);
let topicsMarkup = this.state.topics ? (
this.state.topics.map(
topic => <MyChip label={topic} key={{ topic }.topic.id} /> // console.log({ topic }.topic.id)
)
) : (
<p> loading topics...</p>
);
let imageMarkup = this.state.imageUrl ? (
<img src={this.state.imageUrl} height="150" width="150" />
) : (
<img src={noImage} height="150" width="150" />
);
const { classes } = this.props;
let followMarkup = this.state.following ? (
<Button variant="contained" color="primary" onClick={this.handleSub}>
@@ -130,18 +163,109 @@ class user extends Component {
follow
</Button>
);
let profileMarkup = this.state.profile ? (
<div>
<Typography variant="h5">
@{this.state.profile}{" "}
{this.state.verified ? (
<VerifiedIcon style={{ fill: "#1397D5" }} />
) : null}
</Typography>
{followMarkup}
</div>
) : (
<p>loading username...</p>
);
console.log(this.state.following);
console.log(this.state.topics);
console.log(this.state.myTopics);
let topicsMarkup = this.state.topics ? (
this.state.topics.map(
topic =>
this.state.myTopics ? (
this.state.myTopics.includes(topic) ? (
<MyChip
label={topic}
key={{ topic }.topic.id}
onDelete
deleteIcon={<DoneIcon />}
/>
) : (
<MyChip
label={topic}
key={{ topic }.topic.id}
color="secondary"
/>
)
) : (
<p></p>
)
// topic => <MyChip label={topic} key={{ topic }.topic.id} /> // console.log({ topic }.topic.id)
)
) : (
<p> no topic yet</p>
);
let imageMarkup = this.state.imageUrl ? (
<img src={this.state.imageUrl} height="150" width="150" />
) : (
<img src={noImage} height="150" width="150" />
);
let postMarkup = this.state.posts ? (
this.state.posts.map(post => (
<Card className={classes.card}>
<CardContent>
<Typography>
{this.state.imageUrl ? (
<img src={this.state.imageUrl} height="50" width="50" />
) : (
<img src={noImage} height="50" width="50" />
)}
</Typography>
<Typography variant="h7">
<b>{post.userHandle}</b>
</Typography>
<Typography variant="body2" color={"textSecondary"}>
{post.createdAt}
</Typography>
<br />
<Typography variant="body1">
<b>{post.microBlogTitle}</b>
</Typography>
<Typography variant="body2">{post.quoteBody}</Typography>
<br />
<Typography variant="body2">{post.body}</Typography>
<br />
<Typography variant="body2">
<b>Topics:</b> {post.microBlogTopics}
</Typography>
<br />
<Typography variant="body2" color={"textSecondary"}>
Likes {post.likeCount}
</Typography>
</CardContent>
</Card>
))
) : (
<p>Posts</p>
);
return (
<Grid container spacing={24}>
<Grid item sm={4} xs={8}>
{imageMarkup}
{profileMarkup}
{followMarkup}
{/* {followMarkup} */}
{topicsMarkup}
<br />
</Grid>
<Grid item sm={4} xs={8}>
{postMarkup}
<br />
</Grid>
</Grid>
);
}
@@ -152,7 +276,8 @@ const mapStateToProps = state => ({
});
user.propTypes = {
user: PropTypes.object.isRequired
user: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired
};
export default connect(mapStateToProps)(user);
export default connect(mapStateToProps)(withStyles(styles)(user));

View File

@@ -47,7 +47,7 @@ const styles = {
// marginRight: "10%"
},
card: {
marginBottom: 10
marginBottom: 5
},
profileImage: {
marginTop: 20
@@ -70,12 +70,15 @@ const styles = {
};
class user extends Component {
state = {
profile: null,
imageUrl: null,
topics: null,
newTopic: null
};
constructor() {
super();
this.state = {
profile: null,
imageUrl: null,
topics: null,
newTopic: ""
};
}
handleDelete = topic => {
console.log(topic);
@@ -83,8 +86,16 @@ class user extends Component {
.post(`/deleteTopic`, {
unfollow: topic
})
.then(function() {
location.reload();
.then(() => {
let tempTopics = this.state.topics;
tempTopics.forEach((oldTopic, index) => {
if (oldTopic === topic) {
tempTopics.splice(index, 1);
}
});
this.setState({
topics: tempTopics
});
})
.catch(function(err) {
console.log(err);
@@ -96,8 +107,13 @@ class user extends Component {
.post("/putTopic", {
following: this.state.newTopic
})
.then(function() {
location.reload();
.then(() => {
let tempTopics = this.state.topics;
tempTopics.push(this.state.newTopic);
this.setState({
topics: tempTopics,
newTopic: ""
});
})
.catch(function(err) {
console.log(err);
@@ -131,14 +147,16 @@ class user extends Component {
// console.log(res.data);
this.setState({
posts: res.data
})
this.setState({posts: (this.state.posts).sort((a,b) =>
-a.createdAt.localeCompare(b.createdAt))
})
});
})
.catch(err => console.log(err));
}
formatDate(dateString) {
let newDate = new Date(Date.parse(dateString));
return newDate.toDateString();
}
render() {
const { classes } = this.props;
let authenticated = this.props.user.authenticated;
@@ -161,7 +179,7 @@ class user extends Component {
topic => (
<MyChip
label={topic}
key={topic.id}
key={topic}
onDelete={key => this.handleDelete(topic)}
/>
) // console.log({ topic }.topic.id)
@@ -188,7 +206,7 @@ class user extends Component {
let postMarkup = this.state.posts ? (
this.state.posts.map(post => (
<Card className={classes.card}>
<Card className={classes.card} key={post.postId}>
<CardContent>
<Typography>
{this.state.imageUrl ? (
@@ -197,25 +215,29 @@ class user extends Component {
<img src={noImage} height="50" width="50" />
)}
</Typography>
<Typography variant="h7">
<Typography variant="h6">
<b>{post.userHandle}</b>
</Typography>
<Typography variant="body2" color={"textSecondary"}>
{post.createdAt}
</Typography>
<Typography variant="h7"><b>{post.userHandle}</b></Typography>
<Typography variant="body2" color={"textSecondary"}>{post.createdAt.substring(0,10) +
" " + post.createdAt.substring(11,19)}</Typography>
<br />
<Typography variant="body1">
<b>{post.microBlogTitle}</b>
</Typography>
<Typography variant="body2">{post.quoteBody}</Typography>
<br />
<Typography variant="body2">{post.body}</Typography>
<br />
<Typography variant="body2"><b>Topics:</b> {post.microBlogTopics.join("," + " ")}</Typography>
<Typography variant="body2">
<b>Topics:</b> {post.microBlogTopics}
</Typography>
<br />
<Typography variant="body2" color={"textSecondary"}>Likes {post.likeCount}</Typography>
<Typography variant="body2" color={"textSecondary"}>
Likes {post.likeCount}
</Typography>
</CardContent>
</Card>
))
@@ -229,7 +251,7 @@ class user extends Component {
// showing the logged in users profile, instead of retreiving the
// profile based on the URL entered
let editButtonMarkup = true ? (
<Link to="/edit">
<Link to="/user/edit">
<Button className={classes.button} variant="outlined" color="primary">
Edit Profile
</Button>
@@ -263,7 +285,7 @@ class user extends Component {
<TextField
id="newTopic"
label="new topic"
defaultValue=""
// defaultValue=""
margin="normal"
variant="outlined"
value={this.state.newTopic}
@@ -273,7 +295,7 @@ class user extends Component {
className={classes.addCircle}
color="primary"
// iconStyle={classes.addCircle}
clickable
clickable="true"
onClick={this.handleAddCircle}
cursor="pointer"
/>
@@ -298,7 +320,8 @@ const mapStateToProps = state => ({
});
user.propTypes = {
user: PropTypes.object.isRequired
user: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired
};
export default connect(mapStateToProps)(withStyles(styles)(user));

View File

@@ -89,7 +89,7 @@ export class verify extends Component {
render() {
const { classes } = this.props;
const { errors, loading } = this.state;
const { loading } = this.state;
return (
<Grid container className={classes.form}>

View File

@@ -0,0 +1,146 @@
import {
SET_DIRECT_MESSAGES,
LOADING_UI,
SET_ERRORS,
CLEAR_ERRORS,
SET_LOADING_UI_2,
SET_LOADING_UI_3,
SET_LOADING_UI_4,
SET_NOT_LOADING_UI_2,
SET_NOT_LOADING_UI_3,
SET_NOT_LOADING_UI_4
} from '../types';
import axios from "axios";
// TODO: Tidy up these functions. They shouldn't have all these promises in them.
export const getDirectMessages = () => (dispatch) => {
dispatch({type: SET_LOADING_UI_2});
axios.get('/dms')
.then((res) => {
dispatch({
type: SET_DIRECT_MESSAGES,
payload: res.data.data
});
dispatch({type: SET_NOT_LOADING_UI_2});
dispatch({type: CLEAR_ERRORS});
})
.catch((err) => {
console.error(err);
dispatch({
type: SET_ERRORS,
payload: {
errors: err.response.data.error
}
});
})
}
export const getNewDirectMessages = () => (dispatch) => {
return new Promise((resolve, reject) => {
axios.get('/dms')
.then((res) => {
dispatch({
type: SET_DIRECT_MESSAGES,
payload: res.data.data
});
dispatch({type: SET_NOT_LOADING_UI_2});
dispatch({type: CLEAR_ERRORS});
resolve();
})
.catch((err) => {
console.log(err)
reject(err);
})
})
}
export const reloadDirectMessageChannels = () => (dispatch) => {
return new Promise((resolve, reject) => {
axios.get('/dms')
.then((res) => {
dispatch({
type: SET_DIRECT_MESSAGES,
payload: res.data.data
});
dispatch({type: SET_NOT_LOADING_UI_3});
dispatch({type: CLEAR_ERRORS});
resolve();
})
.catch((err) => {
console.log(err)
reject(err);
})
})
}
export const createNewDirectMessage = (username) => (dispatch) => {
return new Promise((resolve, reject) => {
dispatch({type: SET_LOADING_UI_3});
const data = {
user: username
}
// console.log(username);
axios.post('/dms/new', data)
.then((res) => {
// console.log(res.data);
if (res.data.err) {
dispatch({
type: SET_ERRORS,
payload: {
createDirectMessage: res.data.err
}
});
dispatch({type: SET_NOT_LOADING_UI_3});
} else {
// dispatch(getNewDirectMessages());
// dispatch({type: SET_NOT_LOADING_UI_3});
}
resolve();
})
.catch((err) => {
dispatch({
type: SET_ERRORS,
payload: {
createDirectMessage: err.response.data.error
}
});
dispatch({type: SET_NOT_LOADING_UI_3});
console.log(err.response.data);
reject(err);
})
});
}
export const sendDirectMessage = (user, message) => (dispatch) => {
dispatch({type: SET_LOADING_UI_4});
const data = {
message,
user
};
axios.post('/dms/send', data)
.then((res) => {
// console.log(res);
return axios.get('/dms')
})
.then((res) => {
dispatch({
type: SET_DIRECT_MESSAGES,
payload: res.data.data
});
dispatch({type: SET_NOT_LOADING_UI_4});
dispatch({type: CLEAR_ERRORS});
})
.catch((err) => {
console.log(err);
dispatch({
type: SET_ERRORS,
payload: {
sendDirectMessage: err.response.data
}
})
})
}

View File

@@ -1,18 +1,40 @@
import {SET_USER, SET_ERRORS, CLEAR_ERRORS, LOADING_UI, SET_AUTHENTICATED, SET_UNAUTHENTICATED} from '../types';
import {
SET_USER,
SET_ERRORS,
CLEAR_ERRORS,
LOADING_UI,
// SET_AUTHENTICATED,
SET_UNAUTHENTICATED,
LIKE_POST,
UNLIKE_POST,
SET_LIKES,
LOADING_USER
} from '../types';
import axios from 'axios';
// Saves Authorization in browser local storage and adds it as a header to axios
const setAuthorizationHeader = (token) => {
const FBIdToken = `Bearer ${token}`;
localStorage.setItem('FBIdToken', FBIdToken);
axios.defaults.headers.common['Authorization'] = FBIdToken;
}
// Gets Database info for the logged in user and sets it in Redux
export const getUserData = () => (dispatch) => {
dispatch({ type: LOADING_USER });
axios.get('/user')
.then((res) => {
dispatch({
type: SET_USER,
payload: res.data,
})
});
dispatch({type: CLEAR_ERRORS});
})
.catch((err) => console.error(err));
}
// Sends login data to firebase and sets the user data in Redux
export const loginUser = (loginData, history) => (dispatch) => {
dispatch({ type: LOADING_UI });
axios
@@ -21,7 +43,7 @@ export const loginUser = (loginData, history) => (dispatch) => {
// Save the login token
setAuthorizationHeader(res.data.token);
dispatch(getUserData());
dispatch({ type: CLEAR_ERRORS })
// dispatch({ type: CLEAR_ERRORS })
// Redirects to home page
history.push('/home');
})
@@ -33,6 +55,7 @@ export const loginUser = (loginData, history) => (dispatch) => {
});
};
// Sends signup data to firebase and sets the user data in Redux
export const signupUser = (newUserData, history) => (dispatch) => {
dispatch({ type: LOADING_UI });
axios
@@ -43,7 +66,7 @@ export const signupUser = (newUserData, history) => (dispatch) => {
// Save the signup token
setAuthorizationHeader(res.data.token);
dispatch(getUserData());
dispatch({ type: CLEAR_ERRORS })
// dispatch({ type: CLEAR_ERRORS })
// Redirects to home page
history.push('/home');
})
@@ -55,12 +78,14 @@ export const signupUser = (newUserData, history) => (dispatch) => {
});
};
// Deletes the Authorization header and clears all user data from Redux
export const logoutUser = () => (dispatch) => {
localStorage.removeItem('FBIdToken');
delete axios.defaults.headers.common['Authorization'];
dispatch({ type: SET_UNAUTHENTICATED });
}
export const deleteUser = () => (dispatch) => {
axios
.delete("/delete")
@@ -81,8 +106,65 @@ export const deleteUser = () => (dispatch) => {
dispatch({ type: SET_UNAUTHENTICATED });
}
const setAuthorizationHeader = (token) => {
const FBIdToken = `Bearer ${token}`;
localStorage.setItem('FBIdToken', FBIdToken);
axios.defaults.headers.common['Authorization'] = FBIdToken;
}
export const getLikes = () => (dispatch) => {
axios.get('/likes')
.then((res) => {
dispatch({
type: SET_LIKES,
payload: res.data
})
})
}
export const likePost = (postId, postArray) => (dispatch) => {
postArray.push(postId);
dispatch({
type: LIKE_POST,
payload: {
likes: postArray
}
})
axios.get(`/like/${postId}`)
.then((res) => {
getLikes();
})
}
export const unlikePost = (postId, postArray) => (dispatch) => {
let i;
for (i = 0; i < postArray.length; i++) {
if (postArray[i] === postId) {
postArray.splice(i, 1);
break;
}
}
dispatch({
type: UNLIKE_POST,
payload: {
likes: postArray
}
})
axios.get(`/unlike/${postId}`)
.then((res) => {
getLikes();
})
}
// Sends an image data form to firebase to be uploaded to the user profile
export const uploadImage = (formData) => (dispatch) => {
dispatch({ type: LOADING_UI });
axios.post('/user/image', formData)
.then(() => {
dispatch(getUserData());
// dispatch({ type: CLEAR_ERRORS });
})
.catch(err => {
console.log(err);
})
}

View File

@@ -0,0 +1,17 @@
import {SET_DIRECT_MESSAGES, SET_USERNAME_VALID, SET_USERNAME_INVALID} from '../types';
const initialState = {
directMessages: null,
};
export default function(state = initialState, action) {
switch(action.type) {
case SET_DIRECT_MESSAGES:
return {
...state,
directMessages: action.payload
};
default:
return state;
}
}

View File

@@ -1,7 +1,20 @@
import { SET_ERRORS, CLEAR_ERRORS, LOADING_UI } from '../types';
import {
SET_ERRORS,
CLEAR_ERRORS,
LOADING_UI,
SET_LOADING_UI_2,
SET_LOADING_UI_3,
SET_LOADING_UI_4,
SET_NOT_LOADING_UI_2,
SET_NOT_LOADING_UI_3,
SET_NOT_LOADING_UI_4
} from '../types';
const initialState = {
loading: false,
loading2: false,
loading3: false,
loading4: false,
errors: null
};
@@ -23,7 +36,37 @@ export default function(state = initialState, action) {
return {
...state,
loading: true
}
};
case SET_LOADING_UI_2:
return {
...state,
loading2: true
};
case SET_LOADING_UI_3:
return {
...state,
loading3: true
};
case SET_LOADING_UI_4:
return {
...state,
loading4: true
};
case SET_NOT_LOADING_UI_2:
return {
...state,
loading2: false
};
case SET_NOT_LOADING_UI_3:
return {
...state,
loading3: false
};
case SET_NOT_LOADING_UI_4:
return {
...state,
loading4: false
};
default:
return state;
}

View File

@@ -1,4 +1,17 @@
import {SET_USER, SET_ERRORS, CLEAR_ERRORS, LOADING_UI, SET_AUTHENTICATED, SET_UNAUTHENTICATED} from '../types';
import {
SET_USER,
// SET_ERRORS,
// CLEAR_ERRORS,
// LOADING_UI,
SET_AUTHENTICATED,
SET_UNAUTHENTICATED,
LOADING_USER,
LIKE_POST,
UNLIKE_POST,
SET_LIKES
} from '../types';
const initialState = {
authenticated: false,
@@ -19,9 +32,31 @@ export default function(state = initialState, action) {
return initialState;
case SET_USER:
return {
...state,
authenticated: true,
loading: false,
...action.payload,
};
case LIKE_POST:
return {
...state,
...action.payload
}
case UNLIKE_POST:
return {
...state,
...action.payload
}
case SET_LIKES:
return {
...state,
...action.payload
}
case LOADING_USER:
return {
...state,
loading: true
}
default:
return state;
}

View File

@@ -3,10 +3,22 @@ export const SET_AUTHENTICATED = 'SET_AUTHENTICATED';
export const SET_UNAUTHENTICATED = 'SET_UNAUTHENTICATED';
export const SET_USER = 'SET_USER';
export const LOADING_USER = 'LOADING_USER';
export const LIKE_POST = 'LIKE_POST';
export const UNLIKE_POST = 'UNLIKE_POST';
export const SET_LIKES = 'SET_LIKES';
// UI reducer types
export const SET_ERRORS = 'SET_ERRORS';
export const LOADING_UI = 'LOADING_UI';
export const SET_LOADING_UI_2 = 'SET_LOADING_UI_2';
export const SET_LOADING_UI_3 = 'SET_LOADING_UI_3';
export const SET_LOADING_UI_4 = 'SET_LOADING_UI_4';
export const SET_NOT_LOADING_UI_2 = 'SET_NOT_LOADING_UI_2';
export const SET_NOT_LOADING_UI_3 = 'SET_NOT_LOADING_UI_3';
export const SET_NOT_LOADING_UI_4 = 'SET_NOT_LOADING_UI_4';
export const CLEAR_ERRORS = 'CLEAR_ERRORS';
// Data reducer types
// Data reducer types
export const SET_DIRECT_MESSAGES = 'SET_DIRECT_MESSAGES';
export const SET_USERNAME_VALID = 'SET_USERNAME_VALID';
export const SET_USERNAME_INVALID = 'SET_USERNAME_INVALID';