dispatch/client/src/js/socket.js

81 lines
2.3 KiB
JavaScript
Raw Normal View History

2016-02-04 02:35:50 +00:00
import { routeActions } from 'react-router-redux';
2015-12-28 23:34:32 +00:00
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 }) {
2016-03-14 22:22:24 +00:00
socket.onAny((event, data) => {
const type = `SOCKET_${event.toUpperCase()}`;
2015-12-28 23:34:32 +00:00
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;
if (server && channel) {
const { nick } = state.servers.get(server);
const [joinedChannel] = data.channels;
if (server === data.server &&
nick === data.user &&
channel !== joinedChannel &&
normalizeChannel(channel) === normalizeChannel(joinedChannel)) {
dispatch(select(server, joinedChannel));
}
2015-12-28 23:34:32 +00:00
}
});
socket.on('servers', data => {
if (!data) {
2016-01-15 19:56:03 +00:00
dispatch(routeActions.replace('/connect'));
2015-12-28 23:34:32 +00:00
}
});
socket.on('join', ({ user, server, channels }) =>
dispatch(inform(`${user} joined the channel`, server, channels[0]))
);
socket.on('part', ({ user, server, channel, reason }) =>
dispatch(inform(withReason(`${user} left the channel`, reason), server, channel))
2015-12-28 23:34:32 +00:00
);
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 }) =>
2016-02-04 02:35:50 +00:00
dispatch(addMessages(content.map(line => ({
server,
to: server,
message: line
}))))
2015-12-28 23:34:32 +00:00
);
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));
});
}