dispatch/client/src/js/socket.js

82 lines
2.3 KiB
JavaScript
Raw Normal View History

2015-12-28 23:34:32 +00:00
import { replacePath } from 'redux-simple-router';
import { broadcast, inform, addMessage, addMessages } from './actions/message';
import { select } from './actions/tab';
import { normalizeChannel } from './util';
2015-12-28 23:34:32 +00:00
function withReason(message, reason) {
return message + (reason ? ` (${reason})` : '');
2015-02-21 06:48:25 +00:00
}
2015-01-17 01:37:21 +00:00
2015-12-28 23:34:32 +00:00
export default function handleSocket(socket, { dispatch, getState }) {
socket.onAny(data => {
const type = `SOCKET_${socket.event.toUpperCase()}`;
if (Array.isArray(data)) {
dispatch({ type, data });
} else {
dispatch({ type, ...data });
}
});
socket.on('message', message => dispatch(addMessage(message)));
socket.on('pm', message => dispatch(addMessage(message)));
socket.on('join', data => {
const state = getState();
const { server, channel } = state.tab.selected;
const { nick } = state.servers.get(server);
const [joinedChannel] = data.channels;
if (channel &&
server === data.server &&
nick === data.user &&
channel !== joinedChannel &&
normalizeChannel(channel) === normalizeChannel(joinedChannel)) {
dispatch(select(server, joinedChannel));
}
});
socket.on('servers', data => {
if (!data) {
dispatch(replacePath('/connect'));
}
});
socket.on('join', ({ user, server, channels }) =>
dispatch(inform(`${user} joined the channel`, server, channels[0]))
);
socket.on('part', ({ user, server, channels, reason }) =>
dispatch(inform(withReason(`${user} left the channel`, reason), server, channels[0]))
);
socket.on('quit', ({ user, server, reason, channels }) =>
dispatch(broadcast(withReason(`${user} quit`, reason), server, channels))
);
socket.on('nick', data =>
dispatch(broadcast(`${data.old} changed nick to ${data.new}`, data.server, data.channels))
);
socket.on('motd', ({ content, server }) =>
dispatch(addMessages(content.map(line => {
return {
server,
to: server,
message: line
};
})))
);
socket.on('whois', data => {
const tab = getState().tab.selected;
dispatch(inform([
`Nick: ${data.nick}`,
`Username: ${data.username}`,
`Realname: ${data.realname}`,
`Host: ${data.host}`,
`Server: ${data.server}`,
`Channels: ${data.channels}`
], tab.server, tab.channel));
});
}