2016-05-13 18:09:12 +02:00
|
|
|
(function () {
|
|
|
|
'use strict';
|
|
|
|
|
2016-05-26 18:29:05 +02:00
|
|
|
angular.module('ariaNg').factory('aria2WebSocketRpcService', ['$q', '$websocket', 'ariaNgSettingService', function ($q, $websocket, ariaNgSettingService) {
|
2016-05-16 18:59:27 +02:00
|
|
|
var rpcUrl = ariaNgSettingService.getJsonRpcUrl();
|
2016-05-16 17:41:39 +02:00
|
|
|
var socketClient = null;
|
2016-05-26 18:29:05 +02:00
|
|
|
var sendIdStates = {};
|
2016-05-13 18:09:12 +02:00
|
|
|
|
2016-05-16 17:41:39 +02:00
|
|
|
var getSocketClient = function () {
|
|
|
|
if (socketClient == null) {
|
|
|
|
socketClient = $websocket(rpcUrl);
|
2016-05-13 18:09:12 +02:00
|
|
|
|
2016-05-16 17:41:39 +02:00
|
|
|
socketClient.onMessage(function (message) {
|
|
|
|
if (!message || !message.data) {
|
|
|
|
return;
|
|
|
|
}
|
2016-05-13 18:09:12 +02:00
|
|
|
|
2016-05-16 17:41:39 +02:00
|
|
|
var content = angular.fromJson(message.data);
|
2016-05-13 18:09:12 +02:00
|
|
|
|
2016-05-16 17:41:39 +02:00
|
|
|
if (!content || !content.id) {
|
|
|
|
return;
|
|
|
|
}
|
2016-05-13 18:09:12 +02:00
|
|
|
|
2016-05-16 17:41:39 +02:00
|
|
|
var uniqueId = content.id;
|
|
|
|
var result = content.result;
|
2016-05-13 18:09:12 +02:00
|
|
|
|
2016-05-26 18:29:05 +02:00
|
|
|
if (!sendIdStates[uniqueId]) {
|
2016-05-16 17:41:39 +02:00
|
|
|
return;
|
|
|
|
}
|
2016-05-13 18:09:12 +02:00
|
|
|
|
2016-05-26 18:29:05 +02:00
|
|
|
var state = sendIdStates[uniqueId];
|
|
|
|
|
|
|
|
if (!state) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
var context = state.context;
|
2016-05-16 17:41:39 +02:00
|
|
|
var callbackMethod = context.callback;
|
|
|
|
|
2016-05-26 18:29:05 +02:00
|
|
|
state.deferred.resolve({
|
|
|
|
success: true,
|
|
|
|
context: context
|
|
|
|
});
|
|
|
|
|
2016-05-16 17:41:39 +02:00
|
|
|
if (callbackMethod) {
|
|
|
|
callbackMethod(result);
|
|
|
|
}
|
|
|
|
|
2016-05-26 18:29:05 +02:00
|
|
|
delete sendIdStates[uniqueId];
|
2016-05-16 17:41:39 +02:00
|
|
|
});
|
2016-05-13 18:09:12 +02:00
|
|
|
}
|
|
|
|
|
2016-05-16 17:41:39 +02:00
|
|
|
return socketClient;
|
|
|
|
};
|
2016-05-13 18:09:12 +02:00
|
|
|
|
|
|
|
return {
|
|
|
|
request: function (context) {
|
|
|
|
if (!context) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2016-05-16 17:41:39 +02:00
|
|
|
var client = getSocketClient();
|
2016-05-13 18:09:12 +02:00
|
|
|
var uniqueId = context.uniqueId;
|
|
|
|
var requestBody = angular.toJson(context.requestBody);
|
|
|
|
|
2016-05-26 18:29:05 +02:00
|
|
|
var deferred = $q.defer();
|
|
|
|
|
|
|
|
sendIdStates[uniqueId] = {
|
|
|
|
context: context,
|
|
|
|
deferred: deferred
|
|
|
|
};
|
|
|
|
|
|
|
|
client.send(requestBody);
|
2016-05-13 18:09:12 +02:00
|
|
|
|
2016-05-26 18:29:05 +02:00
|
|
|
return deferred.promise;
|
2016-05-13 18:09:12 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}]);
|
|
|
|
})();
|