This repository has been archived on 2022-01-02. You can view files and clone it, but cannot push or open issues or pull requests.
AriaNg/app/scripts/services/aria2WebSocketRpcService.js

80 lines
2.2 KiB
JavaScript
Raw Normal View History

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();
var socketClient = null;
2016-05-26 18:29:05 +02:00
var sendIdStates = {};
2016-05-13 18:09:12 +02:00
var getSocketClient = function () {
if (socketClient == null) {
socketClient = $websocket(rpcUrl);
2016-05-13 18:09:12 +02:00
socketClient.onMessage(function (message) {
if (!message || !message.data) {
return;
}
2016-05-13 18:09:12 +02:00
var content = angular.fromJson(message.data);
2016-05-13 18:09:12 +02:00
if (!content || !content.id) {
return;
}
2016-05-13 18:09:12 +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]) {
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;
var callbackMethod = context.callback;
2016-05-26 18:29:05 +02:00
state.deferred.resolve({
success: true,
context: context
});
if (callbackMethod) {
callbackMethod(result);
}
2016-05-26 18:29:05 +02:00
delete sendIdStates[uniqueId];
});
2016-05-13 18:09:12 +02:00
}
return socketClient;
};
2016-05-13 18:09:12 +02:00
return {
request: function (context) {
if (!context) {
return;
}
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
}
};
}]);
})();