Files
Iris/src/js/services/pusher/middleware.js

89 lines
3.0 KiB
JavaScript
Raw Normal View History

2016-10-27 16:58:11 +13:00
var actions = require('./actions.js')
2016-10-27 21:20:05 +13:00
var helpers = require('../../helpers.js')
2016-10-27 16:58:11 +13:00
const PusherMiddleware = (function(){
// container for the actual Mopidy socket
var socket = null;
// handle all manner of socket messages
const handleMessage = (ws, store, message) => {
switch( message.action ){
default:
2016-10-27 21:20:05 +13:00
var name = message.action.toUpperCase();
name = name.replace('GET_','');
store.dispatch({ type: 'PUSHER_'+name, data: message.data })
2016-10-27 16:58:11 +13:00
}
}
2016-10-27 21:20:05 +13:00
const makeRequest = (data) => {
data.type = 'query';
data.message_id = helpers.generateGuid();
socket.send( JSON.stringify(data) );
}
2016-10-27 16:58:11 +13:00
/**
* Middleware
*
* This behaves like an action interceptor. We listen for specific actions
* and handle special functionality. If the action is not in our switch, then
* it just proceeds to the next middleware, or default functionality
**/
return store => next => action => {
switch(action.type) {
case 'PUSHER_CONNECT':
if(socket != null) socket.close();
store.dispatch({ type: 'PUSHER_CONNECTING' });
var state = store.getState();
var connection = {
clientid: Math.random().toString(36).substr(2, 9),
connectionid: helpers.generateGuid(),
username: Math.random().toString(36).substr(2, 9)
}
2016-10-28 15:58:07 +13:00
if( state.pusher.username ) connection.username = state.pusher.username;
2016-10-27 16:58:11 +13:00
socket = new WebSocket(
'ws://'+state.mopidy.host+':'+state.pusher.port+'/pusher',
[ connection.clientid, connection.connectionid, connection.username ]
2016-10-27 16:58:11 +13:00
);
socket.onopen = () => {
store.dispatch({ type: 'PUSHER_CONNECTED', connection: connection });
2016-10-28 15:58:07 +13:00
store.dispatch({ type: 'PUSHER_SET_USERNAME', username: connection.username });
2016-10-27 16:58:11 +13:00
};
socket.onmessage = (message) => {
2016-10-27 16:58:11 +13:00
var message = JSON.parse(message.data);
handleMessage( socket, store, message )
};
break;
2016-10-27 21:20:05 +13:00
case 'PUSHER_CONNECTED':
makeRequest({ action: 'get_version' });
return next(action);
break;
2016-10-28 10:48:55 +13:00
case 'PUSHER_CLIENT_CONNECTED':
makeRequest({ action: 'get_connections' });
return next(action);
break;
case 'PUSHER_INSTRUCT':
makeRequest({ action: action.action, data: action.data });
2016-10-27 21:20:05 +13:00
break;
2016-10-27 16:58:11 +13:00
// This action is irrelevant to us, pass it on to the next middleware
default:
return next(action);
}
}
})();
export default PusherMiddleware