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() {
@ -171,21 +207,23 @@ 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()
.then(doc => {
if (doc.exists) { if (doc.exists) {
quoteData = doc.data(); quoteData = doc.data();
return quoteDoc.get(); 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 => {
@ -235,21 +273,23 @@ 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()
.then(doc => {
if (doc.exists) { if (doc.exists) {
quoteData = doc.data(); quoteData = doc.data();
return quoteDoc.get(); 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 => {
@ -306,7 +346,9 @@ exports.checkforLikePost = (req, res) => {
.limit(1); .limit(1);
let result; let result;
likedPostDoc.get().then(data => { likedPostDoc
.get()
.then(data => {
if (data.empty) { if (data.empty) {
result = false; result = false;
return res.status(200).json(result); return res.status(200).json(result);
@ -315,49 +357,49 @@ exports.checkforLikePost = (req, res) => {
return res.status(200).json(result); return res.status(200).json(result);
} }
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
return res.status(500).json({ error: err }); return res.status(500).json({ error: err });
}) });
}; };
exports.likePost = (req, res) => { exports.likePost = (req, res) => {
const postId = req.params.postId; const postId = req.params.postId;
let likedPostDoc; let likedPostDoc;
db.doc(`/users/${req.userData.handle}`) db.doc(`/users/${req.userData.handle}`)
.get() .get()
.then((userDoc) => { .then(userDoc => {
let likes = userDoc.data().likes; let likes = userDoc.data().likes;
if (likes === undefined || likes === null) { if (likes === undefined || likes === null) {
likes = []; likes = [];
} }
if (likes.includes(postId)) { if (likes.includes(postId)) {
return res.status(400).json({error: "This user has already liked this post"}); return res
.status(400)
.json({ error: "This user has already liked this post" });
} }
likes.push(postId); likes.push(postId);
return userDoc.ref.update({likes}) return userDoc.ref.update({ likes });
}) })
.then(() => { .then(() => {
return db.doc(`/posts/${postId}`).get() return db.doc(`/posts/${postId}`).get();
}) })
.then((postDoc) => { .then(postDoc => {
let postData = postDoc.data(); let postData = postDoc.data();
postData.likeCount++; postData.likeCount++;
likedPostDoc = postData; likedPostDoc = postData;
return postDoc.ref.update({likeCount : postData.likeCount}) return postDoc.ref.update({ likeCount: postData.likeCount });
}) })
.then(() => { .then(() => {
return res.status(201).json(likedPostDoc); return res.status(201).json(likedPostDoc);
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
return res.status(500).json({ error: err }); return res.status(500).json({ error: err });
}) });
// let postData; // let postData;
// const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle) // const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
@ -395,24 +437,23 @@ exports.likePost = (req, res) => {
// .catch((err) => { // .catch((err) => {
// return res.status(500).json({error: 'Something is wrong'}); // return res.status(500).json({error: 'Something is wrong'});
// }) // })
};
}
exports.unlikePost = (req, res) => { exports.unlikePost = (req, res) => {
const postId = req.params.postId; const postId = req.params.postId;
let likedPostDoc; let likedPostDoc;
db.doc(`/users/${req.userData.handle}`) db.doc(`/users/${req.userData.handle}`)
.get() .get()
.then((userDoc) => { .then(userDoc => {
let likes = userDoc.data().likes; let likes = userDoc.data().likes;
if (likes === undefined || likes === null) { if (likes === undefined || likes === null) {
likes = []; likes = [];
} }
if (!likes.includes(postId)) { if (!likes.includes(postId)) {
return res.status(400).json({error: "This user hasn't liked this post yet"}); return res
.status(400)
.json({ error: "This user hasn't liked this post yet" });
} }
let i; let i;
@ -422,25 +463,24 @@ exports.unlikePost = (req, res) => {
} }
} }
return userDoc.ref.update({likes}) return userDoc.ref.update({ likes });
}) })
.then(() => { .then(() => {
return db.doc(`/posts/${postId}`).get() return db.doc(`/posts/${postId}`).get();
}) })
.then((postDoc) => { .then(postDoc => {
let postData = postDoc.data(); let postData = postDoc.data();
postData.likeCount--; postData.likeCount--;
likedPostDoc = postData; likedPostDoc = postData;
return postDoc.ref.update({likeCount : postData.likeCount}) return postDoc.ref.update({ likeCount: postData.likeCount });
}) })
.then(() => { .then(() => {
return res.status(201).json(likedPostDoc); return res.status(201).json(likedPostDoc);
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
return res.status(500).json({ error: err }); return res.status(500).json({ error: err });
}) });
// let postData; // let postData;
// const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle) // const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
@ -476,32 +516,28 @@ exports.unlikePost = (req, res) => {
// console.error(err); // console.error(err);
// return res.status(500).json({error: 'Something is wrong'}); // return res.status(500).json({error: 'Something is wrong'});
// }) // })
};
}
exports.getLikes = (req, res) => { exports.getLikes = (req, res) => {
db.doc(`/users/${req.userData.handle}`) db.doc(`/users/${req.userData.handle}`)
.get() .get()
.then((doc) => { .then(doc => {
let likes = doc.data().likes; let likes = doc.data().likes;
if (likes === undefined || likes === null) { if (likes === undefined || likes === null) {
likes = []; likes = [];
} }
return res.status(200).json({ likes }); return res.status(200).json({ likes });
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
return res.status(500).json({ error: err }); return res.status(500).json({ error: err });
}) });
} };
exports.getFilteredPosts = (req, res) => { exports.getFilteredPosts = (req, res) => {
admin admin
.firestore() .firestore()
.collection("posts") .collection("posts")
.where("userHandle", "==", "new user") .where("userHandle", "==", "new user")
.where("microBlogTopics", "=="); .where("microBlogTopics", "==");
}; };

View File

@ -26,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()

View File

@ -163,11 +163,13 @@ exports.login = (req, res) => {
return; return;
}) })
.catch(function(err) { .catch(function(err) {
if (!doc.exists) { // FIX: doc variable is out of scope
return res // if (!doc.exists) {
.status(403) // return res
.json({ general: "Invalid credentials. Please try again." }); // .status(403)
} // .json({ general: "Invalid credentials. Please try again." });
// }
console.log(err);
return res.status(500).send(err); return res.status(500).send(err);
}); });
} }
@ -224,7 +226,7 @@ exports.deleteUser = (req, res) => {
const deleteUsername = req.userData.handle; const deleteUsername = req.userData.handle;
db.doc(`/users/${deleteUsername}`) db.doc(`/users/${deleteUsername}`)
.get() .get()
.then((deleteUserDocSnap) => { .then(deleteUserDocSnap => {
const dms = deleteUserDocSnap.data().dms; const dms = deleteUserDocSnap.data().dms;
const dmRecipients = deleteUserDocSnap.data().dmRecipients; const dmRecipients = deleteUserDocSnap.data().dmRecipients;
@ -237,25 +239,32 @@ exports.deleteUser = (req, res) => {
let otherUsersPromises = []; let otherUsersPromises = [];
// Resolve if they don't have a dmRecipients list // Resolve if they don't have a dmRecipients list
if (dmRecipients === undefined || dmRecipients === null || dmRecipients.length === 0) { if (
dmRecipients === undefined ||
dmRecipients === null ||
dmRecipients.length === 0
) {
resolve(); resolve();
return; return;
} }
dmRecipients.forEach((dmRecipient) => { dmRecipients.forEach(dmRecipient => {
otherUsersPromises.push( otherUsersPromises.push(
// Get each users data // Get each users data
db.doc(`/users/${dmRecipient}`).get() db
.then((otherUserDocSnap) => { .doc(`/users/${dmRecipient}`)
.get()
.then(otherUserDocSnap => {
// Get the index of deleteUsername so that we can remove the dangling // Get the index of deleteUsername so that we can remove the dangling
// reference to the DM document // reference to the DM document
let otherUserDMRecipients = otherUserDocSnap.data().dmRecipients; let otherUserDMRecipients = otherUserDocSnap.data()
.dmRecipients;
let otherUserDMs = otherUserDocSnap.data().dms; let otherUserDMs = otherUserDocSnap.data().dms;
let index = -1; let index = -1;
otherUserDMRecipients.forEach((dmRecip, i) => { otherUserDMRecipients.forEach((dmRecip, i) => {
if (dmRecip === deleteUsername) { if (dmRecip === deleteUsername) {
index = i; index = i;
} }
}) });
if (index !== -1) { if (index !== -1) {
// Remove deleteUsername from their dmRecipients list // Remove deleteUsername from their dmRecipients list
@ -270,28 +279,29 @@ exports.deleteUser = (req, res) => {
dms: otherUserDMs dms: otherUserDMs
}); });
} }
})
)
}) })
);
});
// Wait for the removal of DM data stored on other users to be deleted // Wait for the removal of DM data stored on other users to be deleted
Promise.all(otherUsersPromises) Promise.all(otherUsersPromises)
.then(() => { .then(() => {
// Iterate through DM references and delete them from the dm collection // Iterate through DM references and delete them from the dm collection
let dmRefsPromises = []; let dmRefsPromises = [];
dms.forEach((dmRef) => { dms.forEach(dmRef => {
// Create a delete queue // Create a delete queue
let batch = db.batch(); let batch = db.batch();
dmRefsPromises.push( dmRefsPromises.push(
// Add the messages to the delete queue // Add the messages to the delete queue
db.collection(`/dm/${dmRef.id}/messages`).listDocuments() db
.then((docs) => { .collection(`/dm/${dmRef.id}/messages`)
console.log("second") .listDocuments()
.then(docs => {
console.log("second");
console.log(docs); console.log(docs);
docs.map((doc) => { docs.map(doc => {
batch.delete(doc); batch.delete(doc);
}) });
// Add the doc that the DM is stored in to the delete queue // Add the doc that the DM is stored in to the delete queue
batch.delete(dmRef); batch.delete(dmRef);
@ -299,8 +309,8 @@ exports.deleteUser = (req, res) => {
// Commit the writes // Commit the writes
return batch.commit(); return batch.commit();
}) })
) );
}) });
return Promise.all(dmRefsPromises); return Promise.all(dmRefsPromises);
}) })
@ -308,18 +318,17 @@ exports.deleteUser = (req, res) => {
resolve(); resolve();
return; return;
}) })
.catch((err) => { .catch(err => {
console.log("error " + err); console.log("error " + err);
reject(err); reject(err);
return; return;
});
}) })
}) .catch(err => {
.catch((err) => {
console.log(err); console.log(err);
return res.status(500).json({ error: err }); return res.status(500).json({ error: err });
}) });
});
})
} }
// Deletes user from authentication // Deletes user from authentication
@ -332,18 +341,18 @@ exports.deleteUser = (req, res) => {
return db return db
.collection("users") .collection("users")
.doc(`${req.user.handle}`) .doc(`${req.user.handle}`)
.delete() .delete();
}) })
.then(() => { .then(() => {
resolve(); resolve();
return; return;
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
reject(err); reject(err);
return; return;
}) });
}) });
// Deletes any custom profile image // Deletes any custom profile image
let image; let image;
@ -452,15 +461,16 @@ exports.getUserDetails = (req, res) => {
exports.getAllHandles = (req, res) => { exports.getAllHandles = (req, res) => {
var user_query = admin.firestore().collection("users"); var user_query = admin.firestore().collection("users");
user_query.get() user_query
.then((allUsers) => { .get()
.then(allUsers => {
let users = []; let users = [];
allUsers.forEach((user) => { allUsers.forEach(user => {
users.push(user.data().handle); users.push(user.data().handle);
}); });
return res.status(200).json(users); return res.status(200).json(users);
}) })
.catch((err) => { .catch(err => {
return res.status(500).json({ return res.status(500).json({
message: "Failed to retrieve posts from database.", message: "Failed to retrieve posts from database.",
error: err error: err
@ -552,6 +562,614 @@ exports.unverifyUser = (req, res) => {
return res.status(500).json({ error: err.code }); return res.status(500).json({ error: err.code });
}); });
}; };
// Returns all the DMs that the user is currently participating in
exports.getDirectMessages = (req, res) => {
/* Return value
* data: [DMs]
* dm : {
* dmId: str
* messages: [msgs]
* msg: {
* author: str
* createdAt: ISOString
* message: str
* messageId: str
* }
* recipient: str
* hasDirectMessagesEnabled: bool
* recentMessage: str
* recentMessageTimestamp: ISOString
* }
*/
// Returns all the messages in a dm documentSnapshot
function getMessages(dm) {
let promise = new Promise((resolve, reject) => {
let messagesCollection = dm.collection("messages");
// If the messagesCollection is missing, that means that there aren't any messages
if (messagesCollection === null || messagesCollection === undefined) {
return;
}
let msgs = [];
let promises = [];
// Get all of the messages in the DM
messagesCollection.get().then(dmQuerySnap => {
dmQuerySnap.forEach(dmQueryDocSnap => {
promises.push(
dmQueryDocSnap.ref.get().then(messageData => {
msgs.push(messageData.data());
return;
})
);
});
let waitPromise = Promise.all(promises);
waitPromise.then(() => {
// Sort the messages in reverse order by date
// Newest should be at the bottom, because that's how they will be displayed on the front-end
msgs.sort((a, b) => {
return b.createdAt > a.createdAt
? -1
: b.createdAt < a.createdAt
? 1
: 0;
});
resolve(msgs);
});
});
});
return promise;
}
const dms = req.userData.dms;
const dmRecipients = req.userData.dmRecipients;
// Return null if this user has no DMs
if (dms === undefined || dms === null || dms.length === 0)
return res.status(200).json({ data: null });
let dmsData = [];
let dmPromises = [];
dms.forEach(dm => {
let dmData = {};
// Make a new promise for each DM document
dmPromises.push(
new Promise((resolve, reject) => {
dm.get() // DM document reference
.then(doc => {
let docData = doc.data();
// Recipient is the person you are messaging
docData.authors[0] === req.userData.handle
? (dmData.recipient = docData.authors[1])
: (dmData.recipient = docData.authors[0]);
// Save the createdAt time
dmData.createdAt = docData.createdAt;
// Get all the messages from this dm document
getMessages(dm).then(msgs => {
dmData.messages = msgs;
dmData.recentMessage =
msgs.length !== 0 ? msgs[msgs.length - 1].message : null;
dmData.recentMessageTimestamp =
msgs.length !== 0 ? msgs[msgs.length - 1].createdAt : null;
dmData.dmId = doc.id;
resolve(dmData);
});
})
.catch(err => {
console.err(err);
return res.status(400).json({
error: {
message:
"An error occurred when reading the DM document reference",
error: err
}
});
});
}).then(dmData => {
dmsData.push(dmData);
})
);
});
// Get all the data from the users to get the data on whether they have DMs enabled or not
let userPromises = [];
dmRecipients.forEach(recipient => {
userPromises.push(db.doc(`/users/${recipient}`).get());
});
// Wait for all DM document promises to resolve before returning data
Promise.all(dmPromises)
.then(() => {
return Promise.all(userPromises);
})
.then(userData => {
// Sort the DMs so that the ones with the newest messages are at the top
dmsData.sort((a, b) => {
if (
a.recentMessageTimestamp === null &&
b.recentMessageTimestamp === null
) {
if (b.createdAt < a.createdAt) {
return -1;
} else if (b.createdAt > a.createdAt) {
return 1;
} else {
return 0;
}
} else if (a.recentMessageTimestamp === null) {
return 1;
} else if (b.recentMessageTimestamp === null) {
return -1;
} else if (b.recentMessageTimestamp < a.recentMessageTimestamp) {
return -1;
} else if (b.recentMessageTimestamp > a.recentMessageTimestamp) {
return 1;
} else {
return 0;
}
});
dmsData.forEach(dm => {
dm.hasDirectMessagesEnabled =
userData
.find(user => {
if (dm.recipient === user.data().handle) {
return true;
} else {
return false;
}
})
.data().dmEnabled === false
? false
: true;
});
return res.status(200).json({ data: dmsData });
})
.catch(err => {
return res.status(500).json({
error: {
message: "An error occurred while sorting",
error: err
}
});
});
};
// Toggles direct messages on or off depending on the requese
/* Request Parameters
* enable: bool
*/
exports.toggleDirectMessages = (req, res) => {
const enable = req.body.enable;
const user = req.userData.handle;
db.doc(`/users/${user}`)
.update({ dmEnabled: enable })
.then(() => {
return res.status(201).json({ message: "Success" });
})
.catch(err => {
return res.status(500).json({ error: err });
});
};
// Returns a promise that resolves if user has DMs enabled
// and rejects if there is an error or DMs are disabled
isDirectMessageEnabled = username => {
return new Promise((resolve, reject) => {
let result = {};
result.code = null;
result.message = null;
if (username === null || username === undefined || username === "") {
result.code = 400;
result.message =
"No user was sent in the request. The request should have a non-empty 'user' key.";
reject(result);
}
db.doc(`/users/${username}`)
.get()
.then(doc => {
if (doc.exists) {
// console.log(doc.data())
if (
doc.data().dmEnabled === true ||
doc.data().dmEnabled === null ||
doc.data().dmEnabled === undefined
) {
// Assume DMs are enabled if they don't have a dmEnabled key
resolve(result);
} else {
result.code = 400;
result.message = `${username} has DMs disabled`;
reject(result);
}
} else {
console.log(`${username} is not in the database`);
result.code = 400;
result.message = `${username} is not in the database`;
reject(result);
}
})
.catch(err => {
console.log("HI");
console.error(err);
result.code = 500;
result.message = err;
reject(result);
});
});
};
// Returns a promise that resolves if the data in the DM is valid and
// rejects if there are any error. Errors are returned in the promise
verifyDirectMessageIntegrity = dmRef => {
return new Promise((resolve, reject) => {
resolve("Not implemented yet");
});
};
// Checks if there are any DM channels open with userB on userA's side
oneWayCheck = (userA, userB) => {
return new Promise((resolve, reject) => {
db.doc(`/users/${userA}`)
.get()
.then(userASnapshot => {
const dmList = userASnapshot.data().dms;
const dmRecipients = userASnapshot.data().dmRecipients;
if (
dmList === null ||
dmList === undefined ||
dmRecipients === null ||
dmRecipients === undefined
) {
// They don't have any DMs yet
console.log("No DMs array");
userASnapshot.ref
.set({ dms: [], dmRecipients: [] }, { merge: true })
.then(() => {
resolve();
});
} else if (dmList.length === 0) {
// Their DMs are empty
console.log("DMs array is empty");
resolve();
} else {
// let dmDocs = [];
// let forEachPromises = [];
// dmList.forEach((dmRef) => {
// forEachPromises.push(
// dmRef.get()
// // .then((dmDoc) => {
// // TODO: Figure out why dmDoc.exists() isn't working
// // Make sure all of the docs exist and none of the references
// // are broken
// // if (dmDoc.exists()) {
// // dmDocs.push(dmDoc);
// // } else {
// // console.log(`DM reference /dm/${dmDoc.id} is invalid`);
// // reject(`DM reference /dm/${dmDoc.id} is invalid`);
// // }
// // })
// )
// })
dmRecipients.forEach(dmRecipient => {
if (dmRecipient === userB) {
console.log(`You already have a DM with ${userB}`);
// reject(new Error(`You already have a DM with ${userB}`));
reject({
code: 400,
message: `You already have a DM with that user`
});
return;
}
});
resolve();
// Promise.all(forEachPromises)
// .then((dmDocs) => {
// // Check if any of the DMs have for userA have userA and userB as the authors.
// // This would mean that they already have a DM channel
// dmDocs.forEach((dmDoc) => {
// // Checking if any of the authors key in any of their DMs are missing
// let authors = dmDoc.data().authors;
// // if (authors[0] === "keanureeves") {
// // console.log("it is")
// // resolve();
// // } else {
// // console.log("it is not")
// // reject("not my keanu");
// // }
// // if (authors === null || authors === undefined || authors.length !== 2) {
// // // console.log(`The authors key in /dm/${dmDoc.id} is undefined or missing values`);
// // // reject(`The authors key in /dm/${dmDoc.id} is undefined or missing values`);
// // console.log('a')
// // reject("a")
// // } else if ((authors[0] === userA && authors[1] === userB) || (authors[1] === userA && authors[0] === userB)) {
// // // console.log(`${userA} already has a DM channel between ${userA} and ${userB}`);
// // // reject(`${userA} already has a DM channel between ${userA} and ${userB}`);
// // console.log('b')
// // reject('b')
// // } else {
// // // BUG: For some reason the promise.all is resolving even though there are multiple rejects
// // // and only one resolve
// // console.log("c");
// // resolve();
// // }
// // console.log(authors)
// // console.log([userA, userB])
// if (authors[0] === null || authors === undefined || authors.length !== 2) {
// console.log('a');
// reject('a');
// } else if (authors[0] === userA && authors[1] === userB) {
// console.log("b");
// reject('b');
// } else {
// console.log('c');
// resolve();
// }
// })
// })
}
});
});
};
// Returns a promise that resolves if there is not already a DM channel
// between the creator and recipient usernames. It rejects if one already
// exists or there is an error.
checkNoDirectMessageExists = (creator, recipient) => {
return new Promise((resolve, reject) => {
let creatorPromise = oneWayCheck(creator, recipient);
let recipientPromise = oneWayCheck(recipient, creator);
let temp_array = [];
temp_array.push(creatorPromise);
temp_array.push(recipientPromise);
Promise.all(temp_array)
.then(() => {
resolve();
})
.catch(err => {
reject(err);
});
});
};
addDirectMessageToUser = (username, recipient, dmRef) => {
return new Promise((resolve, reject) => {
db.doc(`/users/${username}`)
.get()
.then(docSnap => {
let dmList = docSnap.data().dms;
let dmRecipients = docSnap.data().dmRecipients;
dmList.push(dmRef);
dmRecipients.push(recipient);
return db
.doc(`/users/${username}`)
.update({ dms: dmList, dmRecipients });
})
.then(() => {
resolve();
})
.catch(err => {
reject(err);
});
});
};
// Sends a DM from the caller to the requested DM document
/* Request Parameters
* message: str
* user: str
*/
exports.sendDirectMessage = (req, res) => {
// TODO: add error checking for if message or user is null
const creator = req.userData.handle;
const recipient = req.body.user;
const message = req.body.message;
const newMessage = {
author: creator,
createdAt: new Date().toISOString(),
message,
messageId: null
};
db.doc(`/users/${recipient}`)
.get()
.then(recipDoc => {
// Return if the other user has DM's disabled
if (
recipDoc.data().dmEnabled === false &&
recipDoc.data().dmEnabled !== null &&
recipDoc.data().dmEnabled !== undefined
) {
return res.status(400).json({ error: "This user has DMs disabled" });
}
});
db.doc(`/users/${creator}`)
.get()
.then(userDoc => {
let dmList = userDoc.data().dms;
// Return if the creator doesn't have any DMs.
// This means they have not created a DM's channel yet
if (dmList === null || dmList === undefined) {
return res
.status(400)
.json({
error: `There is no DM channel between ${creator} and ${recipient}. Use /api/dms/new.`
});
}
let dmRefPromises = [];
dmList.forEach(dmRef => {
dmRefPromises.push(
new Promise((resolve, reject) => {
dmRef
.get()
.then(dmDoc => {
let authors = dmDoc.data().authors;
if (
(authors[0] === creator && authors[1] === recipient) ||
(authors[1] === creator && authors[0] === recipient)
) {
resolve({ correct: true, dmRef });
} else {
resolve({ correct: false, dmRef });
}
})
.catch(err => {
reject(err);
});
})
);
});
return Promise.all(dmRefPromises);
})
.then(results => {
let correctDMRef = null;
results.forEach(result => {
if (result.correct) {
correctDMRef = result.dmRef;
}
});
if (correctDMRef === null) {
console.log(
`There is no DM channel between ${creator} and ${recipient}. Use /api/dms/new.`
);
return res.status(400).json({
error: `There is no DM channel between ${creator} and ${recipient}. Use /api/dms/new.`
});
}
return db.collection(`/dm/${correctDMRef.id}/messages`).add(newMessage);
})
.then(newMsgRef => {
return newMsgRef.update({ messageId: newMsgRef.id }, { merge: true });
})
.then(() => {
return res.status(200).json({ message: "OK" });
})
.catch(err => {
console.log(err);
return res.status(500).json({ error: err });
});
};
// Creates a DM between the caller and the user in the request
/* Request Parameters
* user: str
*/
exports.createDirectMessage = (req, res) => {
const creator = req.userData.handle;
const recipient = req.body.user;
// Check if they are DMing themselves
if (creator === recipient)
return res.status(400).json({ error: "You can't DM yourself" });
// Check if this user has DMs enabled
let creatorEnabled = isDirectMessageEnabled(creator);
// Check if the requested user has DMs enabled
let recipientEnabled = isDirectMessageEnabled(recipient);
// Make sure that they don't already have a DM channel
let noDMExists = checkNoDirectMessageExists(creator, recipient);
let dataValidations = [creatorEnabled, recipientEnabled, noDMExists];
Promise.all(dataValidations)
.then(() => {
// Create a new DM document
return db.collection("dm").add({});
})
.then(dmDocRef => {
// Fill it with some data.
// Note that there isn't a messages collection by default.
let dmData = {
dmId: dmDocRef.id,
authors: [creator, recipient],
createdAt: new Date().toISOString()
};
// Update DM document
let dmDocPromise = dmDocRef.set(dmData);
// Add the DM reference to the creator
let updateCreatorPromise = addDirectMessageToUser(
creator,
recipient,
dmDocRef
);
// Add the DM reference to the recipient
let updateRecipientPromise = addDirectMessageToUser(
recipient,
creator,
dmDocRef
);
// Wait for all promises
return Promise.all([
dmDocPromise,
updateCreatorPromise,
updateRecipientPromise
]);
})
.then(() => {
return res.status(201).json({ message: "Success!" });
})
.catch(err => {
console.log(err);
if (err.code && err.message && err.code > 0) {
// Specific error that I've created
return res.status(err.code).json({ error: err.message });
} else {
// Generic or firebase error
return res.status(500).json({ error: err });
}
});
};
// Checks if the requested user has DMs enable or not
/* Request Parameters
* user: str
*/
exports.checkDirectMessagesEnabled = (req, res) => {
isDirectMessageEnabled(req.body.user)
.then(() => {
return res.status(200).json({ enabled: true });
})
.catch(result => {
console.log(result);
if (result.code === 200) {
// DMs are disabled
return res.status(200).json({ enabled: false });
} else {
// Some other error occured
return res.status(result.code).json({ err: result.message });
}
});
};
exports.getUserHandles = (req, res) => { exports.getUserHandles = (req, res) => {
db.doc(`/users/${req.body.userHandle}`) db.doc(`/users/${req.body.userHandle}`)
.get() .get()
@ -574,7 +1192,13 @@ exports.addSubscription = (req, res) => {
let userRef = db.doc(`/users/${req.userData.handle}`); let userRef = db.doc(`/users/${req.userData.handle}`);
userRef.get().then(doc => { userRef.get().then(doc => {
new_following = doc.data().following; new_following = doc.data().following;
new_following.push(req.body.following); const struct = {
handle: req.body.following,
topics: ["Admin"]
};
new_following
? new_following.push(struct)
: (new_following = req.body.following);
// add stuff // add stuff
userRef userRef
@ -587,7 +1211,7 @@ exports.addSubscription = (req, res) => {
.catch(err => { .catch(err => {
return res.status(500).json({ err }); return res.status(500).json({ err });
}); });
return res.status(200).json({ message: "ok" }); // return res.status(200).json({ message: "ok" });
}); });
}; };
@ -615,25 +1239,32 @@ exports.uploadProfileImage = (req, res) => {
let imageFileName; let imageFileName;
let imageToBeUploaded = {}; let imageToBeUploaded = {};
let oldImageFileName = req.userData.imageUrl ? req.userData.imageUrl.split("/o/")[1].split("?alt")[0] : null; let oldImageFileName = req.userData.imageUrl
? req.userData.imageUrl.split("/o/")[1].split("?alt")[0]
: null;
// console.log(`old file: ${oldImageFileName}`); // console.log(`old file: ${oldImageFileName}`);
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => { busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') { if (mimetype !== "image/jpeg" && mimetype !== "image/png") {
return res.status(400).json({ error: "Wrong filetype submitted" }); return res.status(400).json({ error: "Wrong filetype submitted" });
} }
// console.log(fieldname); // console.log(fieldname);
// console.log(filename); // console.log(filename);
// console.log(mimetype); // console.log(mimetype);
const imageExtension = filename.split(".")[filename.split(".").length - 1]; // Get the image file extension const imageExtension = filename.split(".")[filename.split(".").length - 1]; // Get the image file extension
imageFileName = `${Math.round(Math.random() * 100000000000)}.${imageExtension}`; // Get a random filename imageFileName = `${Math.round(
Math.random() * 100000000000
)}.${imageExtension}`; // Get a random filename
const filepath = path.join(os.tmpdir(), imageFileName); const filepath = path.join(os.tmpdir(), imageFileName);
imageToBeUploaded = { filepath, mimetype }; imageToBeUploaded = { filepath, mimetype };
file.pipe(fs.createWriteStream(filepath)); file.pipe(fs.createWriteStream(filepath));
}); });
busboy.on("finish", () => { busboy.on("finish", () => {
// Save the file to the storage bucket // Save the file to the storage bucket
admin.storage().bucket(config.storageBucket).upload(imageToBeUploaded.filepath, { admin
.storage()
.bucket(config.storageBucket)
.upload(imageToBeUploaded.filepath, {
resumable: false, resumable: false,
metadata: { metadata: {
metadata: { metadata: {
@ -649,24 +1280,33 @@ exports.uploadProfileImage = (req, res) => {
.then(() => { .then(() => {
// Delete their old image if they have one // Delete their old image if they have one
if (oldImageFileName !== null && oldImageFileName !== "no-img.png") { if (oldImageFileName !== null && oldImageFileName !== "no-img.png") {
admin.storage().bucket(config.storageBucket).file(oldImageFileName).delete() admin
.storage()
.bucket(config.storageBucket)
.file(oldImageFileName)
.delete()
.then(() => { .then(() => {
return res.status(201).json({ message: "Image uploaded successfully1"}); return res
.status(201)
.json({ message: "Image uploaded successfully1" });
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
return res.status(201).json({ message: "Image uploaded successfully2"}); return res
}) .status(201)
.json({ message: "Image uploaded successfully2" });
});
// return res.status(201).json({ message: "Image uploaded successfully"}); // return res.status(201).json({ message: "Image uploaded successfully"});
} else { } else {
return res.status(201).json({ message: "Image uploaded successfully3"}); return res
.status(201)
.json({ message: "Image uploaded successfully3" });
} }
}) })
.catch((err) => { .catch(err => {
console.error(err); console.error(err);
return res.status(500).json({ error: err.code}) return res.status(500).json({ error: err.code });
}) });
}); });
busboy.end(req.rawBody); busboy.end(req.rawBody);
@ -722,7 +1362,7 @@ exports.uploadProfileImage = (req, res) => {
// }); // });
// }); // });
// busboy.end(req.rawBody); // busboy.end(req.rawBody);
} };
exports.removeSub = (req, res) => { exports.removeSub = (req, res) => {
let new_following = []; let new_following = [];
@ -731,7 +1371,7 @@ exports.removeSub = (req, res) => {
new_following = doc.data().following; new_following = doc.data().following;
// remove username from array // remove username from array
new_following.forEach(function(follower, index) { new_following.forEach(function(follower, index) {
if (follower === `${req.body.unfollow}`) { if (follower.handle === `${req.body.unfollow}`) {
new_following.splice(index, 1); new_following.splice(index, 1);
} }
}); });

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,8 +127,9 @@ 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;
@ -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,13 +197,35 @@ 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 ? (
<CircularProgress
size={60}
style={{ marginTop: "300px" }}
></CircularProgress>
) : (
<Grid container> <Grid container>
<Grid item sm={4} xs={8}> <Grid item sm={4} xs={8}>
<Writing_Microblogs /> <Writing_Microblogs />
@ -180,24 +234,33 @@ class Home extends Component {
{postMarkup} {postMarkup}
</Grid> </Grid>
</Grid> </Grid>
) : loading ? )
(<CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress>) ) : loading ? (
: <CircularProgress
( size={60}
style={{ marginTop: "300px" }}
></CircularProgress>
) : (
<div> <div>
<div> <div>
<img src={logo} className="app-logo" alt="logo" /> <img src={logo} className="app-logo" alt="logo" />
<br/><br/> <br />
<br />
<b>Welcome to Twistter!</b> <b>Welcome to Twistter!</b>
<br/><br/> <br />
<br />
<b>See the most interesting topics people are following right now.</b> <b>See the most interesting topics people are following right now.</b>
</div> </div>
<br/><br/><br/><br/> <br />
<br />
<br />
<br />
<div> <div>
<b>Join today or sign in if you already have an account.</b> <b>Join today or sign in if you already have an account.</b>
<br/><br/> <br />
<br />
<form action="./signup"> <form action="./signup">
<button className="authButtons signup">Sign up</button> <button className="authButtons signup">Sign up</button>
</form> </form>
@ -207,7 +270,7 @@ class Home extends Component {
</form> </form>
</div> </div>
</div> </div>
)); );
} }
} }
@ -218,7 +281,7 @@ class Quote extends Component {
characterCount: 250, characterCount: 250,
showModal: false, showModal: false,
value: "" value: ""
} };
this.handleSubmitWithoutPost = this.handleSubmitWithoutPost.bind(this); this.handleSubmitWithoutPost = this.handleSubmitWithoutPost.bind(this);
this.handleOpenModal = this.handleOpenModal.bind(this); this.handleOpenModal = this.handleOpenModal.bind(this);
@ -228,19 +291,17 @@ class Quote extends Component {
handleSubmitWithoutPost(event) { handleSubmitWithoutPost(event) {
const post = { const post = {
userImage: "bing-url"
userImage: "bing-url", };
}
const headers = { const headers = {
headers: { "Content-Type": "application/json" } headers: { "Content-Type": "application/json" }
}; };
axios.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();
@ -267,18 +328,17 @@ 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();
@ -288,10 +348,25 @@ class Quote extends Component {
render() { render() {
return ( return (
<div> <div>
<Button variant="outlined" color="primary" onClick={this.handleOpenModal}>Quote with Post</Button> <Button
variant="outlined"
color="primary"
onClick={this.handleOpenModal}
>
Quote with Post
</Button>
<ReactModal <ReactModal
isOpen={this.state.showModal} isOpen={this.state.showModal}
style={{content: {height: "50%", width: "25%", marginTop: "auto", marginLeft: "auto", marginRight: "auto", marginBottom : "auto"}}} 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" }}>
@ -324,83 +399,93 @@ class Quote extends Component {
this.handleChangeforPost(e); this.handleChangeforPost(e);
this.handleChangeforCharacterCount(e); this.handleChangeforCharacterCount(e);
}} }}
autoComplete='off' autoComplete="off"
></TextField> ></TextField>
<div style={{ fontSize: "14px", marginRight: "-100px" }}> <div style={{ fontSize: "14px", marginRight: "-100px" }}>
<p2>Characters Left: {this.state.characterCount}</p2> <p2>Characters Left: {this.state.characterCount}</p2>
</div> </div>
<Button variant="outlined" color="primary" onClick={this.handleSubmit}>Share Quoted Post</Button> <Button
variant="outlined"
<Button variant="outlined" color="primary" onClick={this.handleCloseModal}>Cancel</Button> color="primary"
onClick={this.handleSubmit}
>
Share Quoted Post
</Button>
<Button
variant="outlined"
color="primary"
onClick={this.handleCloseModal}
>
Cancel
</Button>
</form> </form>
</div> </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.get(`/like/${this.props.microBlog}`) axios
.then((res) => { .get(`/like/${this.props.microBlog}`)
.then(res => {
console.log(res.data); console.log(res.data);
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
})
}
else
{
this.setState(() => {
return {num: this.state.num - 1}
}); });
axios.get(`/unlike/${this.props.microBlog}`) } else {
.then((res) => { this.setState(() => {
return { num: this.state.num - 1 };
});
axios
.get(`/unlike/${this.props.microBlog}`)
.then(res => {
console.log(res.data); console.log(res.data);
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
}) });
} }
} }
/* componentDidMount() { /* componentDidMount() {
@ -423,31 +508,28 @@ class Like extends Component {
} */ } */
render() { render() {
const label = this.state.like ? "Unlike" : "Like";
const label = this.state.like ? 'Unlike' : 'Like'
return ( return (
<div> <div>
<Typography variant="body2" color={"textSecondary"}>Likes {this.state.num}</Typography> <Typography variant="body2" color={"textSecondary"}>
Likes {this.state.num}
</Typography>
<button onClick={this.handleClick}>{label}</button> <button onClick={this.handleClick}>{label}</button>
</div> </div>
) );
}
} }
} const mapStateToProps = state => ({
const mapStateToProps = (state) => ({
user: state.user, user: state.user,
UI: state.UI UI: state.UI
}) });
const mapActionsToProps = { const mapActionsToProps = {
likePost, likePost,
unlikePost, unlikePost,
getLikes getLikes
} };
Home.propTypes = { Home.propTypes = {
user: PropTypes.object.isRequired, user: PropTypes.object.isRequired,
@ -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';