|
import io from 'socket.io-client'; |
|
|
|
import { ACTION, SocketActions } from '../actions/types'; |
|
import { Dispatch } from 'react'; |
|
import { AnyAction, MiddlewareAPI } from 'redux'; |
|
|
|
export const socketMiddleware = (baseUrl: string) => { |
|
return (storeAPI: MiddlewareAPI) => { |
|
let socket = io(baseUrl); |
|
|
|
let listener: SocketIOClient.Emitter; |
|
|
|
|
|
return (next: Dispatch<AnyAction>) => (action: SocketActions) => { |
|
|
|
if (action.type === ACTION.SEND_SOCKET_MESSAGE) { |
|
socket.emit('simple-chat-message', action.payload); |
|
return; |
|
} |
|
|
|
|
|
if (action.type === ACTION.SEND_SOCKET_PRIVATE_MESSAGE) { |
|
socket.emit('simple-chat-private-message', action.payload); |
|
return; |
|
} |
|
|
|
|
|
if (action.type === ACTION.SIGN_IN) { |
|
socket.emit('simple-chat-sign-in', action.payload); |
|
listener = setupSocketListener(socket, storeAPI); |
|
} |
|
|
|
|
|
|
|
if (action.type === ACTION.GET_INITIAL_DATA) { |
|
|
|
let servers = Object.keys(action.payload.servers); |
|
let serverIds: string[] = []; |
|
servers.forEach((server, i) => { |
|
serverIds[i] = server.split('-')[1]; |
|
}); |
|
|
|
|
|
serverIds.forEach(serverId => { |
|
socket.emit('subscribe', serverId); |
|
}); |
|
} |
|
|
|
|
|
if (action.type === ACTION.ADD_SERVER) { |
|
let serverId = action.payload.server.split('-')[1]; |
|
socket.emit('subscribe', serverId); |
|
} |
|
|
|
|
|
if (action.type === ACTION.UPDATE_ACTIVE_STATE) { |
|
socket.emit('update-active'); |
|
} |
|
|
|
if (action.type === ACTION.SEND_SOCKET_JOIN_VOICE) { |
|
socket.emit('user-join-voice', action.payload); |
|
} |
|
|
|
if (action.type === ACTION.SEND_SOCKET_LEAVE_VOICE) { |
|
socket.emit('user-leave-voice', action.payload); |
|
} |
|
|
|
if (action.type === ACTION.SEND_SOCKET_RTC_SIGNAL) { |
|
socket.emit('voice-signal', action.payload); |
|
} |
|
|
|
return next(action); |
|
}; |
|
}; |
|
}; |
|
|
|
|
|
|
|
|
|
function setupSocketListener(socket: SocketIOClient.Socket, storeAPI: MiddlewareAPI): SocketIOClient.Emitter { |
|
return socket.on('update', (action: any) => { |
|
|
|
if (action.type === 'message') { |
|
storeAPI.dispatch({ |
|
type: ACTION.RECEIVE_SOCKET_MESSAGE, |
|
payload: action.payload |
|
}); |
|
} else if (action.type === 'private-message') { |
|
storeAPI.dispatch({ |
|
type: ACTION.RECEIVE_SOCKET_PRIVATE_MESSAGE, |
|
payload: action.payload |
|
}); |
|
} else if (action.type === 'user-join-voice') { |
|
storeAPI.dispatch({ |
|
type: ACTION.RECEIVE_SOCKET_JOIN_VOICE, |
|
payload: action.payload |
|
}); |
|
} else if (action.type === 'user-leave-voice') { |
|
storeAPI.dispatch({ |
|
type: ACTION.RECEIVE_SOCKET_LEAVE_VOICE, |
|
payload: action.payload |
|
}); |
|
} else if (action.type === 'voice-signal') { |
|
storeAPI.dispatch({ |
|
type: ACTION.RECEIVE_SOCKET_RTC_SIGNAL, |
|
payload: action.payload |
|
}); |
|
} |
|
}); |
|
} |
|
|