Compare commits

..

48 Commits

Author SHA1 Message Date
shobhitm23
49ce28109b Improved Fonts 2019-11-01 16:15:45 -04:00
shobhitm23
3f24d90fef Merge branch 'Beautify' 2019-11-01 15:37:54 -04:00
shobhitm23
d3bfd8b5f3 Fixing UI 2019-11-01 15:36:22 -04:00
d6876eab0b Fix .then() must return 2019-11-01 14:28:49 -04:00
d4ea00d2e9 Merge pull request #72 from ClaytonWWilson/fix-delete
Fix delete
2019-11-01 13:26:25 -04:00
acd33d6a96 Merge branch 'master' into fix-delete 2019-11-01 13:26:11 -04:00
f1e4362205 Change imageFileName from const to let 2019-11-01 00:37:49 -04:00
1e4b2d16ef Fix edge case 2019-11-01 00:29:22 -04:00
e8e69cec31 Delete removes all data now 2019-11-01 00:26:01 -04:00
Leon Liang
ae89e3d63b Merge pull request #69 from ClaytonWWilson/search_page
added search page
2019-10-31 16:57:38 -04:00
Leon Liang
f60c045483 Merge branch 'master' into search_page 2019-10-31 16:57:22 -04:00
Leon Liang
1842eef2f8 added search page 2019-10-31 16:54:34 -04:00
56323801aa Merge pull request #65 from ClaytonWWilson/auth-backend-3
Auth backend 3
2019-10-31 16:14:22 -04:00
ce984df437 Merge branch 'master' into auth-backend-3 2019-10-31 16:09:17 -04:00
Leon Liang
35e5cf8e9d revert changes that I f ed up 2019-10-31 15:11:16 -04:00
Leon Liang
649b9b4a69 Merge pull request #68 from ClaytonWWilson/delete_topic
Delete topic
2019-10-31 14:44:41 -04:00
Leon Liang
e73b2d02f3 Merge branch 'master' into delete_topic 2019-10-31 14:44:03 -04:00
Leon Liang
50bc73870b delete topic fully works 2019-10-31 14:32:54 -04:00
Aaron Sun
da14700987 Fixed a small bug with the Delete Account button 2019-10-30 18:15:01 -04:00
Aaron Sun
26afabe709 All posts from db can now show on home page timeline 2019-10-30 18:04:35 -04:00
Aaron Sun
a61c296ddf Made the posts look prettier 2019-10-30 16:12:53 -04:00
Aaron Sun
1337071bec UI can now display all features of a post 2019-10-30 15:07:19 -04:00
Aaron Sun
cd19364efc Can now display post body on profile page 2019-10-30 11:40:44 -04:00
Aaron Sun
8438ce27cf Get user's posts works now 2019-10-29 22:25:38 -04:00
Aaron Sun
6db14e3868 Improved the profile page format 2019-10-29 19:39:11 -04:00
DreamCoder23
16567e2373 Merge pull request #63 from ClaytonWWilson/auth-backend-3
Auth backend 3
2019-10-29 14:40:02 -04:00
Aaron Sun
d3a77afe43 Pulled and merged the latest code from master 2019-10-29 14:02:56 -04:00
Aaron Sun
42b73632c0 Delete user's posts fully works now 2019-10-29 10:34:09 -04:00
Leon Liang
b20408c144 delete topic 2019-10-28 21:38:32 -04:00
Aaron Sun
c482f56762 Invalid credential message displays after non-exisitng email is passed in 2019-10-28 20:14:38 -04:00
Aaron Sun
9525ff7d0a Delete post works in Postman but not in actual database 2019-10-28 17:57:03 -04:00
Shobhit Makhija
f602b8251f Merge pull request #61 from ClaytonWWilson/filteredPosts
Arrow-callback warning
2019-10-28 01:34:43 -04:00
Aaron Sun
657277bcad Username and user id now show in post data 2019-10-27 23:11:24 -04:00
Aaron Sun
d69828ef7f Merge branch 'master' of https://github.com/ClaytonWWilson/CS307-Team24 into auth-backend-3 2019-10-27 20:48:15 -04:00
Aaron Sun
5fa4caf0a3 Log in with username fully works now 2019-10-27 17:47:04 -04:00
Aaron Sun
fd226b454e Delete users fully works now 2019-10-27 14:46:31 -04:00
Leon Liang
97998a8f09 merge changes 2019-10-27 13:24:53 -04:00
Leon Liang
13a1401759 Reformat code 2019-10-27 02:53:12 -04:00
Leon Liang
0bbc453d54 Merge pull request #55 from ClaytonWWilson/delete_topic
Delete topic
2019-10-27 00:10:56 -04:00
Leon Liang
e236ceeb4b Merge branch 'master' into delete_topic 2019-10-27 00:10:38 -04:00
Leon Liang
1c81ae1663 show user's profile image 2019-10-27 00:09:17 -04:00
Leon Liang
c356dd18fa added UI allowing topic creation 2019-10-27 00:08:38 -04:00
Aditya Sankaran
19780a1395 made userline not hardcoded 2019-10-26 17:06:42 -04:00
Aditya Sankaran
981795b288 writing microblogs not hardcoded anymore 2019-10-26 16:57:25 -04:00
Leon Liang
ec041732d9 reformat 2019-10-25 23:14:25 -04:00
Leon Liang
eb3766edb2 Merge pull request #54 from ClaytonWWilson/delete_topic
added function to delete topic
2019-10-25 23:13:27 -04:00
Leon Liang
d9f6fb5d8e added function to delete topic 2019-10-25 23:04:09 -04:00
b31a571b29 Add followedTopics array on signup 2019-10-25 19:27:45 -04:00
18 changed files with 858 additions and 450 deletions

View File

