fix components

backend
- sendNamespaces => sendNamespace

frontend
- namespace => buffer
- activateChate takes optional chats object to set it on state
- improved message/error handling
This commit is contained in:
data 2019-07-28 20:50:06 +01:00
parent 830a61433b
commit a09d9a8b9d
5 changed files with 246 additions and 178 deletions

View File

@ -14,6 +14,10 @@ module.exports = io => {
)
socket.on('message', message => {
if (!message) {
console.log('Weird. Received empty message.')
return
}
console.log('sending message to ', message.to, message)
io.to(message.to).emit('message', message)
})
@ -21,6 +25,7 @@ module.exports = io => {
socket.on('join', room => {
console.log(`${socket.id} joins ${room}`)
socket.join(room, () => {
sendNamespace(room)
io.to(room).emit('user joined', { room, socketId: socket.id })
io.of(room).clients((error, clients) => {
if (error) throw error
@ -34,31 +39,48 @@ module.exports = io => {
console.log('all clients:', c)
})
})
socket.on('part', namespace => {
console.log('part', socket.id, namespace)
io.to(namespace).emit('user left', { namespace, socketId: socket.id })
socket.leave(namespace)
socket.on('part', room => {
console.log('part', socket.id, room)
socket.leave(room, () => {
console.log(Object.keys(io.sockets.adapter.rooms))
if (io.sockets.adapter.rooms[room]) {
Object.keys(io.sockets.adapter.rooms[room]['sockets']).map(s => {
sendNamespace(room, s)
return s
})
} else {
console.log(`room ${room} disappeared`)
}
io.to(room).emit('user left', { room, socketId: socket.id })
})
})
socket.on('change nick', nick => {
io.emit('changed nick', { socketId: socket.id, nick: nick })
console.log(`${users[socket.id]['nick']} changed nick to ${nick}`)
socket.broadcast.emit('changed nick', { socketId: socket.id, nick: nick })
users[socket.id]['nick'] = nick
})
socket.on('get namespaces', () => sendNamespaces())
const sendNamespaces = () => {
const namespaces = Object.keys(io.sockets.adapter.rooms).map(k => ({
namespace: k,
sockets: Object.keys(io.sockets.adapter.rooms[k]['sockets']),
}))
io.emit('got namespaces', namespaces)
const sendNamespace = (room, socketId) => {
if (io.sockets.adapter.rooms[room]) {
const namespace = {
namespace: room,
sockets: Object.keys(io.sockets.adapter.rooms[room]['sockets']),
}
if (socketId) {
socket.emit('got namespace', namespace)
} else {
io.emit('got namespace', namespace)
}
}
}
socket.on('disconnect', async () => {
io.emit('user disconnected', socket.id)
console.log(`${socket.id} has disconnected.`)
//sendNamespaces()
io.emit('user disconnected', socket.id)
// OPTIMIZE if there's an easy way to inform rooms the socket was part of
// they should be informed here
//socket.rooms.map(r => r.sockets.map(s => sendNamespace(r, s)))
})
})
}

View File

@ -7,6 +7,11 @@ import moment from 'moment'
const initialState = {
loading: true,
messages: [],
allNamespaces: [],
chats: [],
room: '/',
allUsers: [],
allSockets: [],
allMessages: [],
buffers: [],
@ -18,9 +23,8 @@ class App extends React.Component {
super()
this.state = initialState
this.socket = socket
this.submitMessage = this.submitMessage.bind(this)
this.join = this.join.bind(this)
this.readMessages = this.readMessages.bind(this)
this.formatMessage = this.formatMessage.bind(this)
this.countUnreadMessages = this.countUnreadMessages.bind(this)
this.readMessages = this.readMessages.bind(this)
this.activateChat = this.activateChat.bind(this)
@ -33,6 +37,9 @@ class App extends React.Component {
componentDidMount() {
this.fetchData()
// EVENTS
this.socket.on('connect', () => {
console.log(`I am ${this.socket.id}`)
this.join('#projex')
@ -46,73 +53,64 @@ class App extends React.Component {
})
this.socket.on('user disconnected', socketId => {
console.log(`${socketId} disconnected.`)
// mark user as offline
const oldNick = this.state.allUsers.find(u => u.socketId === socketId)
.nick
console.log(`${oldNick} disconnected.`)
const allUsers = this.state.allUsers.map(u => {
// TODO find a better way to preserve existing chat windows
if (u.socketId === socketId) u.offline = true
return u
})
const oldNick = allUsers.find(u => u.socketId === socketId).nick
this.setState({ allUsers })
// inform channels user was part of
this.state.chats.map(c => {
if (c === socketId) {
const messages = this.state.messages.concat(
this.addNotification(`${oldNick} disconnected`, c)
)
this.setState({ messages })
}
this.state.allNamespaces.map(n => {
if (n.namespace === c && n.sockets.find(s => s === socketId)) {
const messages = this.state.messages.concat(
this.addNotification(`${oldNick} disconnected`, c)
)
this.setState({ messages })
}
return n
// inform sockets the user was chatting with
this.state.chats
.filter(c => c === socketId)
.map(c => {
this.addNotification(`${oldNick} disconnected`, this.socket.id, c)
return c
})
return c
// inform channels the user was part of and update their socket list
const allNamespaces = this.state.allNamespaces.map(n => {
if (n.sockets.find(s => s === socketId)) {
n.sockets = n.sockets.filter(s => s === socketId)
this.addNotification(`${oldNick} disconnected`, n.namespace)
}
return n
})
this.setState({ allNamespaces })
})
this.socket.on('user joined', data => {
const { namespace, socketId } = data
const { room, socketId } = data
const user = this.state.allUsers.find(u => u.socketId === socketId)
console.log(`${user.nick} joined ${namespace}`)
const messages = this.state.messages.concat(
this.addNotification(`${user.nick} joined ${namespace}`, namespace)
)
this.setState({ messages })
console.log(`${user.nick} joined ${room}`)
this.addNotification(`${user.nick} joined ${room}`, room)
})
this.socket.on('user left', data => {
const { namespace, socketId } = data
const { room, socketId } = data
const user = this.state.allUsers.find(u => u.socketId === socketId)
console.log(`${user.nick} left ${namespace}`)
const messages = this.state.messages.concat(
this.addNotification(`${user.nick} left ${namespace}`, namespace)
)
this.setState({ messages })
console.log(`${user.nick} left ${room}`)
this.addNotification(`${user.nick} left ${room}`, room)
})
this.socket.on('changed nick', user => {
if (user.socketId === this.state.user.socketId) return
console.log(`${user.socketId} is now known as ${user.nick}.`)
const allUsers = this.state.allUsers
const oldNick = allUsers.find(u => u.socketId === user.socketId).nick
// inform channels user is part of
this.state.chats.map(c => {
if (c === user.socketId) {
const messages = this.state.messages.concat(
this.addNotification(`${oldNick} is now known as ${user.nick}`, c)
this.addNotification(
`${oldNick} is now known as ${user.nick}`,
this.socket.id,
c
)
this.setState({ messages })
}
this.state.allNamespaces.map(n => {
if (n.namespace === c && n.sockets.find(s => s === user.socketId)) {
const messages = this.state.messages.concat(
this.addNotification(`${oldNick} is now known as ${user.nick}`, c)
)
this.setState({ messages })
this.addNotification(`${oldNick} is now known as ${user.nick}`, c)
}
return n
})
@ -120,7 +118,7 @@ class App extends React.Component {
})
// update nick
allUsers.map(u => {
if (u.socketId === user.socketId) u.nick = user.nick
if (u.socketId === user.socketId) u.nick = this.socket.nick
return u
})
this.setState({ allUsers })
@ -134,11 +132,6 @@ class App extends React.Component {
this.setState({ allNamespaces })
})
this.socket.on('got namespaces', allNamespaces => {
console.log('got namespaces:', allNamespaces)
this.setState({ allNamespaces })
})
this.socket.on('got users', allUsers => {
console.log('got users:', allUsers)
this.setState({ allUsers })
@ -146,7 +139,7 @@ class App extends React.Component {
this.socket.on('message', msg => {
if (
msg.to === this.state.user.socketId &&
msg.to === this.socket.id &&
!this.state.chats.find(c => c === msg.from)
) {
console.log(`${msg.from} wants to chat with me.`)
@ -154,50 +147,65 @@ class App extends React.Component {
this.setState({ chats })
}
if (
(msg.to[0] === '#' && msg.to === this.state.namespace) ||
(msg.to[0] !== '#' && msg.from === this.state.namespace)
(msg.to[0] === '#' && msg.to === this.state.buffer) ||
(msg.to[0] !== '#' && msg.from === this.state.buffer)
)
msg.read = true
const messages = this.state.messages.concat(msg)
console.log(msg)
this.setState({ messages })
})
}
parseCommand() {
const args = this.state.message.split(' ')
const cmd = args[0].slice(1)
if (cmd === 'join') {
if (!args[1]) {
alert('did you forget a channel to join?')
return
}
this.join(args[1])
} else if (cmd === 'part' || cmd === 'leave') {
this.part(args[1] ? args[1] : this.state.namespace)
} else if (cmd === 'nick') this.nick(args[1])
else {
alert(`unknown command: ${cmd}`)
// FUNCTIONS
join(room) {
if (room[0] !== '#') return alert('Use a leading #, silly!')
if (this.state.chats.find(c => c === room)) return
console.log('joining', room)
const chats = this.state.chats.concat(room)
this.socket.emit('join', room, ack => console.log('ack', ack))
this.activateChat(room, chats)
}
query(user) {
if (this.state.chats.find(c => c === user.socketId)) {
this.activateChat(user.socketId)
return
}
this.setState({ message: '' })
console.log(`starting chat with ${user.nick}`)
const chats = this.state.chats.concat(user.socketId)
this.activateChat(user.socketId, chats)
}
addNotification(text, namespace) {
return this.formatMessage(
text,
'server',
'server',
namespace,
namespace === this.state.namespace ? true : false
addNotification(text, to, from) {
if (!text || !to) {
console.log('[addNotification] Missing parameter(s)', text, to)
return
}
const messages = this.state.messages.concat(
this.formatMessage(
text,
from ? from : 'server',
'server',
to,
to === this.state.buffer ? true : false
)
)
this.setState({ messages })
}
formatMessage(text, from, nick, to, read) {
if (!text || !from || !to || !nick) {
console.log(
'[formatMessage] Dropping malformed message (requiring text, from, nick and to).'
'[formatMessage] Dropping malformed message (requiring text, from, nick and to).',
text,
from,
nick,
to,
read
)
return
}
const message = {
return {
id: uuid(),
date: moment().format('MMMM D YYYY, h:mm a'),
text: text,
@ -206,22 +214,6 @@ class App extends React.Component {
to: to,
read: read,
}
return message
}
submitMessage(msg) {
console.log(msg)
if (msg[0] === '/') return this.parseCommand()
if (!msg.length > 0) return
this.sendMessage(
this.formatMessage(
msg,
this.state.user.socketId,
this.state.user.nick,
this.state.namespace
)
)
this.setState({ message: '' })
}
renderLoading() {
return <div>loading...</div>
@ -230,54 +222,10 @@ class App extends React.Component {
renderError() {
return <div>something went wrong.</div>
}
join(room) {
if (room[0] !== '#') return alert('Use a leading #, silly!')
if (this.state.chats.find(c => c === room)) return
console.log('joining', room)
const chats = this.state.chats.concat(room)
this.socket.emit('join', room, ack => console.log('ack', ack))
this.setState({ room, chats })
}
part(namespace) {
console.log(`leaving ${namespace}`)
socket.emit('part', namespace)
const chats = this.state.chats.filter(c => c !== namespace)
this.setState({ chats, namespace: '/' })
}
nick(nick) {
if (nick[0] === '#') {
alert('nick cannot start with #, sorry!')
return
}
console.log(`Changing nick to ${nick}`)
const user = this.state.user
user.nick = nick
this.setState({ user })
this.socket.emit('change nick', nick)
}
query(user) {
if (this.state.chats.find(c => c === user.socketId)) {
this.setState({ namespace: user.socketId })
return
}
console.log(`starting chat with ${user.nick}`)
const chats = this.state.chats.concat(user.socketId)
this.setState({ namespace: user.socketId, chats })
}
sendMessage(msg) {
this.socket.emit('message', msg)
if (msg.to[0] !== '#') {
if (msg.to === this.state.namespace) msg.read = true
const messages = this.state.messages.concat(msg)
this.setState({ messages })
}
}
countUnreadMessages(nsp) {
return this.state.messages.filter(
m =>
!m.read &&
(m.to === nsp || (m.to === this.state.user.socketId && m.from === nsp))
!m.read && (m.to === nsp || (m.to === this.socket.id && m.from === nsp))
).length
}
@ -292,21 +240,26 @@ class App extends React.Component {
this.setState({ messages })
}
activateChat(namespace) {
this.readMessages(namespace)
this.setState({ namespace })
activateChat(buffer, chats) {
this.readMessages(buffer)
this.setState({ buffer })
if (chats) this.setState({ chats })
}
renderApp() {
const title =
this.state.namespace[0] === '#'
this.state.buffer[0] === '#'
? 'Channel'
: this.state.namespace === this.state.user.socketId
? 'Namespace'
: this.state.buffer === this.socket.id
? 'buffer'
: 'Chat with'
console.log(this.socket)
return (
<main role="main" className="d-flex h-100 flex-column">
<Topbar query={this.query} join={this.join} {...this.state} />
<Topbar
query={this.query}
join={this.join}
socket={this.socket}
{...this.state}
/>
<div className="d-flex h-100">
<Sidebar
activateChat={this.activateChat}
@ -315,7 +268,10 @@ class App extends React.Component {
/>
<Messages
title={title}
submitMessage={this.submitMessage}
socket={this.socket}
activateChat={this.activateChat}
join={this.join}
formatMessage={this.formatMessage}
{...this.state}
/>
</div>

View File

@ -12,13 +12,76 @@ class MessageEntryForm extends React.Component {
handleChange(e) {
this.setState({ [e.target.name]: e.target.value })
}
handleSubmit(e) {
e.preventDefault()
this.props.submitMessage(this.state.message)
this.submitMessage(this.state.message)
}
submitMessage(msg) {
if (msg[0] === '/') return this.parseCommand()
if (!msg.length > 0) return
this.sendMessage(
this.props.formatMessage(
msg,
this.props.socket.id,
this.props.socket.nick,
this.props.buffer
)
)
this.setState({ message: '' })
}
sendMessage(msg) {
if (!msg) {
console.log('[sendMessage] Got no message. Fix your code!')
return
}
this.props.socket.emit('message', msg)
if (msg.to[0] !== '#') {
if (msg.to === this.props.buffer) msg.read = true
const messages = this.props.messages.concat(msg)
this.setState({ messages })
}
}
parseCommand() {
const args = this.state.message.split(' ')
const cmd = args[0].slice(1)
if (cmd === 'join') {
if (!args[1]) {
alert('did you forget a channel to join?')
return
}
this.props.join(args[1])
} else if (cmd === 'part' || cmd === 'leave') {
this.part(args[1] ? args[1] : this.props.buffer)
} else if (cmd === 'nick') {
if (!args[1]) {
alert('A new nick could be useful.')
return
}
this.nick(args[1])
} else {
alert(`unknown command: ${cmd}`)
}
this.setState({ message: '' })
}
part(room) {
console.log(`leaving ${room}`)
this.props.socket.emit('part', room)
const chats = this.props.chats.filter(c => c !== room)
this.props.activateChat('/', chats)
}
nick(nick) {
if (nick[0] === '#') {
alert('nick cannot start with #, sorry!')
return
}
console.log(`Changing nick to ${nick}`)
this.props.socket.nick = nick
this.props.socket.emit('change nick', nick)
}
render() {
return (
return this.props.socket.id ? (
<form onSubmit={this.handleSubmit}>
<input
className="bg-light p-2 w-100"
@ -32,9 +95,11 @@ class MessageEntryForm extends React.Component {
type="submit"
onSubmit={this.handleSubmit}
>
submit as {this.props.user.nick}
submit as {this.props.socket.nick}
</Button>
</form>
) : (
<div>Disconnected</div>
)
}
}

View File

@ -1,13 +1,23 @@
import React from 'react'
import MessageEntryForm from './MessageEntryForm'
const Messages = props => {
const { title, namespace, messages, user, submitMessage } = props
const {
title,
buffer,
chats,
messages,
socket,
activateChat,
join,
formatMessage,
submitMessage,
} = props
return (
<div className="bg-secondary d-flex flex-column flex-grow-1 px-2 pb-4">
{/*Main Section Header*/}
<div className="d-flex justify-content-between flex-wrap flex-md-nowrap pt-3 pb-2 mb-3 border-bottom">
<h4 className="mr-auto ml-3">
{title} {namespace}
{title} {buffer}
</h4>
</div>
{/*Main Section Content*/}
@ -16,19 +26,34 @@ const Messages = props => {
{messages
.filter(
m =>
(m.to[0] === '#' && m.to === namespace) ||
(m.to[0] !== '#' && m.from === namespace) ||
(m.from === user.socketId && m.to === namespace)
(m.to[0] === '#' && m.to === buffer) ||
(m.to[0] !== '#' && m.from === buffer) ||
(m.from === socket.socketId && m.to === buffer)
)
.map(m => (
<div className="row d-flex justify-content-between" key={m.id}>
<div className="col">{m.date}</div>
<div className="col">{m.nick}</div>
<div>{m.text}</div>
</div>
))}
.map(m => {
console.log(m)
const rowColor = m.nick === 'server' ? 'text-secondary' : ''
return (
<div className={`d-flex ${rowColor}`} key={m.id}>
<div className="pr-3 text-nowrap">{m.date}</div>
{m.nick === 'server' ? null : (
<div className="pr-3 text-nowrap">{m.nick}:</div>
)}
<div className="pr-3 flex-grow-1">{m.text}</div>
</div>
)
})}
</div>
<MessageEntryForm submitMessage={submitMessage} user={user} />
<MessageEntryForm
activateChat={activateChat}
formatMessage={formatMessage}
submitMessage={submitMessage}
join={join}
buffer={buffer}
chats={chats}
messages={messages}
socket={socket}
/>
</div>
</div>
)

View File

@ -2,7 +2,7 @@ import React from 'react'
import { Navbar, Nav, Dropdown } from 'react-bootstrap'
const Topbar = props => {
const { allUsers, user, allNamespaces, query, join } = props
const { allUsers, socket, allNamespaces, query, join } = props
return (
<Navbar bg="dark" variant="dark" expand="lg">
@ -16,7 +16,7 @@ const Topbar = props => {
<Dropdown.Menu className="bg-dark">
{allUsers
.filter(u => u.socketId !== user.id && u.offline !== true)
.filter(u => u.socketId !== socket.id && u.offline !== true)
.map(u => (
<Dropdown.Item
key={u.socketId}