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

86 lines
2.4 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;
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;
2016-05-26 18:29:05 +02:00
state.deferred.resolve({
success: true,
context: context
});
2016-06-04 11:08:42 +02:00
if (content.error && context.errorCallback) {
context.errorCallback(content.error);
}
if (context.callback) {
if (content.result) {
2016-06-04 11:08:42 +02:00
context.callback(content.result);
} else if (content.error) {
2016-06-04 11:08:42 +02:00
context.callback(content.error);
}
}
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
}
};
}]);
})();