2016-05-13 18:09:12 +02:00
|
|
|
(function () {
|
|
|
|
'use strict';
|
|
|
|
|
|
|
|
angular.module('ariaNg').factory('aria2WebSocketRpcService', ['$websocket', 'ariaNgSettingService', function ($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-13 18:09:12 +02:00
|
|
|
var sendIdMapping = {};
|
|
|
|
|
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-16 17:41:39 +02:00
|
|
|
if (!sendIdMapping[uniqueId]) {
|
|
|
|
return;
|
|
|
|
}
|
2016-05-13 18:09:12 +02:00
|
|
|
|
2016-05-16 17:41:39 +02:00
|
|
|
var context = sendIdMapping[uniqueId];
|
|
|
|
var callbackMethod = context.callback;
|
|
|
|
|
|
|
|
if (callbackMethod) {
|
|
|
|
callbackMethod(result);
|
|
|
|
}
|
|
|
|
|
|
|
|
delete sendIdMapping[uniqueId];
|
|
|
|
});
|
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);
|
|
|
|
|
|
|
|
sendIdMapping[uniqueId] = context;
|
|
|
|
|
2016-05-16 17:41:39 +02:00
|
|
|
return client.send(requestBody);
|
2016-05-13 18:09:12 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}]);
|
|
|
|
})();
|