Skip to content
This repository was archived by the owner on Aug 18, 2020. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11,565 changes: 11,565 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@pusher/chatkit-client": "^1.9.1",
"@pusher/chatkit-server": "^2.0.1",
"cors": "^2.8.4",
"express": "^4.16.3",
"react": "^16.2.0",
Expand All @@ -13,9 +15,10 @@
"concurrently": "^3.5.1"
},
"scripts": {
"start": "concurrently \"node ./server.js\" \"react-scripts start\"",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
},
"proxy": "http://localhost:3001"
}
56 changes: 54 additions & 2 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,66 @@
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
// remember that we have to require chatkit-server after npm i'ing it
const Chatkit = require("@pusher/chatkit-server");

const app = express()
const app = express();

// after requiring it above, we must INSTANTIATE chatkit; this is important because
// we NEED chatkit connected to the server (as the module name would suggest) so that
// we can listen for requests from the client
// most interactions with Chatkit will happen on the client side
const chatkit = new Chatkit.default({
instanceLocator: "v1:us1:be5b78ce-ac0c-4305-84d9-50a0f286c003",
key: "aab9bb97-b050-40aa-9ad7-23b76507b91b:WLWsaqvqXN6t5q6NkFuxpGB01ohpGjGvWCXfiRxpCv0="
// we get both the instanceLocater and the secret key from the Pusher dashboard
// under the credentials tab
})
/*
the main PURPOSE behind this server is to accept a POST REQUEST from the CLIENT with
the user's USERNAME;
when we RECEIVE that username, we want to create a CHATKIT user WITH that username;
we have to do this on the CLIENT because it needs to happen SECURELY, and this user creation
can only happen if you have the secret key (above), and in order for the KEY to be secret, it
has to remain on the server
*/

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cors())

const PORT = 3001
// define a route for post requests
app.post("/users", (req, res) => {
// as soon as this endpoint is hit, we bring up the username (via destructuring) from
// the request body (req.body)
const { username } = req.body;
chatkit
.createUser({
id: username,
name: username
})
.then(() => res.sendStatus(201)) // indicate user was created successfully
.catch(error => {
// it's possible that the user enters a username that already exists
if (error.error === "services/chatkit/user_already_exists") {
res.sendStatus(200);
} else {
res.status(error.statusCode).json(error);
}
})
})

app.post('/authenticate', (req, res) => {
const authData = chatkit.authenticate({ userId: req.query.user_id })
res.status(authData.status).send(authData.body)
})

// by DEFAULT, express runs on port 3000, so if we have a coupled app, we will
// want to change the default port because the react development build runs on 3000 as well;
// we also have to add a line in the package.json to create a PROXY; this allows us to make
// make requests TO the port express is listening on
const PORT = 3001;

app.listen(PORT, err => {
if (err) {
console.error(err)
Expand Down
39 changes: 38 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,45 @@
import React, { Component } from 'react'
import UsernameForm from "./components/UsernameForm";
import ChatScreen from "./ChatScreen";

class App extends Component {
constructor() {
super();
this.state={
currentUsername:"",
currentScreen: "WhatIsYourUsernameScreen"
}
this.onUsernameSubmitted = this.onUsernameSubmitted.bind(this);
}

onUsernameSubmitted(username){
fetch("/users", {
method: "POST",
headers:{
"Content-Type": "application/json"
},
body: JSON.stringify({username})
})
.then(response => {
console.log("connected successfully after user submitted")
this.setState({
currentUsername: username,
currentScreen: "ChatScreen"
})
})
.catch(error=>{
console.error("error", error);
})
}


render() {
return <h1>Chatly</h1>
if(this.state.currentScreen==="WhatIsYourUsernameScreen"){
return <UsernameForm onSubmit={this.onUsernameSubmitted} />
}
if(this.state.currentScreen==="ChatScreen"){
return <ChatScreen currentUsername={this.state.currentUsername} />
}
}
}

Expand Down
127 changes: 127 additions & 0 deletions src/ChatScreen.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import React, { Component } from "react";
import Chatkit from "@pusher/chatkit-client";
import MessageList from "./components/MessageList";
import SendMessageForm from "./components/SendMessageForm";
import TypingIndicator from "./components/TypingIndicator";
import WhosOnlineList from "./components/WhosOnlineList";

export default class ChatScreen extends Component {
constructor(props) {
super(props)
this.state = {
currentUser: {},
currentRoom: {},
messages: [],
usersWhoAreTyping: [],
}
}

sendMessage = (text) => {
this.state.currentUser.sendMessage({
text,
roomId: this.state.currentRoom.id,
});
}

sendTypingEvent = () => {
this.state.currentUser
.isTypingIn({ roomId: this.state.currentRoom.id })
.catch(error => console.error("error", error))
}

componentDidMount() {
const chatManager = new Chatkit.ChatManager({
instanceLocator: "v1:us1:be5b78ce-ac0c-4305-84d9-50a0f286c003",
userId: this.props.currentUsername,
tokenProvider: new Chatkit.TokenProvider({
url: "/authenticate"
// unlike in the tutorial,
})
})

chatManager.connect()
.then(currentUser => {
this.setState({ currentUser })
console.log("you connected");
return currentUser.subscribeToRoom({
roomId: "20092046",
messageLimit: 100,
hooks: {
onMessage: message => {
this.setState({
messages: [...this.state.messages, message],
});
},
onUserStartedTyping: user => {
this.setState({
usersWhoAreTyping: [...this.state.usersWhoAreTyping, user.name],
});
},
onUserStoppedTyping: user => {
this.setState({
usersWhoAreTyping: this.state.usersWhoAreTyping.filter(
username => username !== user.name
)
});
},
onPresenceChange: () => this.forceUpdate(),
},
});
})
.then(currentRoom => {
this.setState({ currentRoom });
})
.catch(error => console.error("error", error));
}

render() {
const styles = {
container: {
height: '100vh',
display: 'flex',
flexDirection: 'column',
},
chatContainer: {
display: 'flex',
flex: 1,
},
whosOnlineListContainer: {
width: '300px',
flex: 'none',
padding: 20,
backgroundColor: '#2c303b',
color: 'white',
},
chatListContainer: {
padding: 20,
width: '85%',
display: 'flex',
flexDirection: 'column',
},
}

return (
<div style={styles.container}>
<div style={styles.chatContainer}>
<aside style={styles.whosOnlineListContainer}>
<WhosOnlineList
currentUser={this.state.currentUser}
users={this.state.currentRoom.users}
/>
</aside>
<section style={styles.chatListContainer}>
<MessageList
messages={this.state.messages}
style={styles.chatList}
/>
<TypingIndicator usersWhoAreTyping={this.state.usersWhoAreTyping} />
<SendMessageForm
onSubmit={this.sendMessage}
onChange={this.sendTypingEvent}
/>
</section>
</div>
</div>
)
}
}
43 changes: 43 additions & 0 deletions src/components/MessageList.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import React, { Component } from "react";

export default class MessagesList extends Component {
render() {
const styles = {
container: {
overflowY: 'scroll',
flex: 1,
},
ul: {
listStyle: 'none',
},
li: {
marginTop: 13,
marginBottom: 13,
},
senderUsername: {
fontWeight: 'bold',
},
message: { fontSize: 15 },
}

return (
<div style={{
...this.props.style,
...styles.container
// you have to spread this TWICE so you can gain
// access to the inner/nested object
}}>
<ul style={styles.ul}>
{this.props.messages.map((message, index)=>(
<li key={index} style={styles.li}>
<div>
<span style={styles.senderUsername}>{message.senderId}</span>{' '}
</div>
<p style={styles.message}>{message.text}</p>
</li>
))}
</ul>
</div>
)
}
}
65 changes: 65 additions & 0 deletions src/components/SendMessageForm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import React, { Component } from "react";

export default class SendMessageForm extends Component {
constructor(props) {
super(props);
this.state = {
text: "",
};
}

// instead of writing:
// this.onSubmit = this.onSubmit.bind(this), we can use
// PROPERTY INITIALIZER SYNTAX to bind a function to THIS
// component's scope
onSubmit = (e) => {
e.preventDefault();
this.props.onSubmit(this.state.text);
// again, the line below is just for good UX; clear the
// text area after a user hits enter
this.setState({ text: "" })
}

onChange = (e) => {
this.setState({ text: e.target.value });
if (this.props.onChange) {
this.props.onChange();
}
}

render() {
const styles = {
container: {
padding: 20,
borderTop: '1px #4C758F solid',
marginBottom: 20,
},
form: {
display: 'flex',
},
input: {
color: 'inherit',
background: 'none',
outline: 'none',
border: 'none',
flex: 1,
fontSize: 16,
},
}
return (
<div style={styles.container}>
<div>
<form onSubmit={this.onSubmit} style={styles.form}>
<input
type="text"
placehodler ="Type a message here then hit ENTER"
onChange={this.onChange}
value={this.state.text}
style={styles.input}
/>
</form>
</div>
</div>
)
}
}
14 changes: 14 additions & 0 deletions src/components/TypingIndicator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import React from "react";

export default function TypingIndicator (props) {
return(
props.usersWhoAreTyping.length > 0 ?
<div>
{`${props.usersWhoAreTyping
.slice(0,2)
.join(" and ")} is typing`}
</div>
:
<div />
)
}
Loading