├── .gitignore
├── README.md
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── actions
├── auth.actions.js
├── constants.js
├── index.js
└── user.actions.js
├── components
├── Header
│ ├── index.js
│ └── style.css
├── Layout
│ ├── index.js
│ └── style.css
├── PrivateRoute.js
└── UI
│ └── Card
│ ├── index.js
│ └── style.css
├── containers
├── HomePage
│ ├── index.js
│ └── style.css
├── LoginPage
│ ├── index.js
│ └── style.css
└── RegisterPage
│ ├── index.js
│ └── style.css
├── index.css
├── index.js
├── logo.svg
├── reducers
├── auth.reducer.js
├── index.js
└── user.reducer.js
├── serviceWorker.js
├── setupTests.js
└── store
└── index.js
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## Available Scripts
4 |
5 | In the project directory, you can run:
6 |
7 | ### `npm start`
8 |
9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
11 |
12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console.
14 |
15 | ### `npm test`
16 |
17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
19 |
20 | ### `npm run build`
21 |
22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance.
24 |
25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed!
27 |
28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
29 |
30 | ### `npm run eject`
31 |
32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
33 |
34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
35 |
36 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
37 |
38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
39 |
40 | ## Learn More
41 |
42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
43 |
44 | To learn React, check out the [React documentation](https://reactjs.org/).
45 |
46 | ### Code Splitting
47 |
48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
49 |
50 | ### Analyzing the Bundle Size
51 |
52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
53 |
54 | ### Making a Progressive Web App
55 |
56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
57 |
58 | ### Advanced Configuration
59 |
60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
61 |
62 | ### Deployment
63 |
64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
65 |
66 | ### `npm run build` fails to minify
67 |
68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
69 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "web-messenger",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^4.2.4",
7 | "@testing-library/react": "^9.5.0",
8 | "@testing-library/user-event": "^7.2.1",
9 | "firebase": "^7.15.5",
10 | "react": "^16.13.1",
11 | "react-dom": "^16.13.1",
12 | "react-redux": "^7.2.0",
13 | "react-router-dom": "^5.2.0",
14 | "react-scripts": "3.4.1",
15 | "redux": "^4.0.5",
16 | "redux-thunk": "^2.3.0"
17 | },
18 | "scripts": {
19 | "start": "react-scripts start",
20 | "build": "react-scripts build",
21 | "test": "react-scripts test",
22 | "eject": "react-scripts eject"
23 | },
24 | "eslintConfig": {
25 | "extends": "react-app"
26 | },
27 | "browserslist": {
28 | "production": [
29 | ">0.2%",
30 | "not dead",
31 | "not op_mini all"
32 | ],
33 | "development": [
34 | "last 1 chrome version",
35 | "last 1 firefox version",
36 | "last 1 safari version"
37 | ]
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rizwan17/reactjs-firestore-messenger/d78707e587fb5462c1d008e6c1b45eb5e9df5e37/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 |
28 | Web Messenger
29 |
30 |
31 | You need to enable JavaScript to run this app.
32 |
33 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rizwan17/reactjs-firestore-messenger/d78707e587fb5462c1d008e6c1b45eb5e9df5e37/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rizwan17/reactjs-firestore-messenger/d78707e587fb5462c1d008e6c1b45eb5e9df5e37/public/logo512.png
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0;
3 | padding: 0;
4 | }
5 |
6 | body{
7 | font-family: 'Montserrat', sans-serif;
8 | }
9 |
10 | ul{
11 | margin: 0;
12 | padding: 0;
13 | }
14 |
15 | ul li{
16 | list-style: none;
17 | }
18 |
19 | a{
20 | text-decoration: none;
21 | }
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect } from 'react';
2 | import { BrowserRouter as Router, Route } from 'react-router-dom';
3 | import './App.css';
4 | import HomePage from './containers/HomePage';
5 | import LoginPage from './containers/LoginPage';
6 | import RegisterPage from './containers/RegisterPage';
7 | import PrivateRoute from './components/PrivateRoute';
8 | import { useDispatch, useSelector } from 'react-redux';
9 | import { isLoggedInUser } from './actions';
10 |
11 | function App() {
12 |
13 | const auth = useSelector(state => state.auth);
14 | const dispatch = useDispatch()
15 |
16 |
17 | useEffect(() => {
18 | if(!auth.authenticated){
19 | dispatch(isLoggedInUser())
20 | }
21 | }, []);
22 |
23 |
24 | return (
25 |
26 |
27 | {/* only logged in user can access this home route */}
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 | );
36 | }
37 |
38 | export default App;
39 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import App from './App';
4 |
5 | test('renders learn react link', () => {
6 | const { getByText } = render( );
7 | const linkElement = getByText(/learn react/i);
8 | expect(linkElement).toBeInTheDocument();
9 | });
10 |
--------------------------------------------------------------------------------
/src/actions/auth.actions.js:
--------------------------------------------------------------------------------
1 | import { auth, firestore } from 'firebase';
2 | import { authConstanst } from './constants';
3 | import { getRealtimeUsers } from './user.actions';
4 |
5 | export const signup = (user) => {
6 |
7 | return async (dispatch) => {
8 |
9 | const db = firestore();
10 |
11 | dispatch({type: `${authConstanst.USER_LOGIN}_REQUEST`});
12 |
13 | auth()
14 | .createUserWithEmailAndPassword(user.email, user.password)
15 | .then(data => {
16 | console.log(data);
17 | const currentUser = auth().currentUser;
18 | const name = `${user.firstName} ${user.lastName}`;
19 | currentUser.updateProfile({
20 | displayName: name
21 | })
22 | .then(() => {
23 | //if you are here means it is updated successfully
24 | db.collection('users')
25 | .doc(data.user.uid)
26 | .set({
27 | firstName: user.firstName,
28 | lastName: user.lastName,
29 | uid: data.user.uid,
30 | createdAt: new Date(),
31 | isOnline: true
32 | })
33 | .then(() => {
34 | //succeful
35 | const loggedInUser = {
36 | firstName: user.firstName,
37 | lastName: user.lastName,
38 | uid: data.user.uid,
39 | email: user.email
40 | }
41 | localStorage.setItem('user', JSON.stringify(loggedInUser));
42 | console.log('User logged in successfully...!');
43 | dispatch({
44 | type: `${authConstanst.USER_LOGIN}_SUCCESS`,
45 | payload: { user: loggedInUser }
46 | })
47 | })
48 | .catch(error => {
49 | console.log(error);
50 | dispatch({
51 | type: `${authConstanst.USER_LOGIN}_FAILURE`,
52 | payload: { error }
53 | });
54 | });
55 | });
56 | })
57 | .catch(error => {
58 | console.log(error);
59 | })
60 |
61 |
62 | }
63 |
64 |
65 | }
66 |
67 | export const signin = (user) => {
68 | return async dispatch => {
69 |
70 | dispatch({ type: `${authConstanst.USER_LOGIN}_REQUEST` });
71 | auth()
72 | .signInWithEmailAndPassword(user.email, user.password)
73 | .then((data) => {
74 | console.log(data);
75 |
76 |
77 | const db = firestore();
78 | db.collection('users')
79 | .doc(data.user.uid)
80 | .update({
81 | isOnline: true
82 | })
83 | .then(() => {
84 | const name = data.user.displayName.split(" ");
85 | const firstName = name[0];
86 | const lastName = name[1];
87 |
88 | const loggedInUser = {
89 | firstName,
90 | lastName,
91 | uid: data.user.uid,
92 | email: data.user.email
93 | }
94 |
95 | localStorage.setItem('user', JSON.stringify(loggedInUser));
96 |
97 | dispatch({
98 | type: `${authConstanst.USER_LOGIN}_SUCCESS`,
99 | payload: { user: loggedInUser }
100 | });
101 | })
102 | .catch(error => {
103 | console.log(error)
104 | })
105 |
106 |
107 |
108 |
109 |
110 | })
111 | .catch(error => {
112 | console.log(error);
113 | dispatch({
114 | type: `${authConstanst.USER_LOGIN}_FAILURE`,
115 | payload: { error }
116 | })
117 | })
118 |
119 |
120 |
121 | }
122 | }
123 |
124 | export const isLoggedInUser = () => {
125 | return async dispatch => {
126 |
127 | const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
128 |
129 | if(user){
130 | dispatch({
131 | type: `${authConstanst.USER_LOGIN}_SUCCESS`,
132 | payload: { user }
133 | });
134 | }else{
135 | dispatch({
136 | type: `${authConstanst.USER_LOGIN}_FAILURE`,
137 | payload: { error: 'Login again please' }
138 | });
139 | }
140 |
141 |
142 | }
143 | }
144 |
145 | export const logout = (uid) => {
146 | return async dispatch => {
147 | dispatch({ type: `${authConstanst.USER_LOGOUT}_REQUEST` });
148 | //Now lets logout user
149 |
150 | const db = firestore();
151 | db.collection('users')
152 | .doc(uid)
153 | .update({
154 | isOnline: false
155 | })
156 | .then(() => {
157 |
158 | auth()
159 | .signOut()
160 | .then(() => {
161 | //successfully
162 | localStorage.clear();
163 | dispatch({type: `${authConstanst.USER_LOGOUT}_SUCCESS`});
164 | })
165 | .catch(error => {
166 | console.log(error);
167 | dispatch({ type: `${authConstanst.USER_LOGOUT}_FAILURE`, payload: { error } })
168 | })
169 |
170 | })
171 | .catch(error => {
172 | console.log(error);
173 | })
174 |
175 |
176 |
177 |
178 | }
179 | }
180 |
181 |
--------------------------------------------------------------------------------
/src/actions/constants.js:
--------------------------------------------------------------------------------
1 | export const authConstanst = {
2 | USER_LOGIN: 'USER_LOGIN',
3 | USER_LOGOUT: 'USER_LOGOUT'
4 | }
5 |
6 | export const userConstants = {
7 | GET_REALTIME_USERS: 'GET_REALTIME_USERS',
8 | GET_REALTIME_MESSAGES: 'GET_REALTIME_MESSAGES'
9 | }
--------------------------------------------------------------------------------
/src/actions/index.js:
--------------------------------------------------------------------------------
1 | export * from './auth.actions';
2 | export * from './user.actions';
--------------------------------------------------------------------------------
/src/actions/user.actions.js:
--------------------------------------------------------------------------------
1 | import { userConstants } from "./constants";
2 | import { firestore } from 'firebase';
3 |
4 | export const getRealtimeUsers = (uid) => {
5 |
6 | //console.log('uid', uid)
7 |
8 | return async (dispatch) => {
9 |
10 | dispatch({ type: `${userConstants.GET_REALTIME_USERS}_REQUEST` });
11 |
12 | const db = firestore();
13 | const unsubscribe = db.collection("users")
14 | //.where("uid", "!=", uid)
15 | .onSnapshot((querySnapshot) => {
16 | const users = [];
17 | querySnapshot.forEach(function(doc) {
18 | if(doc.data().uid != uid){
19 | users.push(doc.data());
20 | }
21 | });
22 | //console.log(users);
23 |
24 | dispatch({
25 | type: `${userConstants.GET_REALTIME_USERS}_SUCCESS`,
26 | payload: { users }
27 | });
28 |
29 | });
30 |
31 | return unsubscribe;
32 |
33 | }
34 |
35 | }
36 |
37 | export const updateMessage = (msgObj) => {
38 | return async dispatch => {
39 |
40 | const db = firestore();
41 | db.collection('conversations')
42 | .add({
43 | ...msgObj,
44 | isView: false,
45 | createdAt: new Date()
46 | })
47 | .then((data) => {
48 | console.log(data)
49 | //success
50 | // dispatch({
51 | // type: userConstants.GET_REALTIME_MESSAGES,
52 | // })
53 |
54 |
55 | })
56 | .catch(error => {
57 | console.log(error)
58 | });
59 |
60 | }
61 | }
62 |
63 | export const getRealtimeConversations = (user) => {
64 | return async dispatch => {
65 |
66 | const db = firestore();
67 | db.collection('conversations')
68 | .where('user_uid_1', 'in', [user.uid_1, user.uid_2])
69 | .orderBy('createdAt', 'asc')
70 | .onSnapshot((querySnapshot) => {
71 |
72 | const conversations = [];
73 |
74 | querySnapshot.forEach(doc => {
75 |
76 | if(
77 | (doc.data().user_uid_1 == user.uid_1 && doc.data().user_uid_2 == user.uid_2)
78 | ||
79 | (doc.data().user_uid_1 == user.uid_2 && doc.data().user_uid_2 == user.uid_1)
80 | ){
81 | conversations.push(doc.data())
82 | }
83 |
84 |
85 |
86 | // if(conversations.length > 0){
87 |
88 | // }else{
89 | // dispatch({
90 | // type: `${userConstants.GET_REALTIME_MESSAGES}_FAILURE`,
91 | // payload: { conversations }
92 | // })
93 | // }
94 |
95 |
96 |
97 |
98 | });
99 |
100 | dispatch({
101 | type: userConstants.GET_REALTIME_MESSAGES,
102 | payload: { conversations }
103 | })
104 |
105 | console.log(conversations);
106 | })
107 | //user_uid_1 == 'myid' and user_uid_2 = 'yourId' OR user_uid_1 = 'yourId' and user_uid_2 = 'myId'
108 |
109 |
110 | }
111 | }
--------------------------------------------------------------------------------
/src/components/Header/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { NavLink, Link } from 'react-router-dom';
3 | import './style.css';
4 | import { useSelector, useDispatch } from 'react-redux';
5 | import { logout } from '../../actions';
6 |
7 | /**
8 | * @author
9 | * @function Header
10 | **/
11 |
12 | const Header = (props) => {
13 |
14 | const auth = useSelector(state => state.auth);
15 | const dispatch = useDispatch();
16 |
17 | // const logout = () => {
18 | // dispatch(logout())
19 | // }
20 |
21 | return(
22 |
23 |
24 |
Web Messenger
25 |
26 | {
27 | !auth.authenticated ?
28 |
29 | Login
30 | Sign up
31 | : null
32 | }
33 |
34 |
35 |
36 |
37 |
38 | {auth.authenticated ? `Hi ${auth.firstName} ${auth.lastName}` : ''}
39 |
40 |
41 |
42 | {
43 | auth.authenticated ?
44 |
45 | {
46 | dispatch(logout(auth.uid))
47 | }}>Logout
48 | : null
49 | }
50 |
51 |
52 |
53 |
54 |
55 | )
56 |
57 | }
58 |
59 | export default Header
--------------------------------------------------------------------------------
/src/components/Header/style.css:
--------------------------------------------------------------------------------
1 | .header{
2 | width: 100%;
3 | position: relative;
4 | height: 60px;
5 | display: flex;
6 | background: #1b5ff9;
7 | justify-content: space-between;
8 | box-sizing: border-box;
9 | }
10 |
11 | .logo{
12 | font-size: 20px;
13 | color: #fff;
14 | text-transform: capitalize;
15 | font-weight: bold;
16 | margin: 18px;
17 | text-shadow: 0 0;
18 | }
19 |
20 | .menu{
21 | display: flex;
22 | margin: 20px;
23 | }
24 |
25 | .menu > li > a{
26 | color: #fff;
27 | font-weight: bold;
28 | text-shadow: 0 0;
29 | text-decoration: none;
30 | }
31 |
32 | .leftMenu{
33 | display: flex;
34 | color: #fff;
35 | margin: 20px;
36 | }
37 |
38 | .leftMenu > li{
39 | margin: 0 10px;
40 | }
41 |
42 | .leftMenu > li > a{
43 | color: #fff;
44 | }
45 |
46 | .leftMenu > li > a.active{
47 | font-weight: bold;
48 | }
--------------------------------------------------------------------------------
/src/components/Layout/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import Header from '../Header';
3 |
4 | /**
5 | * @author
6 | * @function Layout
7 | **/
8 |
9 | const Layout = (props) => {
10 | return(
11 |
12 |
13 | {props.children}
14 |
15 | )
16 |
17 | }
18 |
19 | export default Layout
--------------------------------------------------------------------------------
/src/components/Layout/style.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rizwan17/reactjs-firestore-messenger/d78707e587fb5462c1d008e6c1b45eb5e9df5e37/src/components/Layout/style.css
--------------------------------------------------------------------------------
/src/components/PrivateRoute.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Route, Redirect } from 'react-router-dom';
3 |
4 | /**
5 | * @author
6 | * @function PrivateRoute
7 | **/
8 |
9 | const PrivateRoute = ({component: Component, ...rest}) => {
10 | return(
11 | {
12 | const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
13 |
14 | if(user){
15 | return
16 | }else{
17 | return
18 | }
19 |
20 | }} />
21 | )
22 |
23 | }
24 |
25 | export default PrivateRoute
--------------------------------------------------------------------------------
/src/components/UI/Card/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import './style.css';
3 |
4 | /**
5 | * @author
6 | * @function Card
7 | **/
8 |
9 | const Card = (props) => {
10 | return(
11 |
12 | {props.children}
13 |
14 | )
15 |
16 | }
17 |
18 | export default Card
--------------------------------------------------------------------------------
/src/components/UI/Card/style.css:
--------------------------------------------------------------------------------
1 | .card{
2 | width: 100%;
3 | border: 1px solid #eee;
4 | background: #fff;
5 | box-shadow: 0 0 5px 1px #ccc;
6 | }
--------------------------------------------------------------------------------
/src/containers/HomePage/index.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react';
2 | import './style.css';
3 | import Layout from '../../components/Layout';
4 | import { useDispatch, useSelector } from 'react-redux';
5 | import { getRealtimeUsers, updateMessage, getRealtimeConversations } from '../../actions';
6 |
7 |
8 | const User = (props) => {
9 |
10 |
11 | const {user, onClick} = props;
12 |
13 | return (
14 | onClick(user)} className="displayName">
15 |
16 |
17 |
18 |
19 | {user.firstName} {user.lastName}
20 |
21 |
22 |
23 | );
24 | }
25 |
26 | const HomePage = (props) => {
27 |
28 | const dispatch = useDispatch();
29 | const auth = useSelector(state => state.auth);
30 | const user = useSelector(state => state.user);
31 | const [chatStarted, setChatStarted] = useState(false);
32 | const [chatUser, setChatUser] = useState('');
33 | const [message, setMessage] = useState('');
34 | const [userUid, setUserUid] = useState(null);
35 | let unsubscribe;
36 |
37 |
38 | useEffect(() => {
39 |
40 | unsubscribe = dispatch(getRealtimeUsers(auth.uid))
41 | .then(unsubscribe => {
42 | return unsubscribe;
43 | })
44 | .catch(error => {
45 | console.log(error);
46 | })
47 |
48 |
49 |
50 |
51 | }, []);
52 |
53 | //console.log(user);
54 |
55 | //componentWillUnmount
56 | useEffect(() => {
57 | return () => {
58 | //cleanup
59 | unsubscribe.then(f => f()).catch(error => console.log(error));
60 |
61 | }
62 | }, []);
63 |
64 |
65 | const initChat = (user) => {
66 |
67 | setChatStarted(true)
68 | setChatUser(`${user.firstName} ${user.lastName}`)
69 | setUserUid(user.uid);
70 |
71 | console.log(user);
72 |
73 | dispatch(getRealtimeConversations({ uid_1: auth.uid, uid_2: user.uid }));
74 |
75 | }
76 |
77 | const submitMessage = (e) => {
78 |
79 | const msgObj = {
80 | user_uid_1: auth.uid,
81 | user_uid_2: userUid,
82 | message
83 | }
84 |
85 |
86 | if(message !== ""){
87 | dispatch(updateMessage(msgObj))
88 | .then(() => {
89 | setMessage('')
90 | });
91 | }
92 |
93 | //console.log(msgObj);
94 |
95 | }
96 |
97 |
98 | return (
99 |
100 |
101 |
102 |
103 |
104 |
105 | {
106 | user.users.length > 0 ?
107 | user.users.map(user => {
108 | return (
109 |
114 | );
115 | }) : null
116 | }
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 | {
126 | chatStarted ? chatUser : ''
127 | }
128 |
129 |
130 | {
131 | chatStarted ?
132 | user.conversations.map(con =>
133 |
134 |
{con.message}
135 |
)
136 | : null
137 | }
138 |
139 |
140 |
141 | {
142 | chatStarted ?
143 |
144 |
: null
151 | }
152 |
153 |
154 |
155 |
156 | );
157 | }
158 |
159 | export default HomePage;
--------------------------------------------------------------------------------
/src/containers/HomePage/style.css:
--------------------------------------------------------------------------------
1 | .container{
2 | display: flex;
3 | position: absolute;
4 | width: 100%;
5 | height: calc(100% - 60px);
6 | overflow: hidden;
7 | }
8 | .listOfUsers{
9 | width: 30%;
10 | height: 100%;
11 | overflow-x: hidden;
12 | border-right: 1px solid #ccc;
13 | }
14 | .chatArea{
15 | width: 70%;
16 | height: 100%;
17 | overflow-x: hidden;
18 | position: relative;
19 | }
20 | .chatHeader{
21 | position: fixed;
22 | width: 70%;
23 | height: 40px;
24 | background: #e2e0e0;
25 | text-align: center;
26 | line-height: 40px;
27 | color: #000;
28 | font-weight: bold;
29 | font-family: sans-serif;
30 | }
31 | .chatControls{
32 | display: flex;
33 | position: fixed;
34 | width: 70%;
35 | height: 50px;
36 | bottom: 0;
37 | }
38 | .chatControls textarea{
39 | width: 90%;
40 | }
41 | .chatControls button{
42 | width: 10%;
43 | }
44 |
45 | .displayName{
46 | display: flex;
47 | align-items: center;
48 | padding: 5px 10px;
49 | box-sizing: border-box;
50 | cursor: pointer;
51 | }
52 |
53 | .displayName.active{
54 | background: #ccc;
55 | }
56 |
57 | .displayName .displayPic{
58 | width: 50px;
59 | height: 50px;
60 | overflow: hidden;
61 | border-radius: 25px;
62 | }
63 |
64 | .displayName .displayPic img{
65 | width: 100%;
66 | height: 100%;
67 | object-fit: cover;
68 | }
69 |
70 | .messageStyle{
71 | background: skyblue;
72 | display: inline-block;
73 | padding: 5px 10px;
74 | border-radius: 10px;
75 | margin: 5px;
76 | display: inline-block;
77 | }
78 |
79 | .messageSections{
80 | height: calc(100% - 90px);
81 | width: 100%;
82 | overflow-x: hidden;
83 | position: relative;
84 | top: 40px;
85 | }
86 |
87 | .onlineStatus{
88 | display: inline-block;
89 | width: 10px;
90 | height: 10px;
91 | background: #16e316;
92 | border-radius: 5px;
93 | box-shadow: 0 0 10px 0 #16e316;
94 | }
95 | .onlineStatus.off{
96 | background: green;
97 | box-shadow: 0 0 0 0;
98 | }
--------------------------------------------------------------------------------
/src/containers/LoginPage/index.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react'
2 | import Layout from '../../components/Layout';
3 | import Card from '../../components/UI/Card';
4 | import { signin, isLoggedInUser } from '../../actions';
5 | import './style.css';
6 | import { useDispatch, useSelector } from 'react-redux';
7 | import { Redirect } from 'react-router-dom';
8 |
9 | /**
10 | * @author
11 | * @function LoginPage
12 | **/
13 |
14 | const LoginPage = (props) => {
15 |
16 | const [email, setEmail] = useState('');
17 | const [password, setPassword] = useState('');
18 | const dispatch = useDispatch();
19 | const auth = useSelector(state => state.auth);
20 |
21 | // useEffect(() => {
22 | // if(!auth.authenticated){
23 | // dispatch(isLoggedInUser())
24 | // }
25 | // }, []);
26 |
27 |
28 |
29 |
30 | const userLogin = (e) => {
31 | e.preventDefault();
32 |
33 | if(email == ""){
34 | alert("Email is required");
35 | return;
36 | }
37 | if(password == ""){
38 | alert("Password is required");
39 | return;
40 | }
41 |
42 | dispatch(signin({ email, password }));
43 |
44 |
45 |
46 |
47 |
48 | }
49 |
50 |
51 | if(auth.authenticated){
52 | return
53 | }
54 |
55 |
56 |
57 | return(
58 |
59 |
87 |
88 | )
89 |
90 | }
91 |
92 | export default LoginPage
--------------------------------------------------------------------------------
/src/containers/LoginPage/style.css:
--------------------------------------------------------------------------------
1 | .loginContainer, .registerContainer{
2 | width: 400px;
3 | position: relative;
4 | margin: 50px auto;
5 | }
--------------------------------------------------------------------------------
/src/containers/RegisterPage/index.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import Layout from '../../components/Layout';
3 | import Card from '../../components/UI/Card';
4 | import { signup } from '../../actions';
5 | import { useDispatch, useSelector } from 'react-redux';
6 | import { Redirect } from 'react-router-dom';
7 |
8 | /**
9 | * @author
10 | * @function RegisterPage
11 | **/
12 |
13 | const RegisterPage = (props) => {
14 |
15 |
16 | const [firstName, setFirstName] = useState('');
17 | const [lastName, setLastName] = useState('');
18 | const [email, setEmail] = useState('');
19 | const [password, setPassword] = useState('');
20 | const dispatch = useDispatch();
21 | const auth = useSelector(state => state.auth);
22 |
23 |
24 | const registerUser = (e) => {
25 |
26 | e.preventDefault();
27 |
28 | const user = {
29 | firstName, lastName, email, password
30 | }
31 |
32 | dispatch(signup(user))
33 | }
34 |
35 |
36 | if(auth.authenticated){
37 | return
38 | }
39 |
40 | return(
41 |
42 |
89 |
90 | )
91 |
92 | }
93 |
94 | export default RegisterPage
--------------------------------------------------------------------------------
/src/containers/RegisterPage/style.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rizwan17/reactjs-firestore-messenger/d78707e587fb5462c1d008e6c1b45eb5e9df5e37/src/containers/RegisterPage/style.css
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 | import firebase from 'firebase';
7 | import { Provider } from 'react-redux';
8 | import store from './store';
9 |
10 |
11 | // Your web app's Firebase configuration
12 | const firebaseConfig = {
13 | apiKey: "AIzaSyBF8co3-j6lq7qGI9b8s0U1YYEIwqXb4_0",
14 | authDomain: "web-messenger-4eb99.firebaseapp.com",
15 | databaseURL: "https://web-messenger-4eb99.firebaseio.com",
16 | projectId: "web-messenger-4eb99",
17 | storageBucket: "web-messenger-4eb99.appspot.com",
18 | messagingSenderId: "252569616509",
19 | appId: "1:252569616509:web:2bbb4c394e9d608f147114",
20 | measurementId: "G-VXYE76S2G7"
21 | };
22 |
23 |
24 | firebase.initializeApp(firebaseConfig);
25 |
26 | window.store = store;
27 |
28 | ReactDOM.render(
29 |
30 |
31 |
32 |
33 | ,
34 | document.getElementById('root')
35 | );
36 |
37 | // If you want your app to work offline and load faster, you can change
38 | // unregister() to register() below. Note this comes with some pitfalls.
39 | // Learn more about service workers: https://bit.ly/CRA-PWA
40 | serviceWorker.unregister();
41 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/src/reducers/auth.reducer.js:
--------------------------------------------------------------------------------
1 | import { authConstanst } from "../actions/constants"
2 |
3 | const initState = {
4 | firstName: '',
5 | lastName: '',
6 | email: '',
7 | authenticating: false,
8 | authenticated: false,
9 | error: null
10 | }
11 |
12 | export default (state = initState, action) => {
13 |
14 | console.log(action);
15 |
16 | switch(action.type){
17 |
18 | case `${authConstanst.USER_LOGIN}_REQUEST`:
19 | state = {
20 | ...state,
21 | authenticating: true
22 | }
23 | break;
24 | case `${authConstanst.USER_LOGIN}_SUCCESS`:
25 | state = {
26 | ...state,
27 | ...action.payload.user,
28 | authenticated: true,
29 | authenticating: false
30 | }
31 | break;
32 | case `${authConstanst.USER_LOGIN}_FAILURE`:
33 | state = {
34 | ...state,
35 | authenticated: false,
36 | authenticating: false,
37 | error: action.payload.error
38 | }
39 | break;
40 | case `${authConstanst.USER_LOGOUT}_REQUEST`:
41 | break;
42 | case `${authConstanst.USER_LOGOUT}_SUCCESS`:
43 | state = {
44 | ...initState
45 | }
46 | break;
47 | case `${authConstanst.USER_LOGOUT}_FAILURE`:
48 | state = {
49 | ...state,
50 | error: action.payload.error
51 | }
52 | break;
53 |
54 | }
55 |
56 |
57 | return state;
58 | }
--------------------------------------------------------------------------------
/src/reducers/index.js:
--------------------------------------------------------------------------------
1 | import { combineReducers } from "redux";
2 | import authReducer from './auth.reducer';
3 | import userReducer from './user.reducer';
4 |
5 | const rootReducer = combineReducers({
6 | auth: authReducer,
7 | user: userReducer,
8 | });
9 |
10 | export default rootReducer;
--------------------------------------------------------------------------------
/src/reducers/user.reducer.js:
--------------------------------------------------------------------------------
1 | import { userConstants } from "../actions/constants"
2 |
3 | const intiState = {
4 | users: [],
5 | conversations: []
6 | }
7 |
8 | export default (state = intiState, action) => {
9 |
10 | switch(action.type){
11 | case `${userConstants.GET_REALTIME_USERS}_REQUEST`:
12 | break;
13 | case `${userConstants.GET_REALTIME_USERS}_SUCCESS`:
14 | state = {
15 | ...state,
16 | users: action.payload.users
17 | }
18 | break;
19 | case userConstants.GET_REALTIME_MESSAGES:
20 | state = {
21 | ...state,
22 | conversations: action.payload.conversations
23 | }
24 | break;
25 | case `${userConstants.GET_REALTIME_MESSAGES}_FAILURE`:
26 | state = {
27 | ...state,
28 | conversations: []
29 | }
30 | break;
31 |
32 | }
33 |
34 |
35 | return state;
36 |
37 | }
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' },
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister();
136 | })
137 | .catch(error => {
138 | console.error(error.message);
139 | });
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom/extend-expect';
6 |
--------------------------------------------------------------------------------
/src/store/index.js:
--------------------------------------------------------------------------------
1 | import { createStore, applyMiddleware } from 'redux';
2 | import rootReducer from '../reducers';
3 | import thunk from 'redux-thunk';
4 |
5 |
6 | const store = createStore(rootReducer, applyMiddleware(thunk));
7 |
8 |
9 | export default store;
--------------------------------------------------------------------------------