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) {
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)
@ -68,7 +70,7 @@ exports.getallPostsforUser = (req, res) => {
.catch(function(err) {
return res
.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
var postsPromise = new Promise((resolve, reject) => {
db.collection("posts").get()
.then((allPosts) => {
allPosts.forEach((post) => {
db.collection("posts")
.get()
.then(allPosts => {
allPosts.forEach(post => {
posts.push(post.data());
});
posts.sort((a, b) => -a.createdAt.localeCompare(b.createdAt));
resolve();
})
.catch((error) => {
.catch(error => {
reject(error);
})
});
});
// Get all users
var usersPromise = new Promise((resolve, reject) => {
db.collection("users").get()
.then((allUsers) => {
allUsers.forEach((user) => {
db.collection("users")
.get()
.then(allUsers => {
allUsers.forEach(user => {
users[user.data().handle] = user.data();
})
});
resolve();
})
.catch((error) => {
.catch(error => {
reject(error);
})
});
});
// Wait for the two promises
Promise.all([postsPromise, usersPromise])
.then(() => {
let newPosts = []
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;
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});
.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() {
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) => {
@ -155,6 +190,7 @@ exports.getOtherUsersPosts = (req, res) => {
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() {
@ -170,23 +206,25 @@ exports.getOtherUsersPosts = (req, res) => {
};
exports.quoteWithPost = (req, res) => {
let quoteData;
const quoteDoc = admin.firestore().collection('quote').
where('userHandle', '==', req.user.handle).
where('quoteId', '==', req.params.postId).limit(1);
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}`);
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'});
}
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) {
@ -234,23 +272,25 @@ exports.quoteWithPost = (req, res) => {
};
exports.quoteWithoutPost = (req, res) => {
let quoteData;
const quoteDoc = admin.firestore().collection('quote').
where('userHandle', '==', req.user.handle).
where('quoteId', '==', req.params.postId).limit(1);
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}`);
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'});
}
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) {
@ -292,7 +332,7 @@ exports.quoteWithoutPost = (req, res) => {
}
})
.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 });
});
};
@ -306,202 +346,198 @@ exports.checkforLikePost = (req, res) => {
.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) => {
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});
})
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 = [];
}
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" });
}
if (likes.includes(postId)) {
return res.status(400).json({error: "This user has already liked this post"});
}
likes.push(postId);
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})
})
.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);
// let postData;
// const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
// .where('postId', '==', req.params.postId).limit(1);
// const postDoc = db.doc(`/posts/${req.params.postId}`);
// const 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'});
// })
}
// 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 = [];
}
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" });
}
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);
}
}
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 });
});
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);
// let postData;
// const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
// .where('postId', '==', req.params.postId).limit(1);
// const postDoc = db.doc(`/posts/${req.params.postId}`);
// const 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'});
// })
}
// 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});
})
}
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", "==");
};

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,6 +11,11 @@ app.use(cors());
*------------------------------------------------------------------*/
const {
getAuthenticatedUser,
getDirectMessages,
sendDirectMessage,
createDirectMessage,
checkDirectMessagesEnabled,
toggleDirectMessages,
getAllHandles,
getUserDetails,
getProfileInfo,
@ -39,6 +44,22 @@ 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);
@ -83,8 +104,21 @@ app.post("/removeSub", fbAuth, removeSub);
* 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);
@ -106,6 +140,8 @@ app.post("/quoteWithoutPost/:postId", fbAuth, quoteWithoutPost);
app.post("/getOtherUsersPosts", fbAuth, getOtherUsersPosts);
app.get("/getAlert", fbAuth, getAlert);
/*------------------------------------------------------------------*
* handlers/topic.js *
*------------------------------------------------------------------*/
@ -113,7 +149,8 @@ const {
putTopic,
getAllTopics,
deleteTopic,
getUserTopics
getUserTopics,
putNewTopic
} = require("./handlers/topic");
// add topic to database
@ -128,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

@ -10,7 +10,7 @@
"axios": "^0.19.0",
"clsx": "^1.0.4",
"create-react-app": "^3.1.2",
"firebase-admin": "^8.8.0",
"dayjs": "^1.8.17",
"fuse.js": "^3.4.6",
"install": "^0.13.0",
"jwt-decode": "^2.2.0",
@ -23,7 +23,8 @@
"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} />
@ -77,6 +78,7 @@ class App extends Component {
<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

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

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

@ -6,41 +6,58 @@ import axios from "axios";
// Material UI and React Router
import CircularProgress from '@material-ui/core/CircularProgress';
import Button from '@material-ui/core/Button';
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 TextField from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography";
import withStyles from '@material-ui/styles/withStyles';
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 ReactModal from 'react-modal';
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";
// Redux
import { likePost, unlikePost, getLikes } from '../redux/actions/userActions';
import { likePost, unlikePost, getLikes } from "../redux/actions/userActions";
const styles = {
card: {
marginBottom: 5
}
}
};
class Home extends Component {
state = {
likes: []
likes: [],
loading: false,
following: null,
topics: null
};
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")
.then(res => {
// console.log(res.data);
@ -50,13 +67,23 @@ class Home extends Component {
})
.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) => {
@ -76,22 +103,23 @@ class Home extends Component {
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 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)
this.props.unlikePost(postId, this.state.likes);
doc.dataset.likes--;
} else {
this.props.likePost(postId, this.state.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));
@ -99,10 +127,11 @@ class Home extends Component {
}
render() {
const { UI:{ loading } } = this.props;
const {
UI: { loading }
} = this.props;
let authenticated = this.props.user.authenticated;
let {classes} = this.props;
let { classes } = this.props;
let username = this.props.user.credentials.handle;
console.log(username);
var hiddenBool = true;
@ -112,7 +141,10 @@ class Home extends Component {
console.log(hiddenBool);
let postMarkup = this.state.posts ? (
// <<<<<<< admin-delete
this.state.posts.map(post => post.hidden ? null :
this.state.following ?
this.state.following.includes(post.userHandle) ? (
<Card className={classes.card} key={post.postId}>
<CardContent>
<Typography>
@ -133,7 +165,7 @@ class Home extends Component {
<br />
<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 />
{!hiddenBool &&
<Button
@ -165,49 +197,80 @@ class Home extends Component {
</CardContent>
</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>
);
return (
authenticated ? (
<Grid container>
<Grid item sm={4} xs={8}>
<Writing_Microblogs />
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>
<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>
</div>
)
) : loading ? (
<CircularProgress
size={60}
style={{ marginTop: "300px" }}
></CircularProgress>
) : (
<div>
<div>
<img src={logo} className="app-logo" alt="logo" />
<br />
<br />
<b>Welcome to Twistter!</b>
<br />
<br />
<b>See the most interesting topics people are following right now.</b>
</div>
<br/><br/><br/><br/>
<br />
<br />
<br />
<br />
<div>
<b>Join today or sign in if you already have an account.</b>
<br/><br/>
<form action="./signup">
<button className="authButtons signup">Sign up</button>
</form>
<br/>
<form action="./login">
<button className="authButtons login">Sign in</button>
</form>
</div>
</div>
));
<div>
<b>Join today or sign in if you already have an account.</b>
<br />
<br />
<form action="./signup">
<button className="authButtons signup">Sign up</button>
</form>
<br />
<form action="./login">
<button className="authButtons login">Sign in</button>
</form>
</div>
</div>
);
}
}
@ -218,38 +281,36 @@ class Quote extends Component {
characterCount: 250,
showModal: false,
value: ""
}
};
this.handleSubmitWithoutPost = this.handleSubmitWithoutPost.bind(this);
this.handleOpenModal = this.handleOpenModal.bind(this);
this.handleCloseModal = this.handleCloseModal.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
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",
}
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);
});
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: "" });
}
@ -267,20 +328,19 @@ class Quote extends Component {
handleSubmit(event) {
const quotedPost = {
quoteBody: this.state.value,
userImage: "bing-url",
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);
});
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: "" });
}
@ -288,14 +348,29 @@ class Quote extends Component {
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"}}}
<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
<form style={{ width: "350px" }}>
{/* <textarea
value={this.state.value}
required
maxLength="250"
@ -308,99 +383,109 @@ class Quote extends Component {
cols={40}
rows={20}
/> */}
<TextField
style={{width: 300}}
value={this.state.value}
label="Write Quoted Post here..."
required
multiline
color="primary"
rows="14"
variant="outlined"
inputProps={{
maxLength: 250
}}
onChange={e => {
this.handleChangeforPost(e);
this.handleChangeforCharacterCount(e);
}}
autoComplete='off'
></TextField>
<div style={{ fontSize: "14px", marginRight: "-100px" }}>
<p2>Characters Left: {this.state.characterCount}</p2>
</div>
<Button variant="outlined" color="primary" onClick={this.handleSubmit}>Share Quoted Post</Button>
<Button variant="outlined" color="primary" onClick={this.handleCloseModal}>Cancel</Button>
<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>
</form>
</div>
<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>
<Button
variant="outlined"
color="primary"
onClick={this.handleSubmitWithoutPost}
>
Quote without Post
</Button>
</div>
)
);
}
}
class Like extends Component {
constructor(props) {
super(props)
super(props);
this.state = {
num : this.props.count,
}
num: this.props.count
};
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
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({
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)
{
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);
})
}
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() {
@ -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,
UI: state.UI
})
});
const mapActionsToProps = {
likePost,
unlikePost,
getLikes
}
};
Home.propTypes = {
user: PropTypes.object.isRequired,
@ -456,16 +538,17 @@ Home.propTypes = {
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));
};
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 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";
@ -99,6 +101,7 @@ export class editProfile extends Component {
email: res.data.email,
handle: res.data.handle,
bio: res.data.bio ? res.data.bio : "",
dmEnabled: res.data.dmEnabled === false ? false : true,
pageLoading: false
});
})
@ -121,6 +124,8 @@ export class editProfile extends Component {
email: "",
handle: "",
bio: "",
dmEnabled: false,
togglingDirectMessages: false,
anchorEl: null,
loading: 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) => {
if (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 { errors, loading } = this.state;
// <<<<<<< edit-profile-image-upload
let imageMarkup = this.props.user.credentials.imageUrl ? (
<Box
@ -364,6 +390,18 @@ export class editProfile extends Component {
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"
@ -453,6 +491,7 @@ export class editProfile extends Component {
}
}
const mapStateToProps = (state) => ({
user: state.user,
UI: state.UI,
@ -463,7 +502,9 @@ const mapActionsToProps = { uploadImage }
editProfile.propTypes = {
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);

View File

@ -22,6 +22,7 @@ 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";
@ -77,7 +78,9 @@ class user extends Component {
user: null,
following: null,
posts: null,
myTopics: null
myTopics: null,
followingList: null,
loading: false
};
}
@ -90,7 +93,8 @@ class user extends Component {
.then(res => {
console.log("removed sub");
this.setState({
following: false
following: false,
myTopics: []
});
})
.catch(function(err) {
@ -113,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
})
@ -126,19 +149,26 @@ 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
),
myTopics: res.data.credentials.followedTopics
following: fol,
myTopics: list
});
})
.catch(err => console.log(err));
axios
let posts = axios
.post("/getOtherUsersPosts", {
handle: this.state.profile
})
@ -149,6 +179,44 @@ class user extends Component {
});
})
.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() {
@ -177,8 +245,8 @@ class user extends Component {
<p>loading username...</p>
);
console.log(this.state.topics);
console.log(this.state.myTopics);
// console.log(this.state.topics);
// console.log(this.state.myTopics);
let topicsMarkup = this.state.topics ? (
this.state.topics.map(
topic =>
@ -186,16 +254,20 @@ class user extends Component {
this.state.myTopics.includes(topic) ? (
<MyChip
label={topic}
key={{ topic }.topic.id}
key={{ topic }.id}
onDelete
deleteIcon={<DoneIcon />}
/>
) : (
) : this.state.following ? (
<MyChip
label={topic}
key={{ topic }.topic.id}
key={{ topic }.id}
color="secondary"
clickable
onClick={key => this.handleAdd(topic)}
/>
) : (
<MyChip label={topic} key={{ topic }.id} color="secondary" />
)
) : (
<p></p>
@ -211,10 +283,10 @@ class user extends Component {
) : (
<img src={noImage} height="150" width="150" />
);
//(this.state.posts);
let postMarkup = this.state.posts ? (
this.state.posts.map(post => (
<Card className={classes.card}>
<Card className={classes.card} key={post.postId} data-key={post.postId}>
<CardContent>
<Typography>
{this.state.imageUrl ? (
@ -223,11 +295,11 @@ class user extends Component {
<img src={noImage} height="50" width="50" />
)}
</Typography>
<Typography variant="h7">
<Typography variant="h4">
<b>{post.userHandle}</b>
</Typography>
<Typography variant="body2" color={"textSecondary"}>
{post.createdAt}
{this.formatDate(post.createdAt)}
</Typography>
<br />
@ -253,8 +325,13 @@ class user extends Component {
<p>Posts</p>
);
return (
<Grid container spacing={24}>
return this.state.loading ? (
<CircularProgress
size={60}
style={{ marginTop: "300px" }}
></CircularProgress>
) : (
<Grid container spacing={10}>
<Grid item sm={4} xs={8}>
{imageMarkup}
{profileMarkup}

View File

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

@ -10,6 +10,15 @@ 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';