Merge branch 'master' into admin-delete

This commit is contained in:
Clayton Wilson 2019-12-06 11:45:50 -05:00 committed by GitHub
commit a459e6581e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 2485 additions and 601 deletions

View File

@ -58,8 +58,10 @@ exports.getallPostsforUser = (req, res) => {
myPosts.forEach(function(doc) { myPosts.forEach(function(doc) {
posts.push(doc.data()); posts.push(doc.data());
}); });
posts.sort((a, b) => -a.createdAt.localeCompare(b.createdAt));
return res.status(200).json(posts); return res.status(200).json(posts);
}) })
.then(function() { .then(function() {
return res return res
.status(200) .status(200)
@ -68,7 +70,7 @@ exports.getallPostsforUser = (req, res) => {
.catch(function(err) { .catch(function(err) {
return res return res
.status(500) .status(500)
.json("Failed to retrieve user's posts from database.", err); .json({message: "Failed to retrieve user's posts from database.", error: err});
}); });
}; };
@ -95,46 +97,79 @@ exports.getallPosts = (req, res) => {
// Get all the posts // Get all the posts
var postsPromise = new Promise((resolve, reject) => { var postsPromise = new Promise((resolve, reject) => {
db.collection("posts").get() db.collection("posts")
.then((allPosts) => { .get()
allPosts.forEach((post) => { .then(allPosts => {
allPosts.forEach(post => {
posts.push(post.data()); posts.push(post.data());
}); });
posts.sort((a, b) => -a.createdAt.localeCompare(b.createdAt));
resolve(); resolve();
}) })
.catch((error) => { .catch(error => {
reject(error); reject(error);
}) });
}); });
// Get all users // Get all users
var usersPromise = new Promise((resolve, reject) => { var usersPromise = new Promise((resolve, reject) => {
db.collection("users").get() db.collection("users")
.then((allUsers) => { .get()
allUsers.forEach((user) => { .then(allUsers => {
allUsers.forEach(user => {
users[user.data().handle] = user.data(); users[user.data().handle] = user.data();
}) });
resolve(); resolve();
}) })
.catch((error) => { .catch(error => {
reject(error); reject(error);
}) });
}); });
// Wait for the two promises // Wait for the two promises
Promise.all([postsPromise, usersPromise]) Promise.all([postsPromise, usersPromise])
.then(() => { .then(() => {
let newPosts = [] let newPosts = [];
// Add the image url of the person who made the post to all of the post objects // Add the image url of the person who made the post to all of the post objects
posts.forEach((post) => { posts.forEach(post => {
post.profileImage = users[post.userHandle].imageUrl ? users[post.userHandle].imageUrl : null; post.profileImage = users[post.userHandle].imageUrl
? users[post.userHandle].imageUrl
: null;
newPosts.push(post); newPosts.push(post);
}); });
return res.status(200).json(newPosts); return res.status(200).json(newPosts);
}) })
.catch((error) => { .catch(error => {
return res.status(500).json({error}); return res.status(500).json({ error });
});
};
exports.getAlert = (req, res) => {
var post_query = admin
.firestore()
.collection("posts")
.where("microBlogTitle", "==", "Alert");
post_query
.get()
.then(function(myPosts) {
let posts = [];
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
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.getOtherUsersPosts = (req, res) => { exports.getOtherUsersPosts = (req, res) => {
@ -155,6 +190,7 @@ exports.getOtherUsersPosts = (req, res) => {
myPosts.forEach(function(doc) { myPosts.forEach(function(doc) {
posts.push(doc.data()); posts.push(doc.data());
}); });
posts.sort((a, b) => -a.createdAt.localeCompare(b.createdAt));
return res.status(200).json(posts); return res.status(200).json(posts);
}) })
.then(function() { .then(function() {
@ -170,23 +206,25 @@ exports.getOtherUsersPosts = (req, res) => {
}; };
exports.quoteWithPost = (req, res) => { exports.quoteWithPost = (req, res) => {
let quoteData; let quoteData;
const quoteDoc = admin.firestore().collection('quote'). const quoteDoc = admin
where('userHandle', '==', req.user.handle). .firestore()
where('quoteId', '==', req.params.postId).limit(1); .collection("quote")
.where("userHandle", "==", req.user.handle)
.where("quoteId", "==", req.params.postId)
.limit(1);
const postDoc = db.doc(`/posts/${req.params.postId}`); const postDoc = db.doc(`/posts/${req.params.postId}`);
postDoc.get() postDoc
.then((doc) => { .get()
if(doc.exists) { .then(doc => {
quoteData = doc.data(); if (doc.exists) {
return quoteDoc.get(); quoteData = doc.data();
} return quoteDoc.get();
else } else {
{ return res.status(404).json({ error: "Post not found" });
return res.status(404).json({error: 'Post not found'}); }
}
}) })
.then(data => { .then(data => {
if (data.empty) { if (data.empty) {
@ -234,23 +272,25 @@ exports.quoteWithPost = (req, res) => {
}; };
exports.quoteWithoutPost = (req, res) => { exports.quoteWithoutPost = (req, res) => {
let quoteData; let quoteData;
const quoteDoc = admin.firestore().collection('quote'). const quoteDoc = admin
where('userHandle', '==', req.user.handle). .firestore()
where('quoteId', '==', req.params.postId).limit(1); .collection("quote")
.where("userHandle", "==", req.user.handle)
.where("quoteId", "==", req.params.postId)
.limit(1);
const postDoc = db.doc(`/posts/${req.params.postId}`); const postDoc = db.doc(`/posts/${req.params.postId}`);
postDoc.get() postDoc
.then((doc) => { .get()
if(doc.exists) { .then(doc => {
quoteData = doc.data(); if (doc.exists) {
return quoteDoc.get(); quoteData = doc.data();
} return quoteDoc.get();
else } else {
{ return res.status(404).json({ error: "Post not found" });
return res.status(404).json({error: 'Post not found'}); }
}
}) })
.then(data => { .then(data => {
if (data.empty) { if (data.empty) {
@ -292,7 +332,7 @@ exports.quoteWithoutPost = (req, res) => {
} }
}) })
.catch(err => { .catch(err => {
// return res.status(500).json({ error: "Something is wrong" }); // return res.status(500).json({ error: "Something is wrong" });
return res.status(500).json({ error: err }); return res.status(500).json({ error: err });
}); });
}; };
@ -306,202 +346,198 @@ exports.checkforLikePost = (req, res) => {
.limit(1); .limit(1);
let result; let result;
likedPostDoc.get().then(data => { likedPostDoc
if (data.empty) { .get()
result = false; .then(data => {
return res.status(200).json(result); if (data.empty) {
} else { result = false;
result = true; return res.status(200).json(result);
return res.status(200).json(result); } else {
} result = true;
}) return res.status(200).json(result);
.catch((err) => { }
})
.catch(err => {
console.log(err); console.log(err);
return res.status(500).json({error: err}); return res.status(500).json({ error: err });
}) });
}; };
exports.likePost = (req, res) => { exports.likePost = (req, res) => {
const postId = req.params.postId;
let likedPostDoc;
db.doc(`/users/${req.userData.handle}`)
.get()
.then(userDoc => {
let likes = userDoc.data().likes;
if (likes === undefined || likes === null) {
likes = [];
}
const postId = req.params.postId; if (likes.includes(postId)) {
let likedPostDoc; return res
db.doc(`/users/${req.userData.handle}`) .status(400)
.get() .json({ error: "This user has already liked this post" });
.then((userDoc) => { }
let likes = userDoc.data().likes;
if (likes === undefined || likes === null) {
likes = [];
}
if (likes.includes(postId)) { likes.push(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 });
});
return userDoc.ref.update({likes}) // let postData;
}) // const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
.then(() => { // .where('postId', '==', req.params.postId).limit(1);
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 postDoc = db.doc(`/posts/${req.params.postId}`);
// 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) => {
// postDoc.get() // if(doc.exists) {
// .then((doc) => { // postData = doc.data();
// if(doc.exists) { // return likeDoc.get();
// postData = doc.data(); // }
// return likeDoc.get(); // else
// } // {
// else // return res.status(404).json({error: 'Post not found'});
// { // }
// return res.status(404).json({error: 'Post not found'}); // })
// } // .then((data) => {
// }) // if (data.empty) {
// .then((data) => { // return admin.firestore().collection('likes').add({
// if (data.empty) { // postId : req.params.postId,
// return admin.firestore().collection('likes').add({ // userHandle: req.user.handle
// 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'});
// })
}
// })
// .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) => { 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 = [];
}
const postId = req.params.postId; if (!likes.includes(postId)) {
let likedPostDoc; return res
db.doc(`/users/${req.userData.handle}`) .status(400)
.get() .json({ error: "This user hasn't liked this post yet" });
.then((userDoc) => { }
let likes = userDoc.data().likes;
if (likes === undefined || likes === null) {
likes = [];
}
if (!likes.includes(postId)) { let i;
return res.status(400).json({error: "This user hasn't liked this post yet"}); for (i = 0; i < likes.length; i++) {
} if (likes[i] === postId) {
likes.splice(i, 1);
}
}
let i; return userDoc.ref.update({ likes });
for (i = 0; i < likes.length; i++) { })
if (likes[i] === postId) { .then(() => {
likes.splice(i, 1); 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 });
});
return userDoc.ref.update({likes}) // let postData;
}) // const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
.then(() => { // .where('postId', '==', req.params.postId).limit(1);
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 postDoc = db.doc(`/posts/${req.params.postId}`);
// 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) => {
// postDoc.get() // if(doc.exists) {
// .then((doc) => { // postData = doc.data();
// if(doc.exists) { // return likeDoc.get();
// postData = doc.data(); // }
// return likeDoc.get(); // else
// } // {
// else // return res.status(404).json({error: 'Post not found'});
// { // }
// return res.status(404).json({error: 'Post not found'}); // })
// } // .then((data) => {
// }) // return db
// .then((data) => { // .doc(`/likes/${data.docs[0].id}`)
// return db // .delete()
// .doc(`/likes/${data.docs[0].id}`) // .then(() => {
// .delete() // postData.likeCount--;
// .then(() => { // return postDoc.update({ likeCount: postData.likeCount });
// postData.likeCount--; // })
// return postDoc.update({ likeCount: postData.likeCount }); // .then(() => {
// }) // res.status(200).json(postData);
// .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) => { exports.getLikes = (req, res) => {
db.doc(`/users/${req.userData.handle}`) db.doc(`/users/${req.userData.handle}`)
.get() .get()
.then((doc) => { .then(doc => {
let likes = doc.data().likes; let likes = doc.data().likes;
if (likes === undefined || likes === null) { if (likes === undefined || likes === null) {
likes = []; likes = [];
} }
return res.status(200).json({likes}); return res.status(200).json({ likes });
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
return res.status(500).json({error: err}); return res.status(500).json({ error: err });
}) });
} };
exports.getFilteredPosts = (req, res) => { exports.getFilteredPosts = (req, res) => {
admin admin
.firestore() .firestore()
.collection("posts") .collection("posts")
.where("userHandle", "==", "new user") .where("userHandle", "==", "new user")
.where("microBlogTopics", "=="); .where("microBlogTopics", "==");
}; };

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -11,6 +11,11 @@ app.use(cors());
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/
const { const {
getAuthenticatedUser, getAuthenticatedUser,
getDirectMessages,
sendDirectMessage,
createDirectMessage,
checkDirectMessagesEnabled,
toggleDirectMessages,
getAllHandles, getAllHandles,
getUserDetails, getUserDetails,
getProfileInfo, getProfileInfo,
@ -39,6 +44,22 @@ app.post("/login", login);
//Deletes user account //Deletes user account
app.delete("/delete", fbAuth, deleteUser); 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); app.post("/getUserDetails", fbAuth, getUserDetails);
@ -83,8 +104,21 @@ app.post("/removeSub", fbAuth, removeSub);
* handlers/post.js * * handlers/post.js *
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/
const { getallPostsforUser, getallPosts, putPost, hidePost, likePost, unlikePost, getLikes, quoteWithPost, quoteWithoutPost, checkforLikePost, getOtherUsersPosts} = require("./handlers/post");
const {
getallPostsforUser,
getallPosts,
putPost,
hidePost,
likePost,
unlikePost,
getLikes,
quoteWithPost,
quoteWithoutPost,
checkforLikePost,
getOtherUsersPosts,
getAlert
} = require("./handlers/post");
app.get("/getallPostsforUser", fbAuth, getallPostsforUser); app.get("/getallPostsforUser", fbAuth, getallPostsforUser);
@ -106,6 +140,8 @@ app.post("/quoteWithoutPost/:postId", fbAuth, quoteWithoutPost);
app.post("/getOtherUsersPosts", fbAuth, getOtherUsersPosts); app.post("/getOtherUsersPosts", fbAuth, getOtherUsersPosts);
app.get("/getAlert", fbAuth, getAlert);
/*------------------------------------------------------------------* /*------------------------------------------------------------------*
* handlers/topic.js * * handlers/topic.js *
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/
@ -113,7 +149,8 @@ const {
putTopic, putTopic,
getAllTopics, getAllTopics,
deleteTopic, deleteTopic,
getUserTopics getUserTopics,
putNewTopic
} = require("./handlers/topic"); } = require("./handlers/topic");
// add topic to database // add topic to database
@ -128,4 +165,6 @@ app.post("/deleteTopic", fbAuth, deleteTopic);
// get topic for this user // get topic for this user
app.post("/getUserTopics", fbAuth, getUserTopics); app.post("/getUserTopics", fbAuth, getUserTopics);
app.post("/putNewTopic", fbAuth, putNewTopic);
exports.api = functions.https.onRequest(app); exports.api = functions.https.onRequest(app);

View File

@ -10,7 +10,7 @@
"axios": "^0.19.0", "axios": "^0.19.0",
"clsx": "^1.0.4", "clsx": "^1.0.4",
"create-react-app": "^3.1.2", "create-react-app": "^3.1.2",
"firebase-admin": "^8.8.0", "dayjs": "^1.8.17",
"fuse.js": "^3.4.6", "fuse.js": "^3.4.6",
"install": "^0.13.0", "install": "^0.13.0",
"jwt-decode": "^2.2.0", "jwt-decode": "^2.2.0",
@ -23,7 +23,8 @@
"react-scripts": "0.9.5", "react-scripts": "0.9.5",
"redux": "^4.0.4", "redux": "^4.0.4",
"redux-thunk": "^2.3.0", "redux-thunk": "^2.3.0",
"typeface-roboto": "0.0.75" "typeface-roboto": "0.0.75",
"underscore": "^1.9.1"
}, },
"devDependencies": {}, "devDependencies": {},
"scripts": { "scripts": {

View File

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

View File

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

View File

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

View File

@ -6,41 +6,58 @@ import axios from "axios";
// Material UI and React Router // Material UI and React Router
import CircularProgress from '@material-ui/core/CircularProgress'; import CircularProgress from "@material-ui/core/CircularProgress";
import Button from '@material-ui/core/Button'; import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid"; import Grid from "@material-ui/core/Grid";
import Card from "@material-ui/core/Card"; import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent"; import CardContent from "@material-ui/core/CardContent";
import TextField from '@material-ui/core/TextField'; import TextField from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography"; import Typography from "@material-ui/core/Typography";
import withStyles from '@material-ui/styles/withStyles'; import withStyles from "@material-ui/styles/withStyles";
// component // component
import '../App.css'; import "../App.css";
import logo from '../images/twistter-logo.png'; import logo from "../images/twistter-logo.png";
import noImage from '../images/no-img.png'; import noImage from "../images/no-img.png";
import Writing_Microblogs from '../Writing_Microblogs'; import Writing_Microblogs from "../Writing_Microblogs";
import ReactModal from 'react-modal'; import ReactModal from "react-modal";
// Redux // Redux
import { likePost, unlikePost, getLikes } from '../redux/actions/userActions'; import { likePost, unlikePost, getLikes } from "../redux/actions/userActions";
const styles = { const styles = {
card: { card: {
marginBottom: 5 marginBottom: 5
} }
} };
class Home extends Component { class Home extends Component {
state = { state = {
likes: [] likes: [],
loading: false,
following: null,
topics: null
}; };
componentDidMount() { componentDidMount() {
axios this.setState({ loading: true });
let userPromise = axios
.get("/user")
.then(res => {
console.log(res.data.credentials.following);
let list = [];
res.data.credentials.following.forEach(element => {
list.push(element.handle);
});
this.setState({
following: list,
topics: res.data.credentials.followedTopics
});
})
.catch(err => console.log(err));
let postPromise = axios
.get("/getallPosts") .get("/getallPosts")
.then(res => { .then(res => {
// console.log(res.data); // console.log(res.data);
@ -50,13 +67,23 @@ class Home extends Component {
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
Promise.all([userPromise, postPromise])
.then(() => {
this.setState({
loading: false
});
})
.catch(error => {
console.log(error);
});
this.props.getLikes(); this.props.getLikes();
} }
componentWillReceiveProps(nextProps) { componentWillReceiveProps(nextProps) {
this.setState({ this.setState({
likes: nextProps.user.likes likes: nextProps.user.likes
}) });
} }
flagPost = (event) => { flagPost = (event) => {
@ -76,22 +103,23 @@ class Home extends Component {
handleClickLikeButton = (event) => { handleClickLikeButton = (event) => {
// Need the ternary if statement because the user can click on the text or body of the // Need the ternary if statement because the user can click on the text or body of the
// Button and they are two different html elements // Button and they are two different html elements
let postId = event.target.dataset.key ? event.target.dataset.key : event.target.parentNode.dataset.key; let postId = event.target.dataset.key
console.log(postId) ? event.target.dataset.key
: event.target.parentNode.dataset.key;
console.log(postId);
let doc = document.getElementById(postId); let doc = document.getElementById(postId);
// console.log(postId); // console.log(postId);
if (this.state.likes.includes(postId)) { if (this.state.likes.includes(postId)) {
this.props.unlikePost(postId, this.state.likes) this.props.unlikePost(postId, this.state.likes);
doc.dataset.likes--; doc.dataset.likes--;
} else { } else {
this.props.likePost(postId, this.state.likes) this.props.likePost(postId, this.state.likes);
doc.dataset.likes++; doc.dataset.likes++;
} }
doc.innerHTML = "Likes " + doc.dataset.likes; doc.innerHTML = "Likes " + doc.dataset.likes;
};
}
formatDate(dateString) { formatDate(dateString) {
let newDate = new Date(Date.parse(dateString)); let newDate = new Date(Date.parse(dateString));
@ -99,10 +127,11 @@ class Home extends Component {
} }
render() { render() {
const {
const { UI:{ loading } } = this.props; UI: { loading }
} = this.props;
let authenticated = this.props.user.authenticated; let authenticated = this.props.user.authenticated;
let {classes} = this.props; let { classes } = this.props;
let username = this.props.user.credentials.handle; let username = this.props.user.credentials.handle;
console.log(username); console.log(username);
var hiddenBool = true; var hiddenBool = true;
@ -112,7 +141,10 @@ class Home extends Component {
console.log(hiddenBool); console.log(hiddenBool);
let postMarkup = this.state.posts ? ( let postMarkup = this.state.posts ? (
// <<<<<<< admin-delete
this.state.posts.map(post => post.hidden ? null : this.state.posts.map(post => post.hidden ? null :
this.state.following ?
this.state.following.includes(post.userHandle) ? (
<Card className={classes.card} key={post.postId}> <Card className={classes.card} key={post.postId}>
<CardContent> <CardContent>
<Typography> <Typography>
@ -133,7 +165,7 @@ class Home extends Component {
<br /> <br />
<Typography variant="body2">{post.body}</Typography> <Typography variant="body2">{post.body}</Typography>
<br /> <br />
<Typography variant="body2"><b>Topics:</b> {post.microBlogTopics}</Typography> <Typography variant="body2"><b>Topics:</b> {post.microBlogTopics.join(", ")}</Typography>
<br /> <br />
{!hiddenBool && {!hiddenBool &&
<Button <Button
@ -165,49 +197,80 @@ class Home extends Component {
</CardContent> </CardContent>
</Card> </Card>
) : (
<p></p>
)
) : (
<p></p>
)
// =======
// this.state.posts.map(post =>
// this.state.following ? (
// this.state.following.includes(post.userHandle) ? (
// ) : (
// <p></p>
// )
// ) : (
// <p></p>
// )
// >>>>>>> master
) )
) : ( ) : (
<p>Loading post...</p> <p>Loading post...</p>
); );
return ( return authenticated ? (
authenticated ? ( this.state.loading ? (
<Grid container> <CircularProgress
<Grid item sm={4} xs={8}> size={60}
<Writing_Microblogs /> style={{ marginTop: "300px" }}
></CircularProgress>
) : (
<Grid container>
<Grid item sm={4} xs={8}>
<Writing_Microblogs />
</Grid>
<Grid item sm={4} xs={8}>
{postMarkup}
</Grid>
</Grid> </Grid>
<Grid item sm={4} xs={8}> )
{postMarkup} ) : loading ? (
</Grid> <CircularProgress
</Grid> size={60}
) : loading ? style={{ marginTop: "300px" }}
(<CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress>) ></CircularProgress>
: ) : (
( <div>
<div> <div>
<div> <img src={logo} className="app-logo" alt="logo" />
<img src={logo} className="app-logo" alt="logo" /> <br />
<br/><br/> <br />
<b>Welcome to Twistter!</b> <b>Welcome to Twistter!</b>
<br/><br/> <br />
<b>See the most interesting topics people are following right now.</b> <br />
</div> <b>See the most interesting topics people are following right now.</b>
</div>
<br/><br/><br/><br/> <br />
<br />
<br />
<br />
<div> <div>
<b>Join today or sign in if you already have an account.</b> <b>Join today or sign in if you already have an account.</b>
<br/><br/> <br />
<form action="./signup"> <br />
<button className="authButtons signup">Sign up</button> <form action="./signup">
</form> <button className="authButtons signup">Sign up</button>
<br/> </form>
<form action="./login"> <br />
<button className="authButtons login">Sign in</button> <form action="./login">
</form> <button className="authButtons login">Sign in</button>
</div> </form>
</div> </div>
)); </div>
);
} }
} }
@ -218,38 +281,36 @@ class Quote extends Component {
characterCount: 250, characterCount: 250,
showModal: false, showModal: false,
value: "" value: ""
} };
this.handleSubmitWithoutPost = this.handleSubmitWithoutPost.bind(this); this.handleSubmitWithoutPost = this.handleSubmitWithoutPost.bind(this);
this.handleOpenModal = this.handleOpenModal.bind(this); this.handleOpenModal = this.handleOpenModal.bind(this);
this.handleCloseModal = this.handleCloseModal.bind(this); this.handleCloseModal = this.handleCloseModal.bind(this);
this.handleSubmit = this.handleSubmit.bind(this); this.handleSubmit = this.handleSubmit.bind(this);
} }
handleSubmitWithoutPost(event) { handleSubmitWithoutPost(event) {
const post = { const post = {
userImage: "bing-url"
userImage: "bing-url", };
}
const headers = { const headers = {
headers: { "Content-Type": "application/json" } headers: { "Content-Type": "application/json" }
}; };
axios.post(`/quoteWithoutPost/${this.props.microblog}`, post, headers) axios
.then((res) => { .post(`/quoteWithoutPost/${this.props.microblog}`, post, headers)
.then(res => {
console.log(res.data); console.log(res.data);
}) })
.catch(err => { .catch(err => {
console.error(err);
console.error(err); });
});
event.preventDefault(); event.preventDefault();
} }
handleOpenModal() { handleOpenModal() {
this.setState({ showModal: true }); this.setState({ showModal: true });
} }
handleCloseModal() { handleCloseModal() {
this.setState({ showModal: false, characterCount: 250, value: "" }); this.setState({ showModal: false, characterCount: 250, value: "" });
} }
@ -267,20 +328,19 @@ class Quote extends Component {
handleSubmit(event) { handleSubmit(event) {
const quotedPost = { const quotedPost = {
quoteBody: this.state.value, quoteBody: this.state.value,
userImage: "bing-url", userImage: "bing-url"
}; };
const headers = { const headers = {
headers: { "Content-Type": "application/json" } headers: { "Content-Type": "application/json" }
}; };
axios.post(`/quoteWithPost/${this.props.microblog}`, quotedPost, headers) axios
.then((res) => { .post(`/quoteWithPost/${this.props.microblog}`, quotedPost, headers)
.then(res => {
console.log(res.data); console.log(res.data);
}) })
.catch(err => { .catch(err => {
console.error(err);
console.error(err); });
});
event.preventDefault(); event.preventDefault();
this.setState({ showModal: false, characterCount: 250, value: "" }); this.setState({ showModal: false, characterCount: 250, value: "" });
} }
@ -288,14 +348,29 @@ class Quote extends Component {
render() { render() {
return ( return (
<div> <div>
<Button variant="outlined" color="primary" onClick={this.handleOpenModal}>Quote with Post</Button> <Button
<ReactModal variant="outlined"
isOpen={this.state.showModal} color="primary"
style={{content: {height: "50%", width: "25%", marginTop: "auto", marginLeft: "auto", marginRight: "auto", marginBottom : "auto"}}} 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" }}> <div style={{ width: "200px", marginLeft: "50px" }}>
<form style={{ width: "350px"}}> <form style={{ width: "350px" }}>
{/* <textarea {/* <textarea
value={this.state.value} value={this.state.value}
required required
maxLength="250" maxLength="250"
@ -308,99 +383,109 @@ class Quote extends Component {
cols={40} cols={40}
rows={20} rows={20}
/> */} /> */}
<TextField <TextField
style={{width: 300}} style={{ width: 300 }}
value={this.state.value} value={this.state.value}
label="Write Quoted Post here..." label="Write Quoted Post here..."
required required
multiline multiline
color="primary" color="primary"
rows="14" rows="14"
variant="outlined" variant="outlined"
inputProps={{ inputProps={{
maxLength: 250 maxLength: 250
}} }}
onChange={e => { onChange={e => {
this.handleChangeforPost(e); this.handleChangeforPost(e);
this.handleChangeforCharacterCount(e); this.handleChangeforCharacterCount(e);
}} }}
autoComplete='off' autoComplete="off"
></TextField> ></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 style={{ fontSize: "14px", marginRight: "-100px" }}>
</div> <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> </ReactModal>
<Button variant="outlined" color="primary" onClick={this.handleSubmitWithoutPost}>Quote without Post</Button> <Button
variant="outlined"
color="primary"
onClick={this.handleSubmitWithoutPost}
>
Quote without Post
</Button>
</div> </div>
) );
} }
} }
class Like extends Component { class Like extends Component {
constructor(props) { constructor(props) {
super(props) super(props);
this.state = { this.state = {
num : this.props.count, num: this.props.count
};
}
this.handleClick = this.handleClick.bind(this); this.handleClick = this.handleClick.bind(this);
} }
componentDidMount() { componentDidMount() {
this.setState({ this.setState({
like: localStorage.getItem(this.props.microBlog + this.props.name) === "false" like:
localStorage.getItem(this.props.microBlog + this.props.name) === "false"
}) });
} }
handleClick(){
handleClick(){
this.setState({ this.setState({
like: !this.state.like like: !this.state.like
}); });
localStorage.setItem(this.props.microBlog + this.props.name, this.state.like.toString()) localStorage.setItem(
this.props.microBlog + this.props.name,
this.state.like.toString()
);
if(this.state.like == false) if (this.state.like == false) {
{ this.setState(() => {
this.setState(() => { return { num: this.state.num + 1 };
return {num: this.state.num + 1} });
}); axios
axios.get(`/like/${this.props.microBlog}`) .get(`/like/${this.props.microBlog}`)
.then((res) => { .then(res => {
console.log(res.data); console.log(res.data);
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
}) });
} } else {
else this.setState(() => {
{ return { num: this.state.num - 1 };
this.setState(() => { });
return {num: this.state.num - 1} axios
}); .get(`/unlike/${this.props.microBlog}`)
axios.get(`/unlike/${this.props.microBlog}`) .then(res => {
.then((res) => { console.log(res.data);
console.log(res.data); })
}) .catch(err => {
.catch((err) => { console.log(err);
console.log(err); });
}) }
}
} }
/* componentDidMount() { /* componentDidMount() {
@ -421,33 +506,30 @@ class Like extends Component {
}) })
} }
} */ } */
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>
)
}
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) => ({ const mapStateToProps = state => ({
user: state.user, user: state.user,
UI: state.UI UI: state.UI
}) });
const mapActionsToProps = { const mapActionsToProps = {
likePost, likePost,
unlikePost, unlikePost,
getLikes getLikes
} };
Home.propTypes = { Home.propTypes = {
user: PropTypes.object.isRequired, user: PropTypes.object.isRequired,
@ -456,16 +538,17 @@ Home.propTypes = {
getLikes: PropTypes.func.isRequired, getLikes: PropTypes.func.isRequired,
classes: PropTypes.object.isRequired, classes: PropTypes.object.isRequired,
UI: PropTypes.object.isRequired UI: PropTypes.object.isRequired
} };
Like.propTypes = { Like.propTypes = {
user: PropTypes.object.isRequired user: PropTypes.object.isRequired
} };
Quote.propTypes = { Quote.propTypes = {
user: PropTypes.object.isRequired user: PropTypes.object.isRequired
} };
export default connect(mapStateToProps, mapActionsToProps)(withStyles(styles)(Home, Like, Quote));
export default connect(
mapStateToProps,
mapActionsToProps
)(withStyles(styles)(Home, Like, Quote));

View File

@ -0,0 +1,667 @@
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.hasDirectMessagesEnabled ? "This user has DMs disabled" :
!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 &&
// Won't accept classes style for some reason
<CircularProgress size={30} style={{position: "absolute"}}/>
}
</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"
disabled={!this.state.selectedChannel.hasDirectMessagesEnabled}
value={
!this.state.selectedChannel.hasDirectMessagesEnabled ?
"This user has DMs disabled"
:
this.state.drafts[this.state.selectedChannel.dmId] ?
this.state.drafts[this.state.selectedChannel.dmId]
:
""
}
onChange={this.handleChangeMessage}
/>
<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

@ -14,6 +14,8 @@ import Popover from "@material-ui/core/Popover";
import TextField from "@material-ui/core/TextField"; import TextField from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography"; import Typography from "@material-ui/core/Typography";
import withStyles from "@material-ui/core/styles/withStyles"; 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 IconButton from "@material-ui/core/IconButton";
import EditIcon from "@material-ui/icons/Edit"; import EditIcon from "@material-ui/icons/Edit";
import Tooltip from "@material-ui/core/Tooltip"; import Tooltip from "@material-ui/core/Tooltip";
@ -99,6 +101,7 @@ export class editProfile extends Component {
email: res.data.email, email: res.data.email,
handle: res.data.handle, handle: res.data.handle,
bio: res.data.bio ? res.data.bio : "", bio: res.data.bio ? res.data.bio : "",
dmEnabled: res.data.dmEnabled === false ? false : true,
pageLoading: false pageLoading: false
}); });
}) })
@ -121,6 +124,8 @@ export class editProfile extends Component {
email: "", email: "",
handle: "", handle: "",
bio: "", bio: "",
dmEnabled: false,
togglingDirectMessages: false,
anchorEl: null, anchorEl: null,
loading: false, loading: false,
pageLoading: false, pageLoading: false,
@ -183,6 +188,28 @@ export class editProfile 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) => { handleImageChange = (event) => {
if (event.target.files[0]) { if (event.target.files[0]) {
const image = event.target.files[0]; const image = event.target.files[0];
@ -222,7 +249,6 @@ export class editProfile extends Component {
const uploading = this.props.UI.loading; const uploading = this.props.UI.loading;
const { errors, loading } = this.state; const { errors, loading } = this.state;
// <<<<<<< edit-profile-image-upload
let imageMarkup = this.props.user.credentials.imageUrl ? ( let imageMarkup = this.props.user.credentials.imageUrl ? (
<Box <Box
@ -364,6 +390,18 @@ export class editProfile extends Component {
fullWidth fullWidth
autoComplete='off' 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 <Button
type="submit" type="submit"
variant="contained" variant="contained"
@ -453,6 +491,7 @@ export class editProfile extends Component {
} }
} }
const mapStateToProps = (state) => ({ const mapStateToProps = (state) => ({
user: state.user, user: state.user,
UI: state.UI, UI: state.UI,
@ -463,7 +502,9 @@ const mapActionsToProps = { uploadImage }
editProfile.propTypes = { editProfile.propTypes = {
uploadImage: PropTypes.func.isRequired, uploadImage: PropTypes.func.isRequired,
classes: PropTypes.object.isRequired classes: PropTypes.object.isRequired,
user: PropTypes.object.isRequired,
UI: PropTypes.object.isRequired
}; };
// export default withStyles(styles)(edit); // export default withStyles(styles)(edit);

View File

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

View File

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

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

@ -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 = { const initialState = {
loading: false, loading: false,
loading2: false,
loading3: false,
loading4: false,
errors: null errors: null
}; };
@ -24,6 +37,36 @@ export default function(state = initialState, action) {
...state, ...state,
loading: true 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: default:
return state; return state;
} }

View File

@ -10,6 +10,15 @@ export const SET_LIKES = 'SET_LIKES';
// UI reducer types // UI reducer types
export const SET_ERRORS = 'SET_ERRORS'; export const SET_ERRORS = 'SET_ERRORS';
export const LOADING_UI = 'LOADING_UI'; 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'; 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';