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

679 lines
27 KiB
JavaScript
Raw Normal View History

2016-10-27 16:58:11 +13:00
import ReactGA from 'react-ga'
2018-08-20 08:48:46 +12:00
var helpers = require('../../helpers')
var coreActions = require('../core/actions')
var uiActions = require('../ui/actions')
var mopidyActions = require('../mopidy/actions')
var pusherActions = require('./actions')
var lastfmActions = require('../lastfm/actions')
2018-08-21 21:08:11 +12:00
var geniusActions = require('../genius/actions')
2018-08-20 08:48:46 +12:00
var spotifyActions = require('../spotify/actions')
2016-10-27 16:58:11 +13:00
const PusherMiddleware = (function(){
2017-03-27 14:23:38 +13:00
// container for the actual websocket
var socket = null
2017-03-27 14:23:38 +13:00
// requests pending
var deferredRequests = []
2016-10-27 16:58:11 +13:00
// handle all manner of socket messages
const handleMessage = (ws, store, message) => {
2017-02-19 21:27:43 +13:00
2017-10-26 19:26:38 +13:00
if (store.getState().ui.log_pusher){
console.log('Pusher log (incoming)', message);
2017-09-19 16:57:59 +12:00
}
// Pull our ID. JSON-RPC nests the ID under the error object,
// so make sure we handle that.
// TODO: Use this as our measure of a successful response vs error
var id = null;
if (message.id){
id = message.id;
} else if (message.error && message.error.id){
id = message.error.id;
}
2017-10-26 19:26:38 +13:00
// Response with request_id
if (id){
2017-09-19 16:57:59 +12:00
2017-10-26 19:26:38 +13:00
// Response matches a pending request
if (deferredRequests[id] !== undefined){
2017-10-26 19:26:38 +13:00
store.dispatch(uiActions.stopLoading(id));
2017-10-26 19:26:38 +13:00
// Response is an error
2018-03-13 08:57:40 +13:00
if (message.error !== undefined){
deferredRequests[id].reject(message.error);
2017-10-26 19:26:38 +13:00
// Successful response
} else {
deferredRequests[id].resolve(message.result);
2017-10-26 19:26:38 +13:00
}
// Hmm, the response doesn't appear to be for us?
2017-02-18 22:04:05 +13:00
} else {
2017-09-19 16:57:59 +12:00
store.dispatch(coreActions.handleException(
'Pusher: Response received with no matching request',
2017-09-19 16:57:59 +12:00
message
));
2017-02-18 22:04:05 +13:00
}
2016-10-27 16:58:11 +13:00
2017-10-26 19:26:38 +13:00
// General broadcast received
2017-02-18 22:04:05 +13:00
} else {
2017-10-26 19:26:38 +13:00
// Broadcast of an error
2018-03-13 08:57:40 +13:00
if (message.error !== undefined){
2017-10-26 19:26:38 +13:00
store.dispatch(coreActions.handleException(
2018-03-13 08:57:40 +13:00
'Pusher: '+message.error.message,
message,
(message.error.data !== undefined && message.error.data.description !== undefined ? message.error.data.description : null)
2017-10-26 19:26:38 +13:00
));
2018-04-09 21:13:12 +12:00
2017-10-26 19:26:38 +13:00
} else {
switch (message.method){
case 'connection_added':
store.dispatch(pusherActions.connectionAdded(message.params.connection));
break;
case 'connection_changed':
store.dispatch(pusherActions.connectionChanged(message.params.connection));
break;
case 'connection_removed':
store.dispatch(pusherActions.connectionRemoved(message.params.connection));
break;
case 'queue_metadata_changed':
store.dispatch(pusherActions.queueMetadataChanged(message.params.queue_metadata));
break;
case 'spotify_token_changed':
store.dispatch(spotifyActions.tokenChanged(message.params.spotify_token));
break;
case 'share_configuration_received':
2018-07-13 16:48:41 +12:00
store.dispatch(uiActions.createNotification({
type: 'share-configuration-received',
configuration: message.params,
2018-07-13 16:48:41 +12:00
sticky: true
}));
break;
case 'notification':
store.dispatch(uiActions.createNotification(message.params.notification));
break;
case 'radio_started':
store.dispatch(pusherActions.radioStarted(message.params.radio));
break;
case 'radio_changed':
store.dispatch(pusherActions.radioChanged(message.params.radio));
break;
case 'radio_stopped':
store.dispatch(pusherActions.radioStopped());
break;
case 'reload':
2018-04-09 21:13:12 +12:00
window.location.reload(true);
break;
case 'upgrading':
case 'upgrade_started':
store.dispatch(mopidyActions.upgrading());
store.dispatch(uiActions.createNotification({content: 'Upgrading...', type: 'info'}));
break;
case 'restarting':
store.dispatch(mopidyActions.restarting());
store.dispatch(uiActions.createNotification({content: 'Restarting...', type: 'info'}));
break;
}
2017-10-26 19:26:38 +13:00
}
}
2016-10-27 21:20:05 +13:00
}
2018-03-13 08:57:40 +13:00
const request = (store, method, params = null) => {
2017-10-10 13:05:28 +13:00
return new Promise((resolve, reject) => {
var id = helpers.generateGuid();
2017-02-18 22:04:05 +13:00
var message = {
2018-03-13 08:57:40 +13:00
jsonrpc: '2.0',
id: id,
2018-03-13 08:57:40 +13:00
method: method
}
if (params){
message.params = params;
2017-02-18 22:04:05 +13:00
}
if (store.getState().ui.log_pusher){
console.log('Pusher log (outgoing)', message);
}
2017-10-26 19:26:38 +13:00
socket.send(JSON.stringify(message));
2017-03-27 14:23:38 +13:00
store.dispatch(uiActions.startLoading(id, 'pusher_'+method));
// Start our 30 second timeout
var timeout = setTimeout(
function(){
store.dispatch(uiActions.stopLoading(id));
reject({
id: id,
2018-03-13 08:57:40 +13:00
code: 32300,
message: "Request timed out"
});
},
30000
);
// add query to our deferred responses
deferredRequests[id] = {
resolve: resolve,
reject: reject
2017-10-26 19:26:38 +13:00
};
})
}
2016-10-27 16:58:11 +13:00
return store => next => action => {
2017-10-10 13:05:28 +13:00
switch(action.type){
2016-10-27 16:58:11 +13:00
case 'PUSHER_CONNECT':
if (socket != null){
socket.close();
}
2018-03-13 08:57:40 +13:00
store.dispatch({type: 'PUSHER_CONNECTING'});
2016-10-27 16:58:11 +13:00
var state = store.getState();
var connection = {
client_id: helpers.generateGuid(),
2017-02-18 22:04:05 +13:00
connection_id: helpers.generateGuid(),
2017-02-17 21:36:31 +13:00
username: 'Anonymous'
}
if (state.pusher.username){
connection.username = state.pusher.username;
}
connection.username = connection.username.replace(/\W/g, '');
2017-02-16 19:51:49 +13:00
2016-10-27 16:58:11 +13:00
socket = new WebSocket(
2017-03-28 18:23:58 +13:00
'ws'+(window.location.protocol === 'https:' ? 's' : '')+'://'+state.mopidy.host+':'+state.mopidy.port+'/iris/ws/',
[ connection.client_id, connection.connection_id, connection.username ]
2016-10-27 16:58:11 +13:00
);
2018-03-13 08:57:40 +13:00
socket.onopen = () => {
store.dispatch({
type: 'PUSHER_CONNECTED',
connection_id: connection.connection_id,
client_id: connection.client_id,
username: connection.username
2018-03-13 08:57:40 +13:00
});
2016-10-27 16:58:11 +13:00
};
2017-02-21 20:04:45 +13:00
socket.onclose = () => {
store.dispatch({
type: 'PUSHER_DISCONNECTED'
})
2017-10-26 19:26:38 +13:00
// attempt to reconnect every 5 seconds
2017-02-21 20:04:45 +13:00
setTimeout(() => {
store.dispatch(pusherActions.connect())
}, 5000);
};
2018-03-13 08:57:40 +13:00
socket.onmessage = (message) => {
var message = JSON.parse(message.data);
handleMessage(socket, store, message);
};
2016-10-27 16:58:11 +13:00
break;
2016-10-27 21:20:05 +13:00
case 'PUSHER_CONNECTED':
if (store.getState().ui.allow_reporting){
ReactGA.event({ category: 'Pusher', action: 'Connected', label: action.username});
}
2017-02-14 21:41:13 +13:00
store.dispatch(pusherActions.getConfig());
store.dispatch(pusherActions.getRadio());
store.dispatch(pusherActions.getQueueMetadata());
// Give things a few moments to setup before we check for version.
// This is because the server makes a GitHub request, which creates a [very] small delay
// in subsequent requests.
setTimeout(
function(){
store.dispatch(pusherActions.getVersion());
},
2000
);
next(action);
break;
2018-09-24 16:10:42 +12:00
case 'PUSHER_REQUEST':
request(store, action.method, action.params)
.then(
response => {
if (action.response_callback){
store.dispatch(action.response_callback.call(this, response));
}
},
error => {
if (action.error_callback){
store.dispatch(action.error_callback.call(this, error));
} else {
store.dispatch(coreActions.handleException(
2018-09-24 16:10:42 +12:00
'Pusher request failed',
error,
action.method,
action
));
}
}
2017-10-26 19:26:38 +13:00
);
break
case 'PUSHER_DELIVER_MESSAGE':
request(store, 'send_message', action.data)
.then(
response => {
store.dispatch(uiActions.createNotification({type: 'info', content: 'Message delivered'}));
},
error => {
store.dispatch(coreActions.handleException(
'Could not deliver message',
error
));
}
2017-10-26 19:26:38 +13:00
);
break
2017-03-09 08:04:23 +13:00
case 'PUSHER_DELIVER_BROADCAST':
2017-03-27 14:23:38 +13:00
request(store, 'broadcast', action.data)
2017-03-09 08:04:23 +13:00
break
2017-02-14 12:13:07 +13:00
case 'PUSHER_GET_QUEUE_METADATA':
2017-03-27 14:23:38 +13:00
request(store, 'get_queue_metadata')
2017-02-14 12:13:07 +13:00
.then(
response => {
response.type = 'PUSHER_QUEUE_METADATA'
2017-02-18 22:04:05 +13:00
store.dispatch(response)
},
error => {
store.dispatch(coreActions.handleException(
'Could not load queue metadata',
error
));
2017-02-14 12:13:07 +13:00
}
2017-10-26 19:26:38 +13:00
);
2017-02-14 12:13:07 +13:00
break;
case 'PUSHER_ADD_QUEUE_METADATA':
2017-03-27 14:23:38 +13:00
request(store, 'add_queue_metadata', {
2017-02-18 22:04:05 +13:00
tlids: action.tlids,
added_from: action.from_uri,
added_by: store.getState().pusher.username
})
2017-02-14 12:13:07 +13:00
break;
case 'PUSHER_SET_USERNAME':
request(store, 'set_username', {username: action.username})
2017-10-26 19:26:38 +13:00
.then(
response => {
response.type = 'PUSHER_USERNAME_CHANGED'
store.dispatch(response)
},
error => {
store.dispatch(coreActions.handleException(
'Could not set username',
error
));
// Forced change to local state, even if server-end failed
// Useful for changing when not yet connected (ie Initial setup on
// non-standard ports, etc)
if (action.force){
response.type = 'PUSHER_USERNAME_CHANGED'
store.dispatch(response)
}
}
2017-10-26 19:26:38 +13:00
);
2016-10-28 10:48:55 +13:00
return next(action);
break;
case 'PUSHER_GET_VERSION':
request(store, 'get_version')
.then(
response => {
store.dispatch({
type: 'PUSHER_VERSION',
2018-03-13 08:57:40 +13:00
version: response.version
})
},
error => {
store.dispatch(coreActions.handleException(
'Could not load version',
error
));
}
);
break;
case 'PUSHER_GET_CONFIG':
request(store, 'get_config')
.then(
response => {
store.dispatch({
type: 'PUSHER_CONFIG',
2018-03-13 08:57:40 +13:00
config: response.config
});
},
error => {
store.dispatch(coreActions.handleException(
'Could not load config',
error
));
}
);
break;
2017-02-19 21:27:43 +13:00
case 'PUSHER_GET_CONNECTIONS':
2017-03-27 14:23:38 +13:00
request(store, 'get_connections')
2017-10-26 19:26:38 +13:00
.then(
response => {
store.dispatch({
type: 'PUSHER_CONNECTIONS',
2018-03-13 08:57:40 +13:00
connections: response.connections
})
2017-10-26 19:26:38 +13:00
},
error => {
store.dispatch(coreActions.handleException(
'Could not load connections',
error
));
}
2017-10-26 19:26:38 +13:00
);
return next(action);
break;
2018-10-09 21:39:38 +13:00
/**
* Commands
**/
case 'PUSHER_SET_COMMAND':
var commands_index = Object.assign({}, store.getState().pusher.commands);
if (commands_index[action.command.id]){
var command = Object.assign({}, commands_index[action.command.id], action.command);
} else {
var command = action.command;
}
commands_index[action.command.id] = command;
store.dispatch(pusherActions.commandsUpdated(commands_index));
next(action);
break
case 'PUSHER_SEND_COMMAND':
var commands_index = Object.assign({}, pusher.commands);
// Prepare our command
// We try and make it cross-origin compatible
var command = JSON.parse(commands_index[action.id]);
command.crossDomain = true;
command.dataType = "jsonp";
command.success = function(response){
store.dispatch(uiActions.createNotification({type: 'info', content: 'Command sent', description: command.url}));
}
command.fail = function(xhr, status, error){
store.dispatch(uiActions.createNotification({type: 'bad', content: 'Command failed', description: error}));
}
// Actually send the request
$.ajax(command);
break
/**
* Radio
**/
case 'PUSHER_GET_RADIO':
request(store, 'get_radio')
.then(
response => {
store.dispatch({
type: 'PUSHER_RADIO_LOADED',
2018-03-13 08:57:40 +13:00
radio: response.radio
});
},
error => {
store.dispatch(coreActions.handleException(
'Could not load radio',
error
));
}
);
break;
case 'PUSHER_START_RADIO':
2017-04-18 08:52:28 +12:00
case 'PUSHER_UPDATE_RADIO':
if (store.getState().ui.allow_reporting){
ReactGA.event({ category: 'Pusher', action: 'Start radio', label: action.uris.join() });
}
2017-04-18 08:52:28 +12:00
// start our UI process notification
2017-04-18 04:44:39 +12:00
if (action.type == 'PUSHER_UPDATE_RADIO'){
store.dispatch(uiActions.startProcess('PUSHER_RADIO_PROCESS', 'Updating radio'))
2017-04-18 04:44:39 +12:00
} else {
store.dispatch(uiActions.startProcess('PUSHER_RADIO_PROCESS', 'Starting radio'))
2017-04-18 04:44:39 +12:00
}
2016-12-20 16:58:20 +13:00
var data = {
reset: (action.type == 'PUSHER_START_RADIO'),
2016-12-20 16:58:20 +13:00
seed_artists: [],
seed_genres: [],
seed_tracks: []
}
2017-10-10 13:05:28 +13:00
for(var i = 0; i < action.uris.length; i++){
switch(helpers.uriType(action.uris[i] )){
2016-12-20 16:58:20 +13:00
case 'artist':
2017-10-10 13:05:28 +13:00
data.seed_artists.push(action.uris[i] );
2016-12-20 16:58:20 +13:00
break;
case 'track':
2017-10-10 13:05:28 +13:00
data.seed_tracks.push(action.uris[i] );
2016-12-20 16:58:20 +13:00
break;
case 'genre':
2017-10-10 13:05:28 +13:00
data.seed_genres.push(action.uris[i] );
break;
2016-12-20 16:58:20 +13:00
}
}
2017-03-09 08:04:23 +13:00
if (action.type == 'PUSHER_START_RADIO'){
store.dispatch(pusherActions.deliverBroadcast(
'notification',
{
notification: {
type: 'info',
content: store.getState().pusher.username + ' is starting radio mode'
}
}
));
}
2017-04-18 08:52:28 +12:00
request(store, 'change_radio', data)
.then(
response => {
2018-02-28 09:15:34 +13:00
store.dispatch(uiActions.processFinishing('PUSHER_RADIO_PROCESS'));
if (response.status == 0){
store.dispatch(uiActions.createNotification({content: response.message, type: 'bad'}));
}
store.dispatch(pusherActions.radioChanged(response.radio));
},
2017-11-17 08:32:12 +13:00
error => {
store.dispatch(uiActions.processFinishing('PUSHER_RADIO_PROCESS'));
store.dispatch(coreActions.handleException(
'Could not change radio',
error
));
}
)
2016-12-20 16:58:20 +13:00
break
case 'PUSHER_STOP_RADIO':
store.dispatch(uiActions.createNotification({content: 'Stopping radio'}));
if (store.getState().ui.allow_reporting){
ReactGA.event({ category: 'Pusher', action: 'Stop radio' });
}
2017-01-05 13:49:38 +13:00
store.dispatch(pusherActions.deliverBroadcast(
'notification',
{
notification: {
type: 'info',
content: store.getState().pusher.username + ' stopped radio mode'
}
}
));
2016-12-20 19:54:19 +13:00
var data = {
seed_artists: [],
seed_genres: [],
seed_tracks: []
}
2017-03-27 14:23:38 +13:00
request(store, 'stop_radio', data)
.then(
response => {
store.dispatch(pusherActions.radioStopped());
}, error => {
store.dispatch(coreActions.handleException(
'Could not stop radio',
error
));
}
);
break
case 'PUSHER_BROWSER_NOTIFICATION':
store.dispatch(uiActions.createBrowserNotification(action))
2016-12-20 19:54:19 +13:00
break
case 'PUSHER_NOTIFICATION':
var data = Object.assign(
{},
action, {
type: action.notification_type
}
);
store.dispatch(uiActions.createNotification(data));
break
case 'PUSHER_RELOAD':
// Hard reload. This doesn't strictly clear the cache, but our compiler's
// cache buster should handle that
window.location.reload(true);
break
case 'PUSHER_RESTART':
request(store, 'restart')
.then(
response => {
store.dispatch(mopidyActions.restarting());
},
error => {
store.dispatch(uiActions.createNotification({content: error.message, description: (error.description ? error.description : null), type: 'bad'}));
}
);
next(action);
2018-04-16 09:01:42 +12:00
break
case 'PUSHER_UPGRADE':
if (store.getState().ui.allow_reporting){
ReactGA.event({ category: 'Pusher', action: 'Upgrade', label: '' });
}
request(store, 'upgrade')
.then(
response => {
store.dispatch(mopidyActions.upgrading());
},
error => {
store.dispatch(uiActions.createNotification({content: error.message, description: (error.description ? error.description : null), type: 'bad'}));
}
);
break;
case 'PUSHER_VERSION':
if (store.getState().ui.allow_reporting){
ReactGA.event({ category: 'Pusher', action: 'Version', label: action.version.current });
}
next(action);
break
case 'PUSHER_CONFIG':
// Set default country/locale (unless we've already been configured)
var spotify = store.getState().spotify;
var spotify_updated = false;
var spotify_updates = {};
if (!spotify.country && action.config.country){
spotify_updates.country = action.config.country;
spotify_updated = true;
}
if (!spotify.locale && action.config.locale){
spotify_updates.locale = action.config.locale;
spotify_updated = true;
}
if (action.config.spotify_authorization_url){
spotify_updates.authorization_url = action.config.spotify_authorization_url;
spotify_updated = true;
}
if (spotify_updated){
store.dispatch(spotifyActions.set(spotify_updates));
}
2017-11-02 21:20:56 +13:00
store.dispatch(lastfmActions.set({
authorization_url: (action.config.lastfm_authorization_url ? action.config.lastfm_authorization_url : null)
2018-03-26 10:36:13 +13:00
}));
store.dispatch(geniusActions.set({
authorization_url: (action.config.genius_authorization_url ? action.config.genius_authorization_url : null)
}));
2018-03-26 10:36:13 +13:00
next(action);
break
case 'PUSHER_DEBUG':
2017-03-27 14:23:38 +13:00
request(store, action.message.method, action.message.data )
2017-10-26 19:26:38 +13:00
.then(
response => {
store.dispatch({type: 'DEBUG', response: response})
},
error => {
store.dispatch(coreActions.handleException(
'Could not debug',
error,
error.message
));
}
);
break;
case 'PUSHER_ERROR':
store.dispatch(uiActions.createNotification(action.message, 'bad'));
if (store.getState().ui.allow_reporting){
ReactGA.event({ category: 'Pusher', action: 'Error', label: action.message });
}
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