1
0
forked from notnull/ircz

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

View File

@ -12,13 +12,76 @@ class MessageEntryForm extends React.Component {
handleChange(e) { handleChange(e) {
this.setState({ [e.target.name]: e.target.value }) this.setState({ [e.target.name]: e.target.value })
} }
handleSubmit(e) { handleSubmit(e) {
e.preventDefault() 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() { render() {
return ( return this.props.socket.id ? (
<form onSubmit={this.handleSubmit}> <form onSubmit={this.handleSubmit}>
<input <input
className="bg-light p-2 w-100" className="bg-light p-2 w-100"
@ -32,9 +95,11 @@ class MessageEntryForm extends React.Component {
type="submit" type="submit"
onSubmit={this.handleSubmit} onSubmit={this.handleSubmit}
> >
submit as {this.props.user.nick} submit as {this.props.socket.nick}
</Button> </Button>
</form> </form>
) : (
<div>Disconnected</div>
) )
} }
} }

View File

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

View File

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