@@ -1,78 +1,70 @@
/* eslint-disable prefer-arrow-callback */
/* eslint-disable promise/always-return */
const { admin, db } = require("../util/admin");
const admin = require('firebase-admin');
exports.putPost = (req, res) => {
const newPost = {
body: req.body.body,
userHandle: req.body.userHandle,
userHandle: req.user.handle,
userImage: req.body.userImage,
userID: req.userData.userID,
userID: req.user.uid,
microBlogTitle: req.body.microBlogTitle,
createdAt: new Date().toISOString(),
likeCount: 0,
commentCount: 0,
microBlogTopics: req.body.microBlogTopics
};
const resPost;
admin.firestore().collection('posts').add(newPost)
.then((doc) => {
resPost = newPost;
const resPost = newPost;
resPost.postId = doc.id;
return admin.firestore().doc(`posts/${doc.id}`).set(resPost)
})
.then(() => {
return res.status(200).json(resPost);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: 'something is wrong'});
return res.status(500).json({ error: 'something went wrong'});
});
};
exports.getallPostsforUser = (req, res) => {
db.collection('posts').where('userHandle', '==', 'new user' ).get()
.then((data) => {
var post_query = admin.firestore().collection("posts").where("userHandle", "==", req.user.handle);
post_query.get()
.then(function(myPosts) {
let posts = [];
data.forEach(function(doc) {
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
return res.status(200).json(posts);
})
.catch((err) => {
console.error(err);
return res.status(500).json({error: 'Failed to fetch all posts written by specific user.'})
.then(function() {
res.status(200).send("Successfully retrieved all user's posts from database.");
return;
})
.catch(function(err) {
res.status(500).send("Failed to retrieve user's posts from database.", err);
});
};
exports.getAllPosts = (req, res) => {
db.collection('posts')
.orderBy('createdAt', 'desc')
.get()
.then((data) => {
let posts = [];
data.forEach((doc) => {
posts.push({
body: doc.data().body,
userHandle: doc.data().userHandle,
createdAt: doc.data().createdAt,
commentCount: doc.data().commentCount,
likeCount: doc.data().likeCount,
userImage: doc.data().userImage,
microBlogTitle: doc.data().microBlogTitle,
microBlogTopics: doc.data().microBlogTopics,
postId: doc.id,
});
});
return res.status(200).json(posts);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code });
});
exports.getallPosts = (req, res) => {
var post_query = admin.firestore().collection("posts");
post_query.get()
.then(function(allPosts) {
let posts = [];
allPosts.forEach(function(doc) {
posts.push(doc.data());
});
return res.status(200).json(posts);
})
.then(function() {
res.status(200).send("Successfully retrieved every post from database.");
return;
})
.catch(function(err) {
res.status(500).send("Failed to retrieve posts from database.", err);
});
};
exports.getFilteredPosts = (req, res) => {
admin.firestore().collection('posts').where('userHandle', '==', 'new user').where('microBlogTopics', '==')
};

View File

@@ -1,36 +1,60 @@
/* eslint-disable prefer-arrow-callback */
/* eslint-disable promise/always-return */
const admin = require('firebase-admin');
const { admin, db } = require("../util/admin");
exports.putTopic = (req, res) => {
const newTopic = {
topic: req.body.topic
};
const newTopic = {
topic: req.body.topic
};
admin.firestore().collection('topics').add(newTopic)
.then((doc) => {
const resTopic = newTopic;
return res.status(200).json(resTopic);
admin
.firestore()
.collection("topics")
.add(newTopic)
.then(doc => {
const resTopic = newTopic;
return res.status(200).json(resTopic);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: 'something is wrong'});
.catch(err => {
console.error(err);
return res.status(500).json({ error: "something is wrong" });
});
};
exports.getAllTopics = (req, res) => {
admin.firestore().collection('topics').get()
.then((data) => {
let topics = [];
data.forEach(function(doc) {
topics.push(doc.data());
admin
.firestore()
.collection("topics")
.get()
.then(data => {
let topics = [];
data.forEach(function(doc) {
topics.push({
topic: doc.data().topic,
id: doc.id
});
return res.status(200).json(topics);
});
return res.status(200).json(topics);
})
.catch((err) => {
console.error(err);
return res.status(500).json({error: 'Failed to fetch all posts written by specific user.'})
.catch(err => {
console.error(err);
return res.status(500).json({ error: "Failed to fetch all topics." });
});
};
exports.deleteTopic = (req, res) => {
const topic = db.doc(`/topics/${req.params.topicId}`);
topic
.get()
.then(doc => {
if (!doc.exists) {
return res.status(404).json({ error: "Topic not found" });
} else {
return topic.delete();
}
})
};
.then(() => {
return res.json({ message: "Topic successfully deleted!" });
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: "Failed to delete topic." });
});
};

View File

@@ -1,6 +1,4 @@
/* eslint-disable prefer-arrow-callback */
/* eslint-disable promise/catch-or-return */
const { admin, db } = require("../util/admin");
const config = require("../util/config");
const { validateUpdateProfileInfo } = require("../util/validator");
@@ -8,8 +6,6 @@ const { validateUpdateProfileInfo } = require("../util/validator");
const firebase = require("firebase");
firebase.initializeApp(config);
var handle2Email = new Map();
exports.signup = (req, res) => {
const newUser = {
email: req.body.email,
@@ -58,7 +54,7 @@ exports.signup = (req, res) => {
db.doc(`/users/${newUser.handle}`)
.get()
.then((doc) => {
.then(doc => {
if (doc.exists) {
return res
.status(400)
@@ -68,25 +64,27 @@ exports.signup = (req, res) => {
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password);
})
.then((data) => {
.then(data => {
userId = data.user.uid;
return data.user.getIdToken();
})
.then((idToken) => {
.then(idToken => {
token = idToken;
const defaultImageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/no-img.png?alt=media`;
const userCred = {
email: newUser.email,
handle: newUser.handle,
createdAt: newUser.createdAt,
userId
userId,
followedTopics: [],
imageUrl: defaultImageUrl
};
handle2Email.set(userCred.handle, userCred.email);
return db.doc(`/users/${newUser.handle}`).set(userCred);
})
.then(() => {
return res.status(201).json({ token });
})
.catch((err) => {
.catch(err => {
console.error(err);
if (err.code === "auth/email-already-in-use") {
return res.status(500).json({ email: "This email is already taken." });
@@ -98,7 +96,6 @@ exports.signup = (req, res) => {
exports.login = (req, res) => {
const user = {
email: req.body.email,
handle: req.body.handle,
password: req.body.password
};
@@ -107,80 +104,172 @@ exports.login = (req, res) => {
const emailRegEx = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
// Email check
// Checks if email/username field is empty
if (user.email.trim() === "") {
errors.email = "Email must not be blank.";
}
else if (!user.email.match(emailRegEx)) {
user.email = handle2Email.get(user.email);
}
// Password check
// Checks if password field is empty
if (user.password.trim() === "") {
errors.password = "Password must not be blank.";
}
// Checking if any errors have been raised
// Checks if any of the above two errors were found
if (Object.keys(errors).length > 0) {
return res.status(400).json(errors);
}
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then((data) => {
return data.user.getIdToken();
})
.then((token) => {
return res.status(200).json({ token });
})
.catch((err) => {
console.error(err);
if (err.code === "auth/wrong-password" || err.code === "auth/invalid-email" || err.code === "auth/user-not-found") {
return res
.status(403)
.json({ general: "Invalid credentials. Please try again." });
}
return res.status(500).json({ error: err.code });
});
// Email/username field is username since it's not in email format
if (!user.email.match(emailRegEx)) {
var userDoc = db.collection("users").doc(`${user.email}`);
userDoc
.get()
.then(function(doc) {
if (doc.exists) {
user.email = doc.data().email;
} else {
return res
.status(403)
.json({ general: "Invalid credentials. Please try again." });
}
return;
})
.then(function() {
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then(data => {
return data.user.getIdToken();
})
.then(token => {
return res.status(200).json({ token });
})
.catch(err => {
console.error(err);
if (
err.code === "auth/user-not-found" ||
err.code === "auth/invalid-email" ||
err.code === "auth/wrong-password"
) {
return res
.status(403)
.json({ general: "Invalid credentials. Please try again." });
}
return res.status(500).json({ error: err.code });
});
return;
})
.catch(function(err) {
if (!doc.exists) {
return res
.status(403)
.json({ general: "Invalid credentials. Please try again." });
}
return res.status(500).send(err);
});
}
// Email/username field is username
else {
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then(data => {
return data.user.getIdToken();
})
.then(token => {
return res.status(200).json({ token });
})
.catch(err => {
console.error(err);
if (
err.code === "auth/user-not-found" ||
err.code === "auth/invalid-email" ||
err.code === "auth/wrong-password"
) {
return res
.status(403)
.json({ general: "Invalid credentials. Please try again." });
}
return res.status(500).json({ error: err.code });
});
}
};
//Deletes user account
//Deletes user account and all associated data
exports.deleteUser = (req, res) => {
var currentUser;
// Get the profile image filename
// `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`
let imageFileName;
req.userData.imageUrl ?
imageFileName = req.userData.imageUrl.split('/o/')[1].split('?alt=')[0] :
imageFileName = 'no-img.png'
const userId = req.userData.userId;
let errors = {};
firebase.auth().onAuthStateChanged(function(user) {
currentUser = user;
if (currentUser) {
/*db.collection("users").doc(`${currentUser.handle}`).delete()
.then(function() {
res.status(200).send("Removed user from database.");
return;
})
.catch(function(err) {
res.status(500).send("Failed to remove user from database.", err);
});*/
function thenFunction(data) {
console.log(`${data} data for ${req.userData.handle} has been deleted.`);
}
//let ref = db.collection('users');
//let userDoc = ref.where('userId', '==', currentUser.uid).get();
//userDoc.ref.delete();
function catchFunction(data, err) {
console.error(err);
errors[data] = err;
}
currentUser.delete()
.then(function() {
console.log("User successfully deleted.");
res.status(200).send("Deleted user.");
return;
})
.catch(function(err) {
console.log("Error deleting user.", err);
res.status(500).send("Failed to delete user.");
// Deletes user from authentication
let auth = admin.auth().deleteUser(userId);
// Deletes database data
let data = db.collection("users").doc(`${req.user.handle}`).delete();
// Deletes any custom profile image
let image;
if (imageFileName !== 'no-img.png') {
image = admin.storage().bucket().file(imageFileName).delete()
} else {
image = Promise.resolve();
}
// Deletes all users posts
let posts = db.collection("posts")
.where("userHandle", "==", req.user.handle)
.get()
.then((query) => {
query.forEach((snap) => {
snap.ref.delete();
});
}
else {
console.log("Cannot get user.");
res.status(500).send("Cannot get user.");
return;
})
let promises = [
auth
.then(thenFunction('auth'))
.catch((err) => catchFunction('auth', err)),
data
.then(thenFunction('data'))
.catch((err) => catchFunction('data', err)),
image
.then(thenFunction('image'))
.catch((err) => catchFunction('image', err)),
posts
.then(thenFunction('posts'))
.catch((err) => catchFunction('image', err))
];
// Wait for all promises to resolve
let waitPromise = Promise.all(promises);
waitPromise.then(() => {
if (Object.keys(errors) > 0) {
return res.status(500).json(errors);
} else {
return res.status(200).json({message: `All data for ${req.userData.handle} has been deleted.`});
}
});
})
.catch((err) => {
return res.status(500).json({error: err});
})
};
// Returns all data in the database for the user who is currently signed in
@@ -188,10 +277,10 @@ exports.getProfileInfo = (req, res) => {
db.collection("users")
.doc(req.user.handle)
.get()
.then((data) => {
.then(data => {
return res.status(200).json(data.data());
})
.catch((err) => {
.catch(err => {
console.error(err);
return res.status(500).json(err);
});
@@ -199,8 +288,6 @@ exports.getProfileInfo = (req, res) => {
// Updates the data in the database of the user who is currently logged in
exports.updateProfileInfo = (req, res) => {
// TODO: Add functionality for adding/updating profile images
// Data validation
const { valid, errors, profileData } = validateUpdateProfileInfo(req);
if (!valid) return res.status(400).json(errors);
@@ -211,13 +298,11 @@ exports.updateProfileInfo = (req, res) => {
.set(profileData, { merge: true })
.then(() => {
console.log(`${req.user.handle}'s profile info has been updated.`);
return res
.status(201)
.json({
general: `${req.user.handle}'s profile info has been updated.`
});
return res.status(201).json({
general: `${req.user.handle}'s profile info has been updated.`
});
})
.catch((err) => {
.catch(err => {
console.error(err);
return res.status(500).json({
error: "Error updating profile data"
@@ -229,14 +314,15 @@ exports.getUserDetails = (req, res) => {
let userData = {};
db.doc(`/users/${req.body.handle}`)
.get()
.then((doc) => {
.then(doc => {
if (doc.exists) {
userData = doc.data();
return res.status(200).json({userData});
} else {
return res.status(400).json({error: "User not found."})
}})
.catch((err) => {
return res.status(200).json({ userData });
} else {
return res.status(400).json({ error: "User not found." });
}
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: err.code });
});
@@ -246,17 +332,34 @@ exports.getAuthenticatedUser = (req, res) => {
let credentials = {};
db.doc(`/users/${req.user.handle}`)
.get()
.then((doc) => {
.then(doc => {
if (doc.exists) {
credentials = doc.data();
return res.status(200).json({credentials});
} else {
return res.status(400).json({error: "User not found."})
}})
.catch((err) => {
return res.status(200).json({ credentials });
} else {
return res.status(400).json({ error: "User not found." });
}
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: err.code });
});
};
exports.getUserHandles = (req, res) => {
admin
.firestore()
.collection("users")
.get()
.then(data => {
let users = [];
data.forEach(function(doc) {
users.push(doc.data().handle);
});
return res.status(200).json(users);
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: "Failed to get all user handles." });
});
};

View File

@@ -16,7 +16,8 @@ const {
login,
signup,
deleteUser,
updateProfileInfo
updateProfileInfo,
getUserHandles
} = require("./handlers/users");
// Adds a user to the database and registers them in firebase with
@@ -29,7 +30,7 @@ app.post("/signup", signup);
app.post("/login", login);
//Deletes user account
app.delete("/delete", deleteUser);
app.delete("/delete", fbAuth, deleteUser);
app.get("/getUser", fbAuth, getUserDetails);
@@ -41,25 +42,25 @@ app.post("/updateProfileInfo", fbAuth, updateProfileInfo);
app.get("/user", fbAuth, getAuthenticatedUser);
// get user handles with search phase
app.get("/getUserHandles", fbAuth, getUserHandles);
/*------------------------------------------------------------------*
* handlers/post.js *
*------------------------------------------------------------------*/
const { getallPostsforUser, putPost, getAllPosts
} = require("./handlers/post");
const { getallPostsforUser, getallPosts, putPost } = require("./handlers/post");
app.get("/getallPostsforUser", getallPostsforUser);
app.get("/getallPostsforUser", fbAuth, getallPostsforUser);
app.get("/getallPosts", getallPosts);
// Adds one post to the database
app.post("/putPost", fbAuth, putPost);
// Displays posts on home page
app.get("/getAllPosts", getAllPosts );
/*------------------------------------------------------------------*
* handlers/topic.js *
*------------------------------------------------------------------*/
const { putTopic, getAllTopics
} = require("./handlers/topic");
const { putTopic, getAllTopics, deleteTopic } = require("./handlers/topic");
// add topic to database
app.post("/putTopic", fbAuth, putTopic);
@@ -67,4 +68,7 @@ app.post("/putTopic", fbAuth, putTopic);
// get all topics from database
app.get("/getAllTopics", fbAuth, getAllTopics);
// delete a specific topic
app.delete("/deleteTopic/:topicId", fbAuth, deleteTopic);
exports.api = functions.https.onRequest(app);

View File

@@ -535,6 +535,11 @@
"integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==",
"dev": true
},
"ansi-regex": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz",
"integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg=="
},
"ansi-styles": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
@@ -1190,11 +1195,18 @@
"progress": "^2.0.0",
"regexpp": "^2.0.1",
"semver": "^5.5.1",
"strip-ansi": "^4.0.0",
"strip-json-comments": "^2.0.1",
"table": "^5.2.3",
"text-table": "^0.2.0"
},
"dependencies": {
"ansi-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
"integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
"dev": true
},
"debug": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
@@ -1209,6 +1221,15 @@
"resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz",
"integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==",
"dev": true
},
"strip-ansi": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
"integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
"dev": true,
"requires": {
"ansi-regex": "^3.0.0"
}
}
}
},
@@ -2355,6 +2376,7 @@
"mute-stream": "0.0.7",
"run-async": "^2.2.0",
"rxjs": "^6.4.0",
"string-width": "^2.1.0",
"strip-ansi": "^5.1.0",
"through": "^2.3.6"
},
@@ -2403,6 +2425,12 @@
"integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=",
"optional": true
},
"is-fullwidth-code-point": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz",
"integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=",
"dev": true
},
"is-obj": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz",
@@ -3252,7 +3280,8 @@
"dev": true,
"requires": {
"ansi-styles": "^3.2.0",
"astral-regex": "^1.0.0"
"astral-regex": "^1.0.0",
"is-fullwidth-code-point": "^2.0.0"
}
},
"snakeize": {
@@ -3292,12 +3321,47 @@
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-0.1.2.tgz",
"integrity": "sha1-gIudDlb8Jz2Am6VzOOkpkZoanxo="
},
"string-width": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz",
"integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==",
"dev": true,
"requires": {
"is-fullwidth-code-point": "^2.0.0",
"strip-ansi": "^4.0.0"
},
"dependencies": {
"ansi-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
"integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
"dev": true
},
"strip-ansi": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
"integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
"dev": true,
"requires": {
"ansi-regex": "^3.0.0"
}
}
}
},
"string_decoder": {
"version": "0.10.31",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz",
"integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=",
"optional": true
},
"strip-ansi": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz",
"integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==",
"requires": {
"ansi-regex": "^4.1.0"
}
},
"strip-json-comments": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
@@ -3344,6 +3408,7 @@
"dev": true,
"requires": {
"emoji-regex": "^7.0.1",
"is-fullwidth-code-point": "^2.0.0",
"strip-ansi": "^5.1.0"
}
},

View File

@@ -16,7 +16,8 @@
"axios": "^0.19.0",
"firebase": "^6.6.2",
"firebase-admin": "^8.6.0",
"firebase-functions": "^3.1.0"
"firebase-functions": "^3.1.0",
"strip-ansi": "^5.2.0"
},
"devDependencies": {
"eslint": "^5.12.0",

View File

@@ -52,6 +52,3 @@ body {
color: #1da1f2;
}
.a{
text-decoration: none;
}

View File

@@ -10,11 +10,11 @@ import jwtDecode from "jwt-decode";
// Redux
import { Provider } from "react-redux";
import store from "./redux/store";
import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider';
import createMuiTheme from '@material-ui/core/styles/createMuiTheme';
import themeObject from './util/theme';
import { SET_AUTHENTICATED } from './redux/types';
import { logoutUser, getUserData } from './redux/actions/userActions';
import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider";
import createMuiTheme from "@material-ui/core/styles/createMuiTheme";
import themeObject from "./util/theme";
import { SET_AUTHENTICATED } from "./redux/types";
import { logoutUser, getUserData } from "./redux/actions/userActions";
// Components
import AuthRoute from "./util/AuthRoute";
@@ -22,15 +22,16 @@ import AuthRoute from "./util/AuthRoute";
// axios.defaults.baseURL = 'http://localhost:5006/twistter-e4649/us-central1/api';
// Pages
import home from './pages/Home';
import signup from './pages/Signup';
import login from './pages/Login';
import user from './pages/user';
import logout from './pages/Logout';
import Delete from './pages/Delete';
import writeMicroblog from './Writing_Microblogs.js';
import editProfile from './pages/editProfile';
import userLine from './Userline.js';
import home from "./pages/Home";
import signup from "./pages/Signup";
import login from "./pages/Login";
import user from "./pages/user";
import logout from "./pages/Logout";
import Delete from "./pages/Delete";
import writeMicroblog from "./Writing_Microblogs.js";
import editProfile from "./pages/editProfile";
import userLine from "./Userline.js";
import Search from "./pages/Search.js";
const theme = createMuiTheme(themeObject);
@@ -43,7 +44,7 @@ if (token) {
window.location.href = "/login";
} else {
store.dispatch({ type: SET_AUTHENTICATED });
axios.defaults.headers.common['Authorization'] = token;
axios.defaults.headers.common["Authorization"] = token;
store.dispatch(getUserData());
}
} catch (invalidTokenError) {
@@ -52,34 +53,35 @@ if (token) {
}
}
class App extends Component {
render() {
return (
<MuiThemeProvider theme={theme}>
<Provider store={store}>
<Router>
<div className='container' >
<div className="container">
<Navbar />
</div>
<div className="app">
<Switch>
{/* 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="/login" component={login} />
<Route exact path="/logout" component={logout} />
<Route exact path="/delete" component={Delete} />
<Route exact path="/user" component={user} />
<Route exact path="/home" component={writeMicroblog} />
<Route exact path="/edit" component={editProfile} />
{/* <Route exact path="/user" component={userLine} /> */}
{/* 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="/login" component={login} />
<AuthRoute exact path="/" component={home}/>
<Route exact path="/logout" component={logout} />
<Route exact path="/delete" component={Delete} />
<Route exact path="/home" component={home} />
<Route exact path="/user" component={user} />
<Route exact path="/edit" component={editProfile} />
<Route exact path="/search" component={Search} />
<AuthRoute exact path="/" component={home} />
<AuthRoute exact path="/" component={home}/>
</Switch>
</div>
</Router>
</Provider>
</MuiThemeProvider>

View File

@@ -1,108 +1,128 @@
import React, { Component } from "react";
import { BrowserRouter as Router } from 'react-router-dom';
import Route from 'react-router-dom/Route';
import axios from 'axios';
import { BrowserRouter as Router } from "react-router-dom";
import Route from "react-router-dom/Route";
import axios from "axios";
class Writing_Microblogs extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
title: '',
topics: '',
characterCount: 250
};
constructor(props) {
super(props);
this.state = {
value: "",
title: "",
topics: "",
characterCount: 250
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeforPost = this.handleChangeforPost.bind(this);
this.handleChangeforTopics = this.handleChangeforTopics.bind(this);
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeforPost = this.handleChangeforPost.bind(this);
this.handleChangeforTopics = this.handleChangeforTopics.bind(this);
}
handleChange(event) {
this.setState( {title: event.target.value });
}
handleChange(event) {
this.setState({ title: event.target.value });
}
handleChangeforTopics(event) {
this.setState( {topics: event.target.value});
}
handleChangeforTopics(event) {
this.setState({ topics: event.target.value });
}
handleSubmit(event) {
// alert('A title for the microblog was inputted: ' + this.state.title + '\nA microblog was posted: ' + this.state.value);
const postData = {
body: this.state.value,
userHandle: "new user",
userImage: "bing-url",
microBlogTitle: this.state.title,
microBlogTopics: this.state.topics.split(', ')
}
const headers = {
headers: { 'Content-Type': 'application/json'}
}
axios
.post('/putPost', postData, headers)
.then((res) =>{
alert('Post was shared successfully!')
console.log(res.data);
})
.catch((err) => {
alert('An error occured.');
console.error(err);
})
event.preventDefault();
this.setState({value: '', title: '',characterCount: 250, topics: ''})
}
handleSubmit(event) {
// alert('A title for the microblog was inputted: ' + this.state.title + '\nA microblog was posted: ' + this.state.value);
const postData = {
body: this.state.value,
userImage: "bing-url",
microBlogTitle: this.state.title,
microBlogTopics: this.state.topics.split(", ")
};
const headers = {
headers: { "Content-Type": "application/json" }
};
handleChangeforPost(event) {
this.setState({value: event.target.value })
}
axios
.post("/putPost", postData, headers)
.then(res => {
alert("Post was shared successfully!");
console.log(res.data);
})
.catch(err => {
alert("An error occured.");
console.error(err);
});
event.preventDefault();
this.setState({ value: "", title: "", characterCount: 250, topics: "" });
}
handleChangeforCharacterCount(event) {
const charCount = event.target.value.length
const charRemaining = 250 - charCount
this.setState({characterCount: charRemaining })
}
handleChangeforPost(event) {
this.setState({ value: event.target.value });
}
render() {
return (
<div>
<div style={{ width: "200px", height: "50px", marginTop: "180px", marginLeft: "50px" }}>
<form>
<textarea placeholder="Enter Microblog Title" value={this.state.title} required onChange={this.handleChange} cols={30} rows={1} />
handleChangeforCharacterCount(event) {
const charCount = event.target.value.length;
const charRemaining = 250 - charCount;
this.setState({ characterCount: charRemaining });
}
</form>
render() {
return (
<div>
<div
style={{
width: "200px",
height: "50px",
marginTop: "180px",
marginLeft: "50px"
}}
>
<form>
<textarea
placeholder="Enter Microblog Title"
value={this.state.title}
required
onChange={this.handleChange}
cols={30}
rows={1}
/>
</form>
</div>
<div style={{ width: "200px", height: "50px", marginLeft: "50px" }}>
<form>
<textarea
placeholder="Enter topics seperated by a comma"
value={this.state.topics}
required
onChange={this.handleChangeforTopics}
cols={40}
rows={1}
/>
</form>
</div>
<div style={{ width: "200px", marginLeft: "50px" }}>
<form onSubmit={this.handleSubmit}>
<textarea
value={this.state.value}
required
maxLength="250"
placeholder="Write Microblog here..."
onChange={e => {
this.handleChangeforPost(e);
this.handleChangeforCharacterCount(e);
}}
cols={40}
rows={20}
/>
<div style={{ fontSize: "14px", marginRight: "-100px" }}>
<p2>Characters Left: {this.state.characterCount}</p2>
</div>
<div style={{ width: "200px", height: "50px", marginLeft: "50px"}} >
<form>
<textarea placeholder="Enter topics seperated by a comma" value={this.state.topics} required onChange={this.handleChangeforTopics} cols={40} rows={1} />
</form>
</div>
<div style={{ width: "200px", marginLeft: "50px"}}>
<form onSubmit={this.handleSubmit}>
<textarea value={this.state.value} required maxLength="250" placeholder= "Write Microblog here..."
onChange = { (e) => { this.handleChangeforPost(e); this.handleChangeforCharacterCount(e) } } cols={40} rows={20} />
<div style={{ fontSize: "14px", marginRight: "-100px"}} >
<p2>Characters Left: {this.state.characterCount}</p2>
</div>
<div style={{ marginRight: "-100px" }}>
<button onClick>Share Post</button>
</div>
</form>
</div>
</div>
);
}
<div style={{ marginRight: "-100px" }}>
<button onClick>Share Post</button>
</div>
</form>
</div>
</div>
);
}
}
export default Writing_Microblogs;
export default Writing_Microblogs;

View File

@@ -10,7 +10,7 @@ import Button from '@material-ui/core/Button';
import withStyles from "@material-ui/core/styles/withStyles";
// Redux stuff
// import { logoutUser } from '../../redux/actions/userActions';
import { logoutUser } from '../../redux/actions/userActions';
import { connect } from 'react-redux';
const styles = {
@@ -31,13 +31,9 @@ const styles = {
position: "absolute"
}
};
export class Navbar extends Component {
render() {
export class Navbar extends Component {
render() {
const authenticated = this.props.user.authenticated;
return (
<AppBar>
@@ -45,6 +41,9 @@ const styles = {
<Button component={ Link } to='/'>
Home
</Button>
{authenticated && <Button component={ Link } to='/user'>
Profile
</Button>}
{!authenticated && <Button component={ Link } to='/login'>
Login
</Button>}
@@ -54,11 +53,6 @@ const styles = {
{authenticated && <Button component={ Link } to='/logout'>
Logout
</Button>}
{/* Commented out the delete button, because it should probably go on
the profile or editProfile page instead of the NavBar */}
{/* <Button component={ Link } to='/delete'>
Delete Account
</Button> */}
</ToolBar>
</AppBar>
)
@@ -69,13 +63,9 @@ const mapStateToProps = (state) => ({
user: state.user
})
// const mapActionsToProps = { logoutUser };
Navbar.propTypes = {
user: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired
}
export default connect(mapStateToProps)(withStyles(styles)(Navbar));
// export default Navbar;

View File

@@ -1,55 +0,0 @@
import React, { Component } from 'react'
import withStyles from '@material-ui/core/styles/withStyles';
import Link from 'react-router-dom/Link';
// MUI Stuff
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import { Typography } from '@material-ui/core';
const styles = {
card:{
display: 'flex',
marginBottom: 20,
},
image:{
minWidth: 200,
},
content: {
padding: 25,
objectFit: 'cover',
}
}
class Posts extends Component {
render() {
const { classes, post : {body, createdAt, userImage, userHandle, commmentCount, likeCount, microBlogTopics} } = this.props
return (
<Card className={classes.card}>
<CardMedia
image={userImage}
title="Profile Image"
className={classes.image}/>
<CardContent class={classes.content}>
<Typography
variant = "h5"
component={Link}
to={`/users/${userHandle}`}
color="primary"
>
{userHandle}
</Typography>
<Typography
variant = "body2"
color="textSecondary">
{createdAt}
</Typography>
<Typography variant="body1">{body}</Typography>
</CardContent>
</Card>
)
}
}
export default withStyles(styles)(Posts);

View File

@@ -7,7 +7,8 @@ import Button from "@material-ui/core/Button";
import withStyles from "@material-ui/core/styles/withStyles";
// Redux stuff
import { logoutUser } from "../redux/actions/userActions";
//import { logoutUser } from "../redux/actions/userActions";
import { deleteUser } from "../redux/actions/userActions";
import { connect } from "react-redux";
const styles = {
@@ -32,7 +33,8 @@ const styles = {
export class Delete extends Component {
componentDidMount() {
this.props.logoutUser();
//this.props.logoutUser();
this.props.deleteUser();
this.props.history.push('/');
}
@@ -45,10 +47,12 @@ const mapStateToProps = (state) => ({
user: state.user
});
const mapActionsToProps = { logoutUser };
//const mapActionsToProps = { logoutUser };
const mapActionsToProps = { deleteUser };
Delete.propTypes = {
logoutUser: PropTypes.func.isRequired,
//logoutUser: PropTypes.func.isRequired,
deleteUser: PropTypes.func.isRequired,
user: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired
};

View File

@@ -1,12 +1,74 @@
/* eslint-disable */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import axios from 'axios';
// Material UI and React Router
import Grid from '@material-ui/core/Grid';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from "@material-ui/core/Typography";
// component
import '../App.css';
import logo from '../images/twistter-logo.png';
import noImage from '../images/no-img.png';
import Writing_Microblogs from '../Writing_Microblogs';
class Home extends Component {
state = {};
componentDidMount() {
axios
.get("/getallPosts")
.then(res => {
console.log(res.data);
this.setState({
posts: res.data
})
})
.catch(err => console.log(err));
}
render() {
let authenticated = this.props.user.authenticated;
let postMarkup = this.state.posts ? (
this.state.posts.map(post =>
<Card>
<CardContent>
<Typography>
{
this.state.imageUrl ? (<img src={this.state.imageUrl} height="250" width="250" />) :
(<img src={noImage} height="50" width="50"/>)
}
</Typography>
<Typography variant="h7"><b>{post.userHandle}</b></Typography>
<Typography variant="body2" color={"textSecondary"}>{post.createdAt}</Typography>
<br />
<Typography variant="body1"><b>{post.microBlogTitle}</b></Typography>
<Typography variant="body2">{post.body}</Typography>
<br />
<Typography variant="body2"><b>Topics:</b> {post.microBlogTopics}</Typography>
<br />
<Typography variant="body2" color={"textSecondary"}>Likes {post.likeCount} Comments {post.commentCount}</Typography>
</CardContent>
</Card>
)
) : (<p>My Posts</p>);
return (
authenticated ?
<Grid container spacing={16}>
<Grid item sm={4} xs={8}>
<Writing_Microblogs />
</Grid>
<Grid item sm={4} xs={8}>
{postMarkup}
</Grid>
</Grid>
:
<div>
<div>
<img src={logo} className="app-logo" alt="logo" />
@@ -31,7 +93,15 @@ class Home extends Component {
</div>
</div>
);
}
}
}
export default Home;
const mapStateToProps = (state) => ({
user: state.user
})
Home.propTypes = {
user: PropTypes.object.isRequired
}
export default connect(mapStateToProps)(Home);

View File

@@ -16,13 +16,15 @@ import withStyles from "@material-ui/core/styles/withStyles";
// Redux stuff
import { connect } from 'react-redux';
import { loginUser } from '../redux/actions/userActions';
import { fontFamily } from '@material-ui/system';
//Theme
const styles = {
form: {
textAlign: "center"
},
textField: {
marginBottom: 30
marginBottom: 20
},
pageTitle: {
// marginTop: 20,
@@ -34,6 +36,12 @@ const styles = {
},
progress: {
position: "absolute"
},
p: {
fontFamily: "cursive",
},
div: {
backgroundColor: "lightgrey",
}
};
@@ -104,9 +112,14 @@ export class Login extends Component {
<Grid item sm />
<Grid item sm>
<img src={logo} className="app-logo" alt="logo" />
<Typography variant="h2" className={classes.pageTitle}>
Log in to Twistter
<br></br>
<br></br>
<Typography variant="p" className={classes.pageTitle} fontFamily = "Georgia, serif">
<b><font face="Segoe UI">Log in to Twistter</font></b>
<br></br>
</Typography>
<br></br>
<div>
<form noValidate onSubmit={this.handleSubmit}>
<TextField
id="email"
@@ -149,6 +162,7 @@ export class Login extends Component {
<Typography color="error">Invalid username/email or password</Typography>
)}
</form>
</div>
</Grid>
<Grid item sm />
</Grid>

View File

@@ -0,0 +1,74 @@
import React, { Component } from "react";
// import props
import { TextField, Paper } from "@material-ui/core";
import Grid from "@material-ui/core/Grid";
import Axios from "axios";
import user from "./user.js";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useRouteMatch
} from "react-router-dom";
export class Search extends Component {
state = {
searchPhase: null,
searchResult: null
};
handleSearch(event) {
Axios.get("/getUserHandles").then(res => {
this.setState({
searchResult: res.data
});
});
console.log(this.state.searchPhase);
}
handleInput(event) {
this.setState({
searchPhase: event.target.value
});
this.handleSearch();
}
handleRedirect() {
location.reload();
}
render() {
let resultMarkup = this.state.searchResult ? (
this.state.searchResult.map(result => (
<Router>
<div>
<Link to={`/user`}>{result}</Link>
</div>
</Router>
))
) : (
// console.log(this.state.searchResult)
<p> searching... </p>
);
return (
<Grid>
<Grid>
<TextField
id="standard-required"
label="Search"
defaultValue="username"
margin="normal"
value={this.state.searchPhase}
onChange={event => this.handleInput(event)}
/>
</Grid>
<Grid>{resultMarkup}</Grid>
</Grid>
);
}
}
export default Search;

View File

@@ -16,13 +16,17 @@ import withStyles from "@material-ui/core/styles/withStyles";
// Redux stuff
import { connect } from 'react-redux';
import { signupUser } from '../redux/actions/userActions';
import { border } from '@material-ui/system';
const styles = {
form: {
textAlign: "center"
},
textField: {
marginBottom: 30
marginBottom: 20,
//border: "1px solid #234",
display: "inline-block",
boxSizing: "border-box",
},
pageTitle: {
marginBottom: 40
@@ -33,6 +37,14 @@ const styles = {
},
progress: {
position: "absolute"
},
div: {
borderRadius: "5px",
backgroundColor: "grey",
padding: "20px",
},
p: {
fontFamily: "Segoe UI",
}
};
@@ -92,9 +104,13 @@ export class Signup extends Component {
<Grid item sm />
<Grid item sm>
<img src={logo} className="app-logo" alt="logo" />
<Typography variant="h2" className={classes.pageTitle}>
Create a new account
<br></br>
<br></br>
<Typography variant="p" className={classes.pageTitle}>
<b><font face="Segoe UI">Create a new account</font></b>
<br></br>
</Typography>
<br></br>
<form noValidate onSubmit={this.handleSubmit}>
<TextField
id="handle"
@@ -146,6 +162,8 @@ export class Signup extends Component {
onChange={this.handleChange}
fullWidth
/>
<br></br>
<br></br>
<Button
type="submit"
variant="contained"

View File

@@ -6,6 +6,7 @@ import PropTypes from "prop-types";
// Material-UI stuff
import Button from "@material-ui/core/Button";
import { Link } from 'react-router-dom';
import CircularProgress from "@material-ui/core/CircularProgress";
import Grid from "@material-ui/core/Grid";
import TextField from "@material-ui/core/TextField";
@@ -220,12 +221,34 @@ export class edit extends Component {
color="primary"
className={classes.button}
disabled={loading}
//component={ Link }
//to='/user'
>
Submit
{loading && (
<CircularProgress size={30} className={classes.progress} />
)}
</Button>
<br />
<Button
//variant="contained"
color="primary"
className={classes.button}
component={ Link }
to='/user'
>
Back to Profile
</Button>
<br />
<Button
variant="contained"
color="secondary"
className={classes.button}
component={ Link }
to='/delete'
>
Delete Account
</Button>
</form>
</Grid>
<Grid item sm />

View File

@@ -1,129 +1,191 @@
/* eslint-disable */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import axios from 'axios';
//import '../App.css';
import { makeStyles, styled } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Card from '@material-ui/core/Card';
//import '../App.css';
// Material UI and React Router
import { makeStyles, styled } from "@material-ui/core/styles";
import { Link } from 'react-router-dom';
import Card from "@material-ui/core/Card";
import CardMedia from '@material-ui/core/CardMedia';
import CardContent from '@material-ui/core/CardContent';
import Chip from '@material-ui/core/Chip';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
import Grid from "@material-ui/core/Grid";
import Chip from "@material-ui/core/Chip";
import Typography from "@material-ui/core/Typography";
import AddCircle from '@material-ui/icons/AddCircle';
import AddCircle from "@material-ui/icons/AddCircle";
import TextField from "@material-ui/core/TextField";
// component
import Profile from '../components/profile/Profile';
import Userline from '../Userline';
import '../App.css';
import noImage from '../images/no-img.png';
import Posts from '../components/post/Posts';
const PostCard = styled(Card)({
background: 'linear-gradient(45deg, #1da1f2 90%)',
border: 3,
borderRadius: 3,
height:325,
width: 345,
padding: '0 30px',
});
import Writing_Microblogs from '../Writing_Microblogs';
const MyChip = styled(Chip)({
margin: 2,
color: 'primary'
color: "primary"
});
const styles = (theme) => ({
...theme
});
const handleDelete = () => {
alert("Delete this topic!");
}
const handleAddCircle = () => {
alert("Add topic");
}
class user extends Component {
class user extends Component {
state = {
profile: null,
topics: null
imageUrl: null,
topics: null,
newTopic: null
};
handleDelete = topic => {
axios
.delete(`/deleteTopic/${topic.id}`)
.then(function() {
location.reload();
})
.catch(function(err) {
console.log(err);
});
};
handleAddCircle = () => {
axios
.post("/putTopic", {
topic: this.state.newTopic
})
.then(function() {
location.reload();
})
.catch(function(err) {
console.log(err);
});
};
handleChange(event) {
this.setState({
newTopic: event.target.value
});
}
componentDidMount() {
axios
.get("/user")
.then(res => {
console.log(res.data.credentials.handle);
this.setState({
profile: res.data.credentials.handle
profile: res.data.credentials.handle,
imageUrl: res.data.credentials.imageUrl
});
})
.catch(err => console.log(err));
axios
.get("/getAllTopics")
.then(res => {
console.log(res.data[1]);
this.setState({
topics: res.data
})
});
})
.catch(err => console.log(err));
axios.get('/getAllPosts')
axios
.get("/getallPostsforUser")
.then(res => {
console.log(res.data);
this.setState({
posts: res.data
})
})
.catch(err => console.log(err));
}
render() {
const classes = this.props;
let authenticated = this.props.user.authenticated;
let classes = this.props;
let profileMarkup = this.state.profile ? (
<p>
<Typography variant='h5'>{this.state.profile}</Typography>
</p>) : (<p>loading username...</p>);
let topicsMarkup = this.state.topics ? (
this.state.topics.map(topic => <MyChip
label={{topic}.topic.topic}
onDelete={handleDelete}/>)
) : (<p> loading topics...</p>);
let posts = classes.data
let recentPostsMarkup = posts ? (
this.state.posts.map(post => <Posts key={post.postId} post={post}/>)
) : ( <p> Loading... </p> );
this.state.topics.map(
topic => (
<MyChip
label={{ topic }.topic.topic}
key={{ topic }.topic.id}
onDelete={key => this.handleDelete(topic)}
/>
) // console.log({ topic }.topic.id)
)
) : (
<p> loading topics...</p>
);
let imageMarkup = this.state.imageUrl ? (<img src={this.state.imageUrl} height="150" width="150" />) :
(<img src={noImage} height="150" width="150"/>);
let postMarkup = this.state.posts ? (
this.state.posts.map(post =>
<Card>
<CardContent>
<Typography>
{
this.state.imageUrl ? (<img src={this.state.imageUrl} height="250" width="250" />) :
(<img src={noImage} height="50" width="50"/>)
}
</Typography>
<Typography variant="h7"><b>{post.userHandle}</b></Typography>
<Typography variant="body2" color={"textSecondary"}>{post.createdAt}</Typography>
<br />
<Typography variant="body1"><b>{post.microBlogTitle}</b></Typography>
<Typography variant="body2">{post.body}</Typography>
<br />
<Typography variant="body2"><b>Topics:</b> {post.microBlogTopics}</Typography>
<br />
<Typography variant="body2" color={"textSecondary"}>Likes {post.likeCount} Comments {post.commentCount}</Typography>
</CardContent>
</Card>
)
) : (<p>My Posts</p>);
return (
<Grid container spacing={16}>
<Grid item sm={8} xs={12}>
{recentPostsMarkup}
</Grid>
<Grid item sm={4} xs={12}>
<img src={noImage}/>
<Grid container spacing={24}>
<Grid item sm={4} xs={8}>
{imageMarkup}
{profileMarkup}
{topicsMarkup}
<MyChip
icon={<AddCircle />}
clickable
onClick={handleAddCircle}
<TextField
id="newTopic"
label="new topic"
defaultValue=""
margin="normal"
variant="outlined"
value={this.state.newTopic}
onChange={(event) => this.handleChange(event)}
/>
<AddCircle
color="primary"
clickable
onClick={this.handleAddCircle}
/>
<br />
{authenticated && <Button component={ Link } to='/edit'>Edit Profile Info</Button>}
</Grid>
<Grid item sm={4} xs={8}>
{postMarkup}
</Grid>
<Grid item sm={4} xs={8}>
<Writing_Microblogs />
</Grid>
      
</Grid>
);
}
}
Userline.PropTypes = {
handle: PropTypes.object.isRequired
};
const mapStateToProps = (state) => ({
user: state.user
});
})
export default user;
user.propTypes = {
user: PropTypes.object.isRequired
}
export default connect(mapStateToProps)(user);