PROJECT COMPLETED!!!!!

This commit is contained in:
Aaron Sun 2019-12-10 23:41:50 -05:00
parent e3593e2f29
commit db6b147c40
26 changed files with 3590 additions and 608 deletions

View File

@ -1,115 +1,543 @@
/* eslint-disable prefer-arrow-callback */
/* eslint-disable promise/always-return */
const admin = require('firebase-admin');
const { admin, 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.deletePost = (req, res) => {
let posts = db.collection("posts")
.where("userHandle", "==", req.user.handle)
.get()
.then((query) => {
query.forEach((snap) => {
snap.ref.delete();
});
return;
})
};
exports.getallPostsforUser = (req, res) => {
var post_query = admin.firestore().collection("posts");//.where("userHandle", "==", req.user.handle);
post_query.orderBy('createdAt', 'desc').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) {
if(doc.data().userHandle === req.user.handle) {
posts.push(doc.data());
}
});
return res.status(200).json(posts);
let posts = [];
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
posts.sort((a, b) => -a.createdAt.localeCompare(b.createdAt));
return res.status(200).json(posts);
})
.then(function() {
res.status(200).send("Successfully retrieved all user's posts from database.");
return;
return res
.status(200)
.json("Successfully retrieved all user's posts from database.");
})
.catch(function(err) {
res.status(500).send("Failed to retrieve user's posts from database.", err);
return res
.status(500)
.json({message: "Failed to retrieve user's posts from database.", error: err});
});
};
exports.hidePost = (req, res) => {
/* db
.collection("posts")
.doc(${req.params.postId}) */
const postId = req.body.postId;
db.doc(`/posts/${postId}`)
.update({
hidden: true
})
.then(() => {
return res.status(200).json({message: "ok"});
})
.catch((error) => {
return res.status(500).json(error);
})
};
exports.getallPosts = (req, res) => {
var post_query = admin.firestore().collection("posts");
post_query.orderBy('createdAt', 'desc').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);
posts.sort((a, b) => -a.createdAt.localeCompare(b.createdAt));
resolve();
})
.catch(error => {
reject(error);
});
});
// Get all users
var usersPromise = new Promise((resolve, reject) => {
db.collection("users")
.get()
.then(allUsers => {
allUsers.forEach(user => {
users[user.data().handle] = user.data();
});
resolve();
})
.catch(error => {
reject(error);
});
});
// Wait for the two promises
Promise.all([postsPromise, usersPromise])
.then(() => {
let newPosts = [];
// Add the image url of the person who made the post to all of the post objects
posts.forEach(post => {
post.profileImage = users[post.userHandle].imageUrl
? users[post.userHandle].imageUrl
: null;
newPosts.push(post);
});
return res.status(200).json(newPosts);
})
.catch(error => {
return res.status(500).json({ error });
});
};
exports.getAlert = (req, res) => {
var post_query = admin
.firestore()
.collection("posts")
.where("microBlogTitle", "==", "Alert");
post_query
.get()
.then(function(myPosts) {
let posts = [];
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
posts.sort((a, b) => -a.createdAt.localeCompare(b.createdAt));
return res.status(200).json(posts);
})
.then(function() {
res.status(200).send("Successfully retrieved every post from database.");
return;
return res
.status(200)
.json("Successfully retrieved all user's posts from database.");
})
.catch(function(err) {
res.status(500).send("Failed to retrieve posts from database.", err);
return res
.status(500)
.json("Failed to retrieve user's posts from database.", err);
});
};
exports.getOtherUsersPosts = (req, res) => {
var post_query = admin
.firestore()
.collection("posts")
.where("userHandle", "==", req.body.handle);
// post_query += admin
// .firestore()
// .collection("posts")
// .where("microBlogTitle", "==", "Alert").where("userHandle", "==", "Admin");
post_query
.get()
.then(function(myPosts) {
let posts = [];
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
posts.sort((a, b) => -a.createdAt.localeCompare(b.createdAt));
return res.status(200).json(posts);
})
.then(function() {
return res
.status(200)
.json("Successfully retrieved all user's posts from database.");
})
.catch(function(err) {
return res
.status(500)
.json("Failed to retrieve user's posts from database.", err);
});
};
exports.quoteWithPost = (req, res) => {
let quoteData;
const quoteDoc = admin
.firestore()
.collection("quote")
.where("userHandle", "==", req.user.handle)
.where("quoteId", "==", req.params.postId)
.limit(1);
const postDoc = db.doc(`/posts/${req.params.postId}`);
postDoc
.get()
.then(doc => {
if (doc.exists) {
quoteData = doc.data();
return quoteDoc.get();
} else {
return res.status(404).json({ error: "Post not found" });
}
})
.then(data => {
if (data.empty) {
return admin
.firestore()
.collection("quote")
.add({
quoteId: req.params.postId,
userHandle: req.user.handle,
quoteBody: req.body.quoteBody
})
.then(() => {
const post = {
body: quoteData.body,
userHandle: req.user.handle,
quoteBody: req.body.quoteBody,
createdAt: new Date().toISOString(),
userImage: req.body.userImage,
likeCount: 0,
commentCount: 0,
userID: req.user.uid,
microBlogTitle: quoteData.microBlogTitle,
microBlogTopics: quoteData.microBlogTopics,
quoteId: req.params.postId
};
return admin
.firestore()
.collection("posts")
.add(post)
.then(doc => {
doc.update({ postId: doc.id });
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("quoteId", "==", req.params.postId)
.limit(1);
const postDoc = db.doc(`/posts/${req.params.postId}`);
postDoc
.get()
.then(doc => {
if (doc.exists) {
quoteData = doc.data();
return quoteDoc.get();
} else {
return res.status(404).json({ error: "Post not found" });
}
})
.then(data => {
if (data.empty) {
return admin
.firestore()
.collection("quote")
.add({
quoteId: req.params.postId,
userHandle: req.user.handle,
quoteBody: null
})
.then(() => {
const post = {
userHandle: req.user.handle,
body: quoteData.body,
quoteBody: null,
createdAt: new Date().toISOString(),
likeCount: 0,
commentCount: 0,
userID: req.user.uid,
userImage: req.body.userImage,
microBlogTitle: quoteData.microBlogTitle,
microBlogTopics: quoteData.microBlogTopics,
quoteId: req.params.postId
};
return admin
.firestore()
.collection("posts")
.add(post)
.then(doc => {
doc.update({ postId: doc.id });
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" });
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) => {
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 = [];
}
if (likes.includes(postId)) {
return res
.status(400)
.json({ error: "This user has already liked this post" });
}
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) => {
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 = [];
}
if (!likes.includes(postId)) {
return res
.status(400)
.json({ error: "This user hasn't liked this post yet" });
}
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'});
// })
};
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', '==');
};
exports.getFollowedPosts = (req, res) => {
var followers_list = admin.firestore().collection("users").doc(req.user.handle).collection("followedUsers");
var post_query = admin.firestore().collection("posts");
followers_list.get()
.then(function(allFollowers) {
var followers_likedTopics = new Map();
allFollowers.forEach(function(followers) {
followers_likedTopics.set(followers.data().handle, followers.data().followedTopics);
});
post_query.orderBy('createdAt', 'desc').get()
.then(function(allPosts) {
let posts = [];
allPosts.forEach(function(doc) {
if(doc.data().userHandle === req.user.handle) {
posts.push(doc.data());
}
else if(followers_likedTopics.has(doc.data().userHandle)) {
doc.data().microBlogTopics.forEach(function(topic) {
if(followers_likedTopics.get(doc.data().userHandle).includes(topic)) {
posts.push(doc.data());
}
});
}
});
return res.status(200).json(posts);
})
.catch(function(err) {
res.status(500).send("Failed to retrieve any posts.", err);
});
})
.then(function() {
//res.status(200).send("Successfully retrieved all interesting posts from followed users.");
return;
})
.catch(function(err) {
res.status(500).send("Failed to retrieve any posts.", err);
});
admin
.firestore()
.collection("posts")
.where("userHandle", "==", "new user")
.where("microBlogTopics", "==");
};

View File

@ -26,6 +26,41 @@ exports.putTopic = (req, res) => {
});
};
exports.putNewTopic = (req, res) => {
let new_following = [];
let userRef = db.doc(`/users/${req.userData.handle}`);
userRef
.get()
.then(doc => {
let topics = [];
new_following = doc.data().following;
// new_following.push(req.body.following);
new_following.forEach(follow => {
if (follow.handle === req.body.handle) {
// topics = follow.topics;
follow.topics.push(req.body.topic);
}
});
// return res.status(201).json({ new_following });
// add stuff
userRef
.set({ following: new_following }, { merge: true })
.then(doc => {
return res
.status(201)
.json({ message: `Following ${req.body.topic}` });
})
.catch(err => {
return res.status(500).json({ err });
});
return res.status(200).json({ message: "OK" });
})
.catch(err => {
return res.status(500).json({ err });
});
};
exports.getAllTopics = (req, res) => {
admin
.firestore()

File diff suppressed because it is too large Load Diff

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);
@ -70,25 +103,54 @@ app.post("/removeSub", fbAuth, removeSub);
/*------------------------------------------------------------------*
* handlers/post.js *
*------------------------------------------------------------------*/
const { getallPostsforUser, getallPosts, getFollowedPosts, putPost } = require("./handlers/post");
const {
getallPostsforUser,
getallPosts,
putPost,
hidePost,
likePost,
unlikePost,
getLikes,
quoteWithPost,
quoteWithoutPost,
checkforLikePost,
getOtherUsersPosts,
getAlert
} = require("./handlers/post");
app.get("/getallPostsforUser", fbAuth, getallPostsforUser);
app.get("/getallPosts", getallPosts);
app.get("/getFollowedPosts", fbAuth, getFollowedPosts);
//Hides Post
app.post("/hidePost", fbAuth, hidePost);
// 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);
app.get("/getAlert", fbAuth, getAlert);
/*------------------------------------------------------------------*
* handlers/topic.js *
* handlers/topic.js *
*------------------------------------------------------------------*/
const {
putTopic,
getAllTopics,
deleteTopic,
getUserTopics
getUserTopics,
putNewTopic
} = require("./handlers/topic");
// add topic to database
@ -103,4 +165,6 @@ app.post("/deleteTopic", fbAuth, deleteTopic);
// get topic for this user
app.post("/getUserTopics", fbAuth, getUserTopics);
app.post("/putNewTopic", fbAuth, putNewTopic);
exports.api = functions.https.onRequest(app);

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;

View File

@ -3097,6 +3097,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",
@ -3962,6 +3967,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",
@ -7172,6 +7182,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",
@ -9766,6 +9792,11 @@
"resolved": "https://registry.npmjs.org/uid-number/-/uid-number-0.0.6.tgz",
"integrity": "sha1-DqEOgDXo61uOREnwbaHHMGY7qoE="
},
"underscore": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/underscore/-/underscore-1.9.1.tgz",
"integrity": "sha512-5/4etnCkd9c8gwgowi5/om/mYO5ajCaOgdzj/oW+0eQV9WxKBDZw5+ycmKmeaTXjInS/W0BzpGLo2xR2aBwZdg=="
},
"union-value": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz",
@ -9996,6 +10027,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

@ -11,17 +11,20 @@
"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

@ -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,37 @@
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";
import CircularProgress from "@material-ui/core/CircularProgress";
const styles = {
container: {
position: "fixed"
},
form: {
width: "300px",
height: "50px",
marginTop: "180px",
marginLeft: "50px"
},
textField: {
marginBottom: 15
},
progress: {
position: "absolute"
},
button: {
positon: "relative",
marginBottom: 30
}
}
class Writing_Microblogs extends Component {
constructor(props) {
super(props);
@ -10,7 +39,8 @@ class Writing_Microblogs extends Component {
value: "",
title: "",
topics: "",
characterCount: 250
characterCount: 250,
loading: false
};
this.handleChange = this.handleChange.bind(this);
@ -27,7 +57,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,
@ -35,25 +65,58 @@ class Writing_Microblogs extends Component {
microBlogTitle: this.state.title,
microBlogTopics: this.state.topics.split(", ")
};
this.setState({
loading: true
})
const headers = {
headers: { "Content-Type": "application/json" }
};
axios
.post("/putPost", postData, headers)
let postPromise = axios
.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);
// let topicPromises = [];
// postData.microBlogTopics.forEach(topic => {
// topicPromises.push(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: "" });
// topicPromises.push(postPromise);
Promise.all([postPromise])
.then(() => {
this.setState({
value: "",
title: "",
characterCount: 250,
topics: "",
loading: false
});
})
.catch((error) => {
console.log(error);
})
}
handleChangeforPost(event) {
this.setState({ value: event.target.value });
}
@ -64,65 +127,69 @@ 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
className={classes.button}
onClick={this.handleSubmit}
disabled={this.state.loading}
variant="outlined"
color="primary"
>
Share Post
{this.state.loading && <CircularProgress size={30} className={classes.progress} />}
</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

@ -1,100 +1,267 @@
/* eslint-disable */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import axios from 'axios';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
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 { makeStyles, styled } from '@material-ui/core/styles';
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';
import logo from '../images/twistter-logo.png';
import noImage from '../images/no-img.png';
import Writing_Microblogs from '../Writing_Microblogs';
import "../App.css";
import logo from "../images/twistter-logo.png";
import noImage from "../images/no-img.png";
import Writing_Microblogs from "../Writing_Microblogs";
import ReactModal from "react-modal";
const MyCardContent = styled(CardContent)({
textAlign: "left"
});
// Redux
import { likePost, unlikePost, getLikes } from "../redux/actions/userActions";
const styles = {
card: {
marginBottom: 5
}
};
class Home extends Component {
state = {};
state = {
likes: [],
loading: false,
following: null,
topics: null
};
componentDidMount() {
axios
.get("/getFollowedPosts")
this.setState({ loading: true });
let userPromise = axios
.get("/user")
.then(res => {
console.log(res.data);
console.log(res.data.credentials.following);
let list = [];
res.data.credentials.following.forEach(element => {
list.push(element.handle);
});
this.setState({
posts: res.data
})
following: list,
topics: res.data.credentials.followedTopics
});
})
.catch(err => console.log(err));
let allPosts;
let postPromise = axios
.get("/getallPosts")
.then(res => {
// console.log(res.data);
// this.setState({
// posts: res.data
// });
allPosts = res.data;
// console.log(allPosts)
return axios.get("/getAlert")
})
.then((res) => {
// console.log(res.data)
// res.data.forEach((adminAlert) => {
// allPosts.push(adminAlert);
// })
this.setState({
posts: allPosts
});
})
.catch(err => console.log(err));
Promise.all([userPromise, postPromise])
.then(() => {
this.setState({
loading: false
});
})
.catch(error => {
console.log(error);
});
this.props.getLikes();
}
componentWillReceiveProps(nextProps) {
this.setState({
likes: nextProps.user.likes
});
}
flagPost = (event) => {
// Flags a post
let postId = event.target.dataset.key ? event.target.dataset.key : event.target.parentNode.dataset.key;
console.log(postId);
axios.post(`/hidePost`, {postId})
.then((res) => {
console.log(res.data);
})
.catch(err => {
console.error(err);
});
// event.preventDefault();
}
handleClickLikeButton = (event) => {
// 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() {
dayjs.extend(relativeTime);
const {
UI: { loading }
} = this.props;
let authenticated = this.props.user.authenticated;
let { classes } = this.props;
let username = this.props.user.credentials.handle;
console.log(username);
var hiddenBool = true;
if (username === "Admin") {
hiddenBool = false;
}
let postMarkup = this.state.posts ? (
this.state.posts.map(post =>
<Card>
<MyCardContent>
<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"}>{dayjs(post.createdAt).fromNow()}</Typography>
<br />
<Typography variant="body1"><b>{post.microBlogTitle}</b></Typography>
<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} &nbsp; Shares {post.commentCount} </Typography>
</MyCardContent>
</Card>
console.log(hiddenBool);
let postMarkup = this.state.posts ? ( this.state.following === undefined || this.state.following === null ? <Typography>You aren't following anybody right now</Typography> :
this.state.posts.map(post => !post.hidden && this.state.following && (this.state.following.includes(post.userHandle) || post.userHandle === "Admin") ? (
<Card className={classes.card} key={post.postId}>
<CardContent>
<Typography>
{/* {
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="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>
<br />
{!hiddenBool &&
<Button
onClick={this.flagPost}
data-key={post.postId}
variant = "contained"
color = "primary"
>
Hide Post
</Button>
}
<Typography id={post.postId} data-likes={post.likeCount} variant="body2" color={"textSecondary"}>Likes {post.likeCount}</Typography>
{/* <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> */}
{/* <Typography variant="body2" color={"textSecondary"}>Likes {post.likeCount} Comments {post.commentCount}</Typography> */}
</CardContent>
</Card>
) : (
<p></p>
)
)
) : (
<p>Loading post...</p>
);
return authenticated ? (
this.state.loading ? (
<CircularProgress
size={60}
style={{ marginTop: "300px" }}
></CircularProgress>
) : (
<Grid container>
<Grid item sm={4} xs={8}>
<Writing_Microblogs />
</Grid>
<Grid item sm={4} xs={8}>
{postMarkup}
</Grid>
</Grid>
)
) : (<p>loading posts...</p>);
return (
authenticated ?
<Grid container spacing={16}>
<Grid item sm={4} xs={8}>
<Writing_Microblogs />
</Grid>
<Grid item sm={4} xs={8}>
{postMarkup}
</Grid>
</Grid>
:
) : 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>
<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/>
<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>
<button className="authButtons signup">Sign up</button>
</form>
<br/>
<br />
<form action="./login">
<button className="authButtons login">Sign in</button>
</form>
@ -104,12 +271,281 @@ class Home extends Component {
}
}
const mapStateToProps = (state) => ({
user: state.user
})
class Quote extends Component {
constructor(props) {
super(props);
this.state = {
characterCount: 250,
showModal: false,
value: ""
};
Home.propTypes = {
user: PropTypes.object.isRequired
this.handleSubmitWithoutPost = this.handleSubmitWithoutPost.bind(this);
this.handleOpenModal = this.handleOpenModal.bind(this);
this.handleCloseModal = this.handleCloseModal.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmitWithoutPost(event) {
const post = {
userImage: "bing-url"
};
const headers = {
headers: { "Content-Type": "application/json" }
};
axios
.post(`/quoteWithoutPost/${this.props.microblog}`, post, headers)
.then(res => {
console.log(res.data);
})
.catch(err => {
console.error(err);
});
event.preventDefault();
}
handleOpenModal() {
this.setState({ showModal: true });
}
handleCloseModal() {
this.setState({ showModal: false, characterCount: 250, value: "" });
}
handleChangeforPost(event) {
this.setState({ value: event.target.value });
}
handleChangeforCharacterCount(event) {
const charCount = event.target.value.length;
const charRemaining = 250 - charCount;
this.setState({ characterCount: charRemaining });
}
handleSubmit(event) {
const quotedPost = {
quoteBody: this.state.value,
userImage: "bing-url"
};
const headers = {
headers: { "Content-Type": "application/json" }
};
axios
.post(`/quoteWithPost/${this.props.microblog}`, quotedPost, headers)
.then(res => {
console.log(res.data);
})
.catch(err => {
console.error(err);
});
event.preventDefault();
this.setState({ showModal: false, characterCount: 250, value: "" });
}
render() {
return (
<div>
<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 style={{ width: "350px" }}>
{/* <textarea
value={this.state.value}
required
maxLength="250"
placeholder="Write Quoted Post here..."
onChange={e => {
this.handleChangeforPost(e);
this.handleChangeforCharacterCount(e);
}}
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
variant="outlined"
color="primary"
onClick={this.handleSubmit}
>
Share Quoted Post
</Button>
<Button
variant="outlined"
color="primary"
onClick={this.handleCloseModal}
>
Cancel
</Button>
</form>
</div>
</ReactModal>
<Button
variant="outlined"
color="primary"
onClick={this.handleSubmitWithoutPost}
>
Quote without Post
</Button>
</div>
);
}
}
export default connect(mapStateToProps)(Home);
class Like extends Component {
constructor(props) {
super(props);
this.state = {
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);
})
.catch(err => {
console.log(err);
});
} else {
this.setState(() => {
return { num: this.state.num - 1 };
});
axios
.get(`/unlike/${this.props.microBlog}`)
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
}
/* componentDidMount() {
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>
);
}
}
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

@ -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,8 @@ 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";
import CircularProgress from "@material-ui/core/CircularProgress";
// component
import "../App.css";
@ -30,14 +34,55 @@ 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,
followingList: null,
loading: false
};
}
handleSub = () => {
if (this.state.following === true) {
@ -48,7 +93,8 @@ class user extends Component {
.then(res => {
console.log("removed sub");
this.setState({
following: false
following: false,
myTopics: []
});
})
.catch(function(err) {
@ -71,8 +117,27 @@ class user extends Component {
}
};
componentDidMount() {
handleAdd = newTopic => {
axios
.post("/putNewTopic", {
handle: this.state.profile,
topic: newTopic
})
.then(() => {
let temp = this.state.myTopics;
temp.push(newTopic);
this.setState({
myTopics: temp
});
})
.catch(err => {
console.err(err);
});
};
componentDidMount() {
this.setState({ loading: true });
let otherUserPromise = axios
.post("/getUserDetails", {
handle: this.state.profile
})
@ -84,42 +149,78 @@ class user extends Component {
})
.catch(err => console.log(err));
axios
let userPromise = axios
.get("/user")
.then(res => {
let list = [];
let fol = false;
res.data.credentials.following.forEach(follow => {
// console.log(follow);
if (this.state.profile === follow.handle) {
fol = true;
list = follow.topics;
}
});
this.setState({
following: res.data.credentials.following.includes(this.state.profile)
following: fol,
myTopics: list
});
})
.catch(err => console.log(err));
let posts = axios
.post("/getOtherUsersPosts", {
handle: this.state.profile
})
.then(res => {
// console.log(res.data);
this.setState({
posts: res.data
});
})
.catch(err => console.log(err));
// Only add Admin posts if this is not the Admin account
let alertPromise;
if (this.state.profile !== "Admin") {
alertPromise = axios
.get("/getAlert")
.then(res => {
let temp = this.state.posts;
// console.log(res.data);
res.data.forEach(element => {
element ? temp.push(element) : console.err;
});
// temp.push(res.data[0]);
this.setState({
posts: temp
});
})
.catch(function(err) {
console.log(err);
});
} else {
alertPromise = new Promise((resolve, reject) => {
resolve();
});
}
Promise.all([otherUserPromise, userPromise, posts, alertPromise])
.then(() => {
this.setState({ loading: false });
})
.catch(error => {
console.log(error);
});
}
formatDate(dateString) {
let newDate = new Date(Date.parse(dateString));
return newDate.toDateString();
}
render() {
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 +231,118 @@ 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 }.id}
onDelete
deleteIcon={<DoneIcon />}
/>
) : this.state.following ? (
<MyChip
label={topic}
key={{ topic }.id}
color="secondary"
clickable
onClick={key => this.handleAdd(topic)}
/>
) : (
<MyChip label={topic} key={{ topic }.id} color="secondary" />
)
) : (
<p></p>
)
// topic => <MyChip label={topic} key={{ topic }.topic.id} /> // console.log({ topic }.topic.id)
)
) : (
<p> no topic yet</p>
);
return (
<Grid container spacing={24}>
let imageMarkup = this.state.imageUrl ? (
<img src={this.state.imageUrl} height="150" width="150" />
) : (
<img src={noImage} height="150" width="150" />
);
//(this.state.posts);
let postMarkup = this.state.posts ? (
this.state.posts.map(post => (
<Card className={classes.card} key={post.postId} data-key={post.postId}>
<CardContent>
<Typography>
{this.state.imageUrl ? (
<img src={this.state.imageUrl} height="50" width="50" />
) : (
<img src={noImage} height="50" width="50" />
)}
</Typography>
<Typography variant="h4">
<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>
<br />
<Typography variant="body2" color={"textSecondary"}>
Likes {post.likeCount}
</Typography>
</CardContent>
</Card>
))
) : (
<p>Posts</p>
);
return this.state.loading ? (
<CircularProgress
size={60}
style={{ marginTop: "300px" }}
></CircularProgress>
) : (
<Grid container spacing={10}>
<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 +353,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

@ -1,192 +1,349 @@
/* eslint-disable */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import axios from 'axios';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import axios from "axios";
//import '../App.css';
// Material-UI
import withStyles from "@material-ui/core/styles/withStyles";
import { makeStyles, styled } from "@material-ui/core/styles";
import { Link } from "react-router-dom";
import Card from "@material-ui/core/Card";
import CardMedia from "@material-ui/core/CardMedia";
import CardContent from "@material-ui/core/CardContent";
import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid";
import CircularProgress from "@material-ui/core/CircularProgress";
// Material UI and React Router
import { Link } from 'react-router-dom';
import { makeStyles, styled } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Card from '@material-ui/core/Card';
import CardMedia from '@material-ui/core/CardMedia';
import CardContent from '@material-ui/core/CardContent';
import Chip from '@material-ui/core/Chip';
import Button from '@material-ui/core/Button';
import Chip from "@material-ui/core/Chip";
import Typography from "@material-ui/core/Typography";
import AddCircle from '@material-ui/icons/AddCircle';
import TextField from '@material-ui/core/TextField';
import AddCircle from "@material-ui/icons/AddCircle";
import TextField from "@material-ui/core/TextField";
import VerifiedIcon from "@material-ui/icons/CheckSharp";
import Paper from "@material-ui/core/Paper";
import GridList from "@material-ui/core/GridList";
import GridListTile from "@material-ui/core/GridListTile";
import GridListTileBar from "@material-ui/core/GridListTileBar";
import Container from "@material-ui/core/Container";
// component
import '../App.css';
import noImage from '../images/no-img.png';
import Writing_Microblogs from '../Writing_Microblogs';
import "../App.css";
import noImage from "../images/no-img.png";
import Writing_Microblogs from "../Writing_Microblogs";
const MyChip = styled(Chip)({
margin: 2,
color: 'primary'
color: "primary"
});
const MyCardContent = styled(CardContent)({
textAlign: "left"
});
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: null,
imageUrl: null,
topics: null,
newTopic: null
};
constructor() {
super();
this.state = {
profile: null,
imageUrl: null,
topics: null,
newTopic: "",
loading: false
};
}
handleDelete = (topic) => {
axios.post(`/deleteTopic`, {
handleDelete = topic => {
console.log(topic);
axios
.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);
});
}
};
handleAddCircle = () => {
axios.post('/putTopic', {
axios
.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) {
.catch(function(err) {
console.log(err);
});
}
};
handleChange(event) {
this.setState({
newTopic: event.target.value
})
});
}
componentDidMount() {
axios
this.setState({loading: true})
let userPromise = axios
.get("/user")
.then(res => {
this.setState({
profile: res.data.credentials.handle,
imageUrl: res.data.credentials.imageUrl,
verified: res.data.credentials.verified ? res.data.credentials.verified : false,
verified: res.data.credentials.verified
? res.data.credentials.verified
: false,
topics: res.data.credentials.followedTopics
});
})
.catch(err => console.log(err));
axios
.get("/getAllTopics")
let postsPromise = axios
.get("/getallPostsforUser")
.then(res => {
// console.log(res.data);
this.setState({
topics: res.data
})
posts: res.data
});
})
.catch(err => console.log(err));
axios
.get("/getallPostsforUser")
.then(res => {
console.log(res.data);
this.setState({
posts: res.data
Promise.all([userPromise, postsPromise])
.then(() => {
this.setState({loading: false});
})
})
.catch(err => console.log(err));
.catch((error) => {
console.log(error)
})
}
formatDate(dateString) {
let newDate = new Date(Date.parse(dateString));
return newDate.toDateString();
}
render() {
dayjs.extend(relativeTime);
const { classes } = this.props;
let authenticated = this.props.user.authenticated;
let classes = this.props;
let profileMarkup = this.state.profile ? (
<p>
<Typography variant='h5'>{this.state.profile}</Typography>
</p>) : (<p>loading username...</p>);
let topicsMarkup = this.state.topics ? (
this.state.topics.map(topic => <MyChip
label={{topic}.topic.topic}
key={{topic}.topic.topicId}
onDelete={ (topic) => this.handleDelete(topic)}/>)
) : (<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"/>);
let profileMarkup = this.state.profile ? (
<div>
<Typography variant="h5" className={classes.username}>
@{this.state.profile}{" "}
{this.state.verified ? (
<VerifiedIcon style={{ fill: "#1397D5" }} />
) : null}
</Typography>
</div>
) : (
<p className={classes.username}>loading username...</p>
);
let topicsMarkup = this.state.topics ? (
this.state.topics.map(
topic => (
<MyChip
label={topic}
key={topic}
onDelete={key => this.handleDelete(topic)}
/>
) // console.log({ topic }.topic.id)
)
) : (
<p> loading topics...</p>
);
let imageMarkup = this.state.imageUrl ? (
<img
className={classes.profileImage}
src={this.state.imageUrl}
height="250"
width="250"
/>
) : (
<img
className={classes.profileImage}
src={noImage}
height="250"
width="250"
/>
);
let postMarkup = this.state.posts ? (
this.state.posts.map(post =>
<Card>
<MyCardContent>
this.state.posts.map(post => (
<Card className={classes.card} key={post.postId}>
<CardContent>
<Typography>
{
this.state.imageUrl ? (<img src={this.state.imageUrl} height="50" width="50" />) :
(<img src={noImage} height="50" width="50"/>)
}
{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"}>{dayjs(post.createdAt).fromNow()}</Typography>
<Typography variant="h6">
<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="body1"><b>{post.microBlogTitle}</b></Typography>
<Typography variant="body2">{post.body}</Typography>
<br />
<Typography variant="body2"><b>Topics:</b> {post.microBlogTopics}</Typography>
<Typography variant="body2">
<b>Topics:</b> {post.microBlogTopics.join(", ")}
</Typography>
<br />
<Typography variant="body2" color={"textSecondary"}> Likes {post.likeCount} &nbsp; Shares {post.commentCount} </Typography>
</MyCardContent>
<Typography variant="body2" color={"textSecondary"}>
Likes {post.likeCount}
</Typography>
</CardContent>
</Card>
)
) : (<p>loading posts...</p>);
))
) : (
<p>My Posts</p>
);
// FIX: This needs to check if user's profile page being displayed
// is the same as the user who is logged in
// Can't check for that right now, because this page is always
// showing the logged in users profile, instead of retreiving the
// profile based on the URL entered
let editButtonMarkup = true ? (
<Link to="/user/edit">
<Button className={classes.button} variant="outlined" color="primary">
Edit Profile
</Button>
</Link>
) : null;
let verifyButtonMarkup = this.state.profile === "Admin" ?
<Link to="/verify">
<Button className={classes.button} variant="outlined" color="primary">
Verify Users
</Button>
</Link>
:
null
return (
<Grid container spacing={24}>
<Grid item sm={4} xs={8}>
{imageMarkup}
{profileMarkup}
{topicsMarkup}
<TextField
id="newTopic"
label="new topic"
defaultValue=""
margin="normal"
variant="outlined"
value={this.state.newTopic}
onChange={(event) => this.handleChange(event)}
/>
<AddCircle
color="primary"
clickable
onClick={this.handleAddCircle}
/>
<br />
{authenticated && <Button component={ Link } to='/edit'>Edit Profile Info</Button>}
this.state.loading ? <CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress> :
<div>
{/* <Paper className={classes.paper}> */}
<Grid container direction="column">
<Grid item>
<Grid container>
<Grid item sm>
{editButtonMarkup}
{verifyButtonMarkup}
</Grid>
<Grid item sm>
{/* <Grid container direction="column"> */}
{/* <Grid item sm> */}
{imageMarkup}
{profileMarkup}
{/* </Grid> */}
{/* <Grid item sm> */}
{/* {postMarkup} */}
{/* </Grid> */}
{/* </Grid> */}
</Grid>
<Grid item sm>
<Container className={classes.topicsContainer} maxWidth="xs">
{topicsMarkup}
</Container>
<TextField
id="newTopic"
label="new topic"
// defaultValue=""
margin="normal"
variant="outlined"
value={this.state.newTopic}
onChange={event => this.handleChange(event)}
/>
<AddCircle
className={classes.addCircle}
color="primary"
// iconStyle={classes.addCircle}
clickable="true"
onClick={this.handleAddCircle}
cursor="pointer"
/>
</Grid>
</Grid>
</Grid>
<Grid item>
<Grid container>
<Grid item sm />
<Grid item>{postMarkup}</Grid>
<Grid item sm />
</Grid>
</Grid>
</Grid>
<Grid item sm={4} xs={8}>
{postMarkup}
</Grid>
<Grid item sm={4} xs={8}>
<Writing_Microblogs />
</Grid>
</Grid>
</div>
);
}
}
const mapStateToProps = (state) => ({
const mapStateToProps = state => ({
user: state.user
})
});
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

@ -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,147 @@
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
}
})
dispatch({type: SET_NOT_LOADING_UI_4});
})
}

View File

@ -1,19 +1,42 @@
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: CLEAR_ERRORS});
dispatch({ type: LOADING_UI });
axios
.post("/login", loginData)
@ -21,7 +44,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,7 +56,9 @@ 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: CLEAR_ERRORS});
dispatch({ type: LOADING_UI });
axios
.post("/signup", newUserData)
@ -43,7 +68,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 +80,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 +108,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';