refactor code

This commit is contained in:
MaysWind 2016-06-10 19:23:16 +08:00
parent 7b7c322d22
commit 02a248c1a5
17 changed files with 355 additions and 222 deletions

View file

@ -268,8 +268,9 @@
<script src="scripts/config/configuration.js"></script> <script src="scripts/config/configuration.js"></script>
<script src="scripts/config/initiator.js"></script> <script src="scripts/config/initiator.js"></script>
<script src="scripts/config/languages.js"></script> <script src="scripts/config/languages.js"></script>
<script src="scripts/config/language-default.js"></script> <script src="scripts/config/defaultLanguage.js"></script>
<script src="scripts/config/aria2options.js"></script> <script src="scripts/config/aria2Options.js"></script>
<script src="scripts/config/aria2RpcConstants.js"></script>
<script src="scripts/controllers/main.js"></script> <script src="scripts/controllers/main.js"></script>
<script src="scripts/controllers/list.js"></script> <script src="scripts/controllers/list.js"></script>
<script src="scripts/controllers/task-detail.js"></script> <script src="scripts/controllers/task-detail.js"></script>

View file

@ -64,8 +64,10 @@
"Percent": "完成度", "Percent": "完成度",
"Download / Upload Speed": "下载 / 上传速度", "Download / Upload Speed": "下载 / 上传速度",
"No connected peers": "没有连接到其他节点", "No connected peers": "没有连接到其他节点",
"Failed to change some tasks state.": "修改一些任务状态时失败.",
"Confirm Remove": "确认删除", "Confirm Remove": "确认删除",
"Are you sure you want to remove the selected task?": "您是否要删除选中的任务?", "Are you sure you want to remove the selected task?": "您是否要删除选中的任务?",
"Failed to remove some task(s).": "删除一些任务时失败.",
"Confirm Clear": "确认清除", "Confirm Clear": "确认清除",
"Are you sure you want to clear stopped tasks?": "您是否要清除已结束的任务?", "Are you sure you want to clear stopped tasks?": "您是否要清除已结束的任务?",
"Language": "语言", "Language": "语言",
@ -83,9 +85,7 @@
"Confirm Shutdown": "确认关闭", "Confirm Shutdown": "确认关闭",
"Are you sure you want to shutdown aria2?": "您是否要关闭 Aria2?", "Are you sure you want to shutdown aria2?": "您是否要关闭 Aria2?",
"Session has been saved successfully.": "会话已经成功保存.", "Session has been saved successfully.": "会话已经成功保存.",
"Failed to save session.": "会话保存失败.",
"Aria2 has been shutdown successfully.": "Aria2 已经成功关闭.", "Aria2 has been shutdown successfully.": "Aria2 已经成功关闭.",
"Failed to shutdown aria2.": "关闭 Aria2 失败.",
"Toggle Navigation": "切换导航", "Toggle Navigation": "切换导航",
"Loading": "正在加载...", "Loading": "正在加载...",
"More Than One Day": "超过1天", "More Than One Day": "超过1天",

View file

@ -0,0 +1,14 @@
(function () {
'use strict';
angular.module('ariaNg').constant('aria2RpcConstants', {
rpcServiceVersion: '2.0',
rpcServiceName: 'aria2',
rpcSystemServiceName: 'system',
rpcTokenPrefix: 'token:'
}).constant('aria2RpcErrors', {
Unauthorized: {
message: 'Unauthorized'
}
});
})();

View file

@ -14,10 +14,5 @@
secret: '', secret: '',
globalStatRefreshInterval: 1000, globalStatRefreshInterval: 1000,
downloadTaskRefreshInterval: 1000 downloadTaskRefreshInterval: 1000
}).constant('aria2RpcConstants', {
rpcServiceVersion: '2.0',
rpcServiceName: 'aria2',
rpcSystemServiceName: 'system',
rpcTokenPrefix: 'token:'
}); });
})(); })();

View file

@ -68,8 +68,10 @@
'Percent': 'Percent', 'Percent': 'Percent',
'Download / Upload Speed': 'Download / Upload Speed', 'Download / Upload Speed': 'Download / Upload Speed',
'No connected peers': 'No connected peers', 'No connected peers': 'No connected peers',
'Failed to change some tasks state.': 'Failed to change some tasks state.',
'Confirm Remove': 'Confirm Remove', 'Confirm Remove': 'Confirm Remove',
'Are you sure you want to remove the selected task?': 'Are you sure you want to remove the selected task?', 'Are you sure you want to remove the selected task?': 'Are you sure you want to remove the selected task?',
'Failed to remove some task(s).': 'Failed to remove some task(s).',
'Confirm Clear': 'Confirm Clear', 'Confirm Clear': 'Confirm Clear',
'Are you sure you want to clear stopped tasks?': 'Are you sure you want to clear stopped tasks?', 'Are you sure you want to clear stopped tasks?': 'Are you sure you want to clear stopped tasks?',
'Language': 'Language', 'Language': 'Language',
@ -87,9 +89,7 @@
'Confirm Shutdown': 'Confirm Shutdown', 'Confirm Shutdown': 'Confirm Shutdown',
'Are you sure you want to shutdown aria2?': 'Are you sure you want to shutdown aria2?', 'Are you sure you want to shutdown aria2?': 'Are you sure you want to shutdown aria2?',
'Session has been saved successfully.': 'Session has been saved successfully.', 'Session has been saved successfully.': 'Session has been saved successfully.',
'Failed to save session.': 'Failed to save session.',
'Aria2 has been shutdown successfully.': 'Aria2 has been shutdown successfully.', 'Aria2 has been shutdown successfully.': 'Aria2 has been shutdown successfully.',
'Failed to shutdown aria2.': 'Failed to shutdown aria2.',
'Toggle Navigation': 'Toggle Navigation', 'Toggle Navigation': 'Toggle Navigation',
'Loading': 'Loading...', 'Loading': 'Loading...',
'More Than One Day': 'More than 1 day', 'More Than One Day': 'More than 1 day',

View file

@ -1,7 +1,7 @@
(function () { (function () {
'use strict'; 'use strict';
angular.module('ariaNg').controller('DownloadListController', ['$rootScope', '$scope', '$window', '$location', '$route', '$interval', 'dragulaService', 'ariaNgCommonService', 'ariaNgSettingService', 'aria2TaskService', function ($rootScope, $scope, $window, $location, $route, $interval, dragulaService, ariaNgCommonService, ariaNgSettingService, aria2TaskService) { angular.module('ariaNg').controller('DownloadListController', ['$rootScope', '$scope', '$window', '$location', '$route', '$interval', 'dragulaService', 'aria2RpcErrors', 'ariaNgCommonService', 'ariaNgSettingService', 'aria2TaskService', function ($rootScope, $scope, $window, $location, $route, $interval, dragulaService, aria2RpcErrors, ariaNgCommonService, ariaNgSettingService, aria2TaskService) {
var location = $location.path().substring(1); var location = $location.path().substring(1);
var downloadTaskRefreshPromise = null; var downloadTaskRefreshPromise = null;
var pauseDownloadTaskRefresh = false; var pauseDownloadTaskRefresh = false;
@ -12,10 +12,20 @@
return; return;
} }
return aria2TaskService.getTaskList(location, needRequestWholeInfo, function (result) { return aria2TaskService.getTaskList(location, needRequestWholeInfo, function (response) {
if (!ariaNgCommonService.extendArray(result, $rootScope.taskContext.list, 'gid')) { if (!response.success) {
if (response.data.message == aria2RpcErrors.Unauthorized.message) {
$interval.cancel(downloadTaskRefreshPromise);
}
return;
}
var taskList = response.data;
if (!ariaNgCommonService.extendArray(taskList, $rootScope.taskContext.list, 'gid')) {
if (needRequestWholeInfo) { if (needRequestWholeInfo) {
$rootScope.taskContext.list = result; $rootScope.taskContext.list = taskList;
needRequestWholeInfo = false; needRequestWholeInfo = false;
} else { } else {
needRequestWholeInfo = true; needRequestWholeInfo = true;
@ -73,9 +83,9 @@
pauseDownloadTaskRefresh = true; pauseDownloadTaskRefresh = true;
aria2TaskService.changeTaskPosition(gid, index, function (result) { aria2TaskService.changeTaskPosition(gid, index, function () {
pauseDownloadTaskRefresh = false; pauseDownloadTaskRefresh = false;
}); }, true);
}); });
$scope.$on('$destroy', function () { $scope.$on('$destroy', function () {

View file

@ -1,12 +1,19 @@
(function () { (function () {
'use strict'; 'use strict';
angular.module('ariaNg').controller('MainController', ['$rootScope', '$scope', '$route', '$location', '$interval', 'ariaNgCommonService', 'ariaNgSettingService', 'aria2TaskService', 'aria2SettingService', function ($rootScope, $scope, $route, $location, $interval, ariaNgCommonService, ariaNgSettingService, aria2TaskService, aria2SettingService) { angular.module('ariaNg').controller('MainController', ['$rootScope', '$scope', '$route', '$location', '$interval', 'aria2RpcErrors', 'ariaNgCommonService', 'ariaNgSettingService', 'aria2TaskService', 'aria2SettingService', function ($rootScope, $scope, $route, $location, $interval, aria2RpcErrors, ariaNgCommonService, ariaNgSettingService, aria2TaskService, aria2SettingService) {
var globalStatRefreshPromise = null; var globalStatRefreshPromise = null;
var refreshGlobalStat = function (silent) { var refreshGlobalStat = function (silent) {
return aria2SettingService.getGlobalStat(function (result) { return aria2SettingService.getGlobalStat(function (response) {
$scope.globalStat = result; if (!response.success && response.data.message == aria2RpcErrors.Unauthorized.message) {
$interval.cancel(globalStatRefreshPromise);
return;
}
if (response.success) {
$scope.globalStat = response.data;
}
}, silent); }, silent);
}; };
@ -67,10 +74,31 @@
return; return;
} }
$rootScope.loadPromise = invoke(gids, function (result) { $rootScope.loadPromise = invoke(gids, function (response) {
if (response.hasError && gids.length > 1) {
ariaNgCommonService.showError('Failed to change some tasks state.');
}
if (!response.hasSuccess) {
return;
}
refreshGlobalStat(true); refreshGlobalStat(true);
if (!response.hasError && state == 'start') {
if ($location.path() == '/waiting') {
$location.path('/downloading');
} else {
$route.reload(); $route.reload();
}); }
} else if (!response.hasError && state == 'pause') {
if ($location.path() == '/downloading') {
$location.path('/waiting');
} else {
$route.reload();
}
}
}, (gids.length > 1));
}; };
$scope.removeTasks = function () { $scope.removeTasks = function () {
@ -81,21 +109,37 @@
} }
ariaNgCommonService.confirm('Confirm Remove', 'Are you sure you want to remove the selected task?', 'warning', function () { ariaNgCommonService.confirm('Confirm Remove', 'Are you sure you want to remove the selected task?', 'warning', function () {
$rootScope.loadPromise = aria2TaskService.removeTasks(tasks, function (result) { $rootScope.loadPromise = aria2TaskService.removeTasks(tasks, function (response) {
if (response.hasError && tasks.length > 1) {
ariaNgCommonService.showError('Failed to remove some task(s).');
}
if (!response.hasSuccess) {
return;
}
refreshGlobalStat(true); refreshGlobalStat(true);
if (!response.hasError) {
if ($location.path() == '/stopped') { if ($location.path() == '/stopped') {
$route.reload(); $route.reload();
} else { } else {
$location.path('/stopped'); $location.path('/stopped');
} }
}); }
}, (tasks.length > 1));
}); });
}; };
$scope.clearStoppedTasks = function () { $scope.clearStoppedTasks = function () {
ariaNgCommonService.confirm('Confirm Clear', 'Are you sure you want to clear stopped tasks?', 'warning', function () { ariaNgCommonService.confirm('Confirm Clear', 'Are you sure you want to clear stopped tasks?', 'warning', function () {
$rootScope.loadPromise = aria2TaskService.clearStoppedTasks(function (result) { $rootScope.loadPromise = aria2TaskService.clearStoppedTasks(function (response) {
if (!response.success) {
return;
}
refreshGlobalStat(true); refreshGlobalStat(true);
if ($location.path() == '/stopped') { if ($location.path() == '/stopped') {
$route.reload(); $route.reload();
} else { } else {

View file

@ -4,7 +4,7 @@
angular.module('ariaNg').controller('Aria2SettingsController', ['$rootScope', '$scope', '$location', 'ariaNgConstants', 'ariaNgCommonService', 'aria2SettingService', function ($rootScope, $scope, $location, ariaNgConstants, ariaNgCommonService, aria2SettingService) { angular.module('ariaNg').controller('Aria2SettingsController', ['$rootScope', '$scope', '$location', 'ariaNgConstants', 'ariaNgCommonService', 'aria2SettingService', function ($rootScope, $scope, $location, ariaNgConstants, ariaNgCommonService, aria2SettingService) {
var location = $location.path().substring($location.path().lastIndexOf('/') + 1); var location = $location.path().substring($location.path().lastIndexOf('/') + 1);
var getAvailableOptions = function (type) { $scope.availableOptions = (function (type) {
var keys = aria2SettingService.getAvailableGlobalOptionsKeys(type); var keys = aria2SettingService.getAvailableGlobalOptionsKeys(type);
if (!keys) { if (!keys) {
@ -13,23 +13,23 @@
} }
return aria2SettingService.getSpecifiedOptions(keys); return aria2SettingService.getSpecifiedOptions(keys);
}; })(location);
$scope.availableOptions = getAvailableOptions(location);
$scope.setGlobalOption = function (key, value, optionStatus) { $scope.setGlobalOption = function (key, value, optionStatus) {
return aria2SettingService.setGlobalOption(key, value, function (result) { return aria2SettingService.setGlobalOption(key, value, function (response) {
if (result == 'OK') { if (response.success && response.data == 'OK') {
optionStatus.setSuccess(); optionStatus.setSuccess();
} else { } else {
optionStatus.setFailed(); optionStatus.setFailed();
} }
}); }, true);
}; };
$rootScope.loadPromise = (function () { $rootScope.loadPromise = (function () {
return aria2SettingService.getGlobalOption(function (result) { return aria2SettingService.getGlobalOption(function (response) {
$scope.globalOptions = result; if (response.success) {
$scope.globalOptions = response.data;
}
}); });
})(); })();
}]); }]);

View file

@ -2,32 +2,30 @@
'use strict'; 'use strict';
angular.module('ariaNg').controller('Aria2StatusController', ['$rootScope', '$scope', 'ariaNgCommonService', 'aria2SettingService', function ($rootScope, $scope, ariaNgCommonService, aria2SettingService) { angular.module('ariaNg').controller('Aria2StatusController', ['$rootScope', '$scope', 'ariaNgCommonService', 'aria2SettingService', function ($rootScope, $scope, ariaNgCommonService, aria2SettingService) {
$rootScope.loadPromise = (function () {
return aria2SettingService.getAria2Status(function (result) {
$scope.aria2Status = result;
});
})();
$scope.saveSession = function () { $scope.saveSession = function () {
return aria2SettingService.saveSession(function (result) { return aria2SettingService.saveSession(function (response) {
if (result == 'OK') { if (response.success && response.data == 'OK') {
ariaNgCommonService.showOperationSucceeded('Session has been saved successfully.'); ariaNgCommonService.showOperationSucceeded('Session has been saved successfully.');
} else {
ariaNgCommonService.showError('Failed to save session.');
} }
}); });
}; };
$scope.shutdown = function () { $scope.shutdown = function () {
ariaNgCommonService.confirm('Confirm Shutdown', 'Are you sure you want to shutdown aria2?', 'warning', function (status) { ariaNgCommonService.confirm('Confirm Shutdown', 'Are you sure you want to shutdown aria2?', 'warning', function (status) {
return aria2SettingService.shutdown(function (result) { return aria2SettingService.shutdown(function (response) {
if (result == 'OK') { if (response.success && response.data == 'OK') {
ariaNgCommonService.showOperationSucceeded('Aria2 has been shutdown successfully.'); ariaNgCommonService.showOperationSucceeded('Aria2 has been shutdown successfully.');
} else {
ariaNgCommonService.showError('Failed to shutdown aria2.');
} }
}); });
}, true); }, true);
}; };
$rootScope.loadPromise = (function () {
return aria2SettingService.getAria2Status(function (response) {
if (response.success) {
$scope.aria2Status = response.data;
}
});
})();
}]); }]);
})(); })();

View file

@ -1,7 +1,7 @@
(function () { (function () {
'use strict'; 'use strict';
angular.module('ariaNg').controller('TaskDetailController', ['$rootScope', '$scope', '$routeParams', '$interval', 'ariaNgCommonService', 'ariaNgSettingService', 'aria2TaskService', 'aria2SettingService', function ($rootScope, $scope, $routeParams, $interval, ariaNgCommonService, ariaNgSettingService, aria2TaskService, aria2SettingService) { angular.module('ariaNg').controller('TaskDetailController', ['$rootScope', '$scope', '$routeParams', '$interval', 'aria2RpcErrors', 'ariaNgCommonService', 'ariaNgSettingService', 'aria2TaskService', 'aria2SettingService', function ($rootScope, $scope, $routeParams, $interval, aria2RpcErrors, ariaNgCommonService, ariaNgSettingService, aria2TaskService, aria2SettingService) {
var tabOrders = ['overview', 'blocks', 'filelist', 'btpeers']; var tabOrders = ['overview', 'blocks', 'filelist', 'btpeers'];
var downloadTaskRefreshPromise = null; var downloadTaskRefreshPromise = null;
var pauseDownloadTaskRefresh = false; var pauseDownloadTaskRefresh = false;
@ -21,9 +21,15 @@
}; };
var refreshBtPeers = function (task, silent) { var refreshBtPeers = function (task, silent) {
return aria2TaskService.getBtTaskPeers(task.gid, function (result) { return aria2TaskService.getBtTaskPeers(task.gid, function (response) {
if (!ariaNgCommonService.extendArray(result, $scope.peers, 'peerId')) { if (!response.success) {
$scope.peers = result; return;
}
var peers = response.data;
if (!ariaNgCommonService.extendArray(peers, $scope.peers, 'peerId')) {
$scope.peers = peers;
} }
$scope.healthPercent = aria2TaskService.estimateHealthPercentFromPeers(task, $scope.peers); $scope.healthPercent = aria2TaskService.estimateHealthPercentFromPeers(task, $scope.peers);
@ -35,20 +41,32 @@
return; return;
} }
return aria2TaskService.getTaskStatus($routeParams.gid, function (result) { return aria2TaskService.getTaskStatus($routeParams.gid, function (response) {
if (result.status == 'active' && result.bittorrent) { if (!response.success) {
refreshBtPeers(result, true); if (response.data.message == aria2RpcErrors.Unauthorized.message) {
$interval.cancel(downloadTaskRefreshPromise);
}
return;
}
var task = response.data;
if (task.status == 'active' && task.bittorrent) {
if ($scope.context.currentTab == 'btpeers') {
refreshBtPeers(task, true);
}
} else { } else {
if (tabOrders.indexOf('btpeers') >= 0) { if (tabOrders.indexOf('btpeers') >= 0) {
tabOrders.splice(tabOrders.indexOf('btpeers'), 1); tabOrders.splice(tabOrders.indexOf('btpeers'), 1);
} }
} }
if (!$scope.task || $scope.task.status != result.status) { if (!$scope.task || $scope.task.status != task.status) {
$scope.availableOptions = getAvailableOptions(result.status, !!result.bittorrent); $scope.availableOptions = getAvailableOptions(task.status, !!task.bittorrent);
} }
$scope.task = ariaNgCommonService.copyObjectTo(result, $scope.task); $scope.task = ariaNgCommonService.copyObjectTo(task, $scope.task);
$rootScope.taskContext.list = [$scope.task]; $rootScope.taskContext.list = [$scope.task];
$rootScope.taskContext.selected = {}; $rootScope.taskContext.selected = {};
@ -125,26 +143,35 @@
pauseDownloadTaskRefresh = true; pauseDownloadTaskRefresh = true;
return aria2TaskService.selectTaskFile(gid, selectedFileIndex, function () { return aria2TaskService.selectTaskFile(gid, selectedFileIndex, function (response) {
pauseDownloadTaskRefresh = false; pauseDownloadTaskRefresh = false;
if (response.success) {
refreshDownloadTask(false); refreshDownloadTask(false);
}); }
}, true);
};
$scope.loadBtPeers = function (task) {
$rootScope.loadPromise = refreshBtPeers(task, false);
}; };
$scope.loadTaskOption = function (task) { $scope.loadTaskOption = function (task) {
$rootScope.loadPromise = aria2TaskService.getTaskOptions(task.gid, function (result) { $rootScope.loadPromise = aria2TaskService.getTaskOptions(task.gid, function (response) {
$scope.options = result; if (response.success) {
$scope.options = response.data;
}
}); });
}; };
$scope.setOption = function (key, value, optionStatus) { $scope.setOption = function (key, value, optionStatus) {
return aria2TaskService.setTaskOption($scope.task.gid, key, value, function (result) { return aria2TaskService.setTaskOption($scope.task.gid, key, value, function (response) {
if (result == 'OK') { if (response.success && response.data == 'OK') {
optionStatus.setSuccess(); optionStatus.setSuccess();
} else { } else {
optionStatus.setFailed(); optionStatus.setFailed();
} }
}); }, true);
}; };
if (ariaNgSettingService.getDownloadTaskRefreshInterval() > 0) { if (ariaNgSettingService.getDownloadTaskRefreshInterval() > 0) {

View file

@ -21,8 +21,8 @@
return; return;
} }
if (context.callback) { if (context.successCallback) {
context.callback(data.result); context.successCallback(data.id, data.result);
} }
}).error(function (data, header, config, status) { }).error(function (data, header, config, status) {
if (!data) { if (!data) {
@ -30,11 +30,7 @@
} }
if (context.errorCallback) { if (context.errorCallback) {
context.errorCallback(data.error); context.errorCallback(data.id, data.error);
}
if (context.callback) {
context.callback(data.error);
} }
}); });
} }

View file

@ -1,7 +1,7 @@
(function () { (function () {
'use strict'; 'use strict';
angular.module('ariaNg').factory('aria2RpcService', ['$q', 'aria2RpcConstants', 'ariaNgCommonService', 'ariaNgSettingService', 'aria2HttpRpcService', 'aria2WebSocketRpcService', function ($q, aria2RpcConstants, ariaNgCommonService, ariaNgSettingService, aria2HttpRpcService, aria2WebSocketRpcService) { angular.module('ariaNg').factory('aria2RpcService', ['$q', 'aria2RpcConstants', 'aria2RpcErrors', 'ariaNgCommonService', 'ariaNgSettingService', 'aria2HttpRpcService', 'aria2WebSocketRpcService', function ($q, aria2RpcConstants, aria2RpcErrors, ariaNgCommonService, ariaNgSettingService, aria2HttpRpcService, aria2WebSocketRpcService) {
var protocol = ariaNgSettingService.getProtocol(); var protocol = ariaNgSettingService.getProtocol();
var secret = ariaNgSettingService.getSecret(); var secret = ariaNgSettingService.getSecret();
@ -13,58 +13,43 @@
return aria2RpcConstants.rpcServiceName + '.' + methodName; return aria2RpcConstants.rpcServiceName + '.' + methodName;
}; };
var invoke = function (method, context) { var invoke = function (context) {
var isSystemMethod = checkIsSystemMethod(method); var uniqueId = ariaNgCommonService.generateUniqueId();
var finalParams = [];
if (secret && !isSystemMethod) { var requestBody = {
finalParams.push(aria2RpcConstants.rpcTokenPrefix + secret);
}
if (angular.isArray(context.params) && context.params.length > 0) {
for (var i = 0; i < context.params.length; i++) {
finalParams.push(context.params[i]);
}
}
context.uniqueId = ariaNgCommonService.generateUniqueId();
context.requestBody = {
jsonrpc: aria2RpcConstants.rpcServiceVersion, jsonrpc: aria2RpcConstants.rpcServiceVersion,
method: (!isSystemMethod ? getAria2MethodFullName(method) : method), method: context.methodName,
id: context.uniqueId id: uniqueId,
params: context.params
}; };
if (finalParams.length > 0) { var requestContext = {
context.requestBody.params = finalParams; uniqueId: uniqueId,
} requestBody: requestBody,
successCallback: context.successCallback,
if (!context.silent) { errorCallback: context.errorCallback
context.errorCallback = function (error) { };
if (!error || !error.message) {
return;
}
if (error.message == 'Unauthorized') {
ariaNgCommonService.showError('rpc.error.' + error.message);
return;
}
}
}
if (protocol == 'ws' || protocol == 'wss') { if (protocol == 'ws' || protocol == 'wss') {
return aria2WebSocketRpcService.request(context); return aria2WebSocketRpcService.request(requestContext);
} else { } else {
return aria2HttpRpcService.request(context); return aria2HttpRpcService.request(requestContext);
} }
}; };
var invokeMulti = function (methodFunc, contexts, keyProperty, callback) { var invokeMulti = function (methodFunc, contexts, callback) {
var promises = []; var promises = [];
var hasSuccess = false;
var hasError = false;
var results = []; var results = [];
for (var i = 0; i < contexts.length; i++) { for (var i = 0; i < contexts.length; i++) {
contexts[i].callback = function (result) { contexts[i].callback = function (response) {
results.push(result); results.push(response);
hasSuccess = hasSuccess | response.success;
hasError = hasError | !response.success;
}; };
promises.push(methodFunc(contexts[i])); promises.push(methodFunc(contexts[i]));
@ -72,33 +57,83 @@
return $q.all(promises).finally(function () { return $q.all(promises).finally(function () {
if (callback) { if (callback) {
callback(results); callback({
hasSuccess: !!hasSuccess,
hasError: !!hasError,
results: results
});
} }
}); });
}; };
var processError = function (error) {
if (!error || !error.message) {
return false;
}
if (error.message == aria2RpcErrors.Unauthorized.message) {
ariaNgCommonService.showError('rpc.error.' + error.message);
return true;
} else {
ariaNgCommonService.showError(error.message);
return true;
}
};
var buildRequestContext = function () { var buildRequestContext = function () {
var context = {}; var methodName = arguments[0];
var isSystemMethod = checkIsSystemMethod(methodName);
var finalParams = [];
if (arguments.length > 0) { var context = {
var invokeContext = arguments[0]; methodName: (!isSystemMethod ? getAria2MethodFullName(methodName) : methodName)
};
context.silent = invokeContext.silent === true; if (secret && !isSystemMethod) {
context.callback = invokeContext.callback; finalParams.push(aria2RpcConstants.rpcTokenPrefix + secret);
} }
if (arguments.length > 1) { if (arguments.length > 1) {
var params = []; var invokeContext = arguments[1];
for (var i = 1; i < arguments.length; i++) { context.successCallback = function (id, result) {
if (invokeContext.callback) {
invokeContext.callback({
id: id,
success: true,
data: result
});
}
};
context.errorCallback = function (id, error) {
var errorProcessed = false;
if (!invokeContext.silent) {
errorProcessed = processError(error);
}
if (invokeContext.callback) {
invokeContext.callback({
id: id,
success: false,
data: error,
errorProcessed: errorProcessed
});
}
};
}
if (arguments.length > 2) {
for (var i = 2; i < arguments.length; i++) {
if (arguments[i] != null && !angular.isUndefined(arguments[i])) { if (arguments[i] != null && !angular.isUndefined(arguments[i])) {
params.push(arguments[i]); finalParams.push(arguments[i]);
}
} }
} }
if (params.length > 0) { if (finalParams.length > 0) {
context.params = params; context.params = finalParams;
}
} }
return context; return context;
@ -136,167 +171,158 @@
// return invoke('addMetalink', context); // return invoke('addMetalink', context);
// }, // },
remove: function (context) { remove: function (context) {
return invoke('remove', buildRequestContext(context, context.gid)); return invoke(buildRequestContext('remove', context, context.gid));
}, },
forceRemove: function (context) { forceRemove: function (context) {
return invoke('forceRemove', buildRequestContext(context, context.gid)); return invoke(buildRequestContext('forceRemove', context, context.gid));
}, },
forceRemoveMulti: function (context) { forceRemoveMulti: function (context) {
var contexts = []; var contexts = [];
for (var i = 0; i < context.gids.length; i++) { for (var i = 0; i < context.gids.length; i++) {
contexts.push({ contexts.push({
silent: !!context.silent,
gid: context.gids[i] gid: context.gids[i]
}); });
} }
return invokeMulti(this.forceRemove, contexts, 'gid', context.callback); return invokeMulti(this.forceRemove, contexts, context.callback);
}, },
pause: function (context) { pause: function (context) {
return invoke('pause', buildRequestContext(context, context.gid)); return invoke(buildRequestContext('pause', context, context.gid));
}, },
pauseAll: function (context) { pauseAll: function (context) {
return invoke('pauseAll', buildRequestContext(context)); return invoke(buildRequestContext('pauseAll', context));
}, },
forcePause: function (context) { forcePause: function (context) {
return invoke('forcePause', buildRequestContext(context, context.gid)); return invoke(buildRequestContext('forcePause', context, context.gid));
}, },
forcePauseMulti: function (context) { forcePauseMulti: function (context) {
var contexts = []; var contexts = [];
for (var i = 0; i < context.gids.length; i++) { for (var i = 0; i < context.gids.length; i++) {
contexts.push({ contexts.push({
silent: !!context.silent,
gid: context.gids[i] gid: context.gids[i]
}); });
} }
return invokeMulti(this.forcePause, contexts, 'gid', context.callback); return invokeMulti(this.forcePause, contexts, context.callback);
}, },
forcePauseAll: function (context) { forcePauseAll: function (context) {
return invoke('forcePauseAll', buildRequestContext(context)); return invoke(buildRequestContext('forcePauseAll', context));
}, },
unpause: function (context) { unpause: function (context) {
return invoke('unpause', buildRequestContext(context, context.gid)); return invoke(buildRequestContext('unpause', context, context.gid));
}, },
unpauseMulti: function (context) { unpauseMulti: function (context) {
var contexts = []; var contexts = [];
for (var i = 0; i < context.gids.length; i++) { for (var i = 0; i < context.gids.length; i++) {
contexts.push({ contexts.push({
silent: !!context.silent,
gid: context.gids[i] gid: context.gids[i]
}); });
} }
return invokeMulti(this.unpause, contexts, 'gid', context.callback); return invokeMulti(this.unpause, contexts, context.callback);
}, },
unpauseAll: function (context) { unpauseAll: function (context) {
return invoke('unpauseAll', buildRequestContext(context)); return invoke(buildRequestContext('unpauseAll', context));
}, },
tellStatus: function (context) { tellStatus: function (context) {
return invoke('tellStatus', buildRequestContext(context, context.gid)); return invoke(buildRequestContext('tellStatus', context, context.gid));
}, },
getUris: function (context) { getUris: function (context) {
return invoke('getUris', buildRequestContext(context, context.gid)); return invoke(buildRequestContext('getUris', context, context.gid));
}, },
getFiles: function (context) { getFiles: function (context) {
return invoke('getFiles', buildRequestContext(context, context.gid)); return invoke(buildRequestContext('getFiles', context, context.gid));
}, },
getPeers: function (context) { getPeers: function (context) {
return invoke('getPeers', buildRequestContext(context, context.gid)); return invoke(buildRequestContext('getPeers', context, context.gid));
}, },
getServers: function (context) { getServers: function (context) {
return invoke('getServers', buildRequestContext(context, context.gid)); return invoke(buildRequestContext('getServers', context, context.gid));
}, },
tellActive: function (context) { tellActive: function (context) {
return invoke('tellActive', buildRequestContext(context, return invoke(buildRequestContext('tellActive', context,
angular.isUndefined(context.requestParams) ? null : context.requestParams angular.isUndefined(context.requestParams) ? null : context.requestParams
)); ));
}, },
tellWaiting: function (context) { tellWaiting: function (context) {
return invoke('tellWaiting', buildRequestContext(context, return invoke(buildRequestContext('tellWaiting', context,
angular.isUndefined(context.offset) ? 0 : context.offset, angular.isUndefined(context.offset) ? 0 : context.offset,
angular.isUndefined(context.num) ? 1000 : context.num, angular.isUndefined(context.num) ? 1000 : context.num,
angular.isUndefined(context.requestParams) ? null : context.requestParams angular.isUndefined(context.requestParams) ? null : context.requestParams
)); ));
}, },
tellStopped: function (context) { tellStopped: function (context) {
return invoke('tellStopped', buildRequestContext(context, return invoke(buildRequestContext('tellStopped', context,
angular.isUndefined(context.offset) ? 0 : context.offset, angular.isUndefined(context.offset) ? 0 : context.offset,
angular.isUndefined(context.num) ? 1000 : context.num, angular.isUndefined(context.num) ? 1000 : context.num,
angular.isUndefined(context.requestParams) ? null : context.requestParams angular.isUndefined(context.requestParams) ? null : context.requestParams
)); ));
}, },
changePosition: function (context) { changePosition: function (context) {
return invoke('changePosition', buildRequestContext(context, context.gid, context.pos, context.how)); return invoke(buildRequestContext('changePosition', context, context.gid, context.pos, context.how));
}, },
// changeUri: function (context) { // changeUri: function (context) {
// return invoke('changeUri', context); // return invoke('changeUri', context);
// }, // },
getOption: function (context) { getOption: function (context) {
return invoke('getOption', buildRequestContext(context, context.gid)); return invoke(buildRequestContext('getOption', context, context.gid));
}, },
changeOption: function (context) { changeOption: function (context) {
return invoke('changeOption', buildRequestContext(context, context.gid, context.options)); return invoke(buildRequestContext('changeOption', context, context.gid, context.options));
}, },
getGlobalOption: function (context) { getGlobalOption: function (context) {
return invoke('getGlobalOption', buildRequestContext(context)); return invoke(buildRequestContext('getGlobalOption', context));
}, },
changeGlobalOption: function (context) { changeGlobalOption: function (context) {
return invoke('changeGlobalOption', buildRequestContext(context, context.options)); return invoke(buildRequestContext('changeGlobalOption', context, context.options));
}, },
getGlobalStat: function (context) { getGlobalStat: function (context) {
return invoke('getGlobalStat', buildRequestContext(context)); return invoke(buildRequestContext('getGlobalStat', context));
}, },
purgeDownloadResult: function (context) { purgeDownloadResult: function (context) {
return invoke('purgeDownloadResult', buildRequestContext(context)); return invoke(buildRequestContext('purgeDownloadResult', context));
}, },
removeDownloadResult: function (context) { removeDownloadResult: function (context) {
return invoke('removeDownloadResult', buildRequestContext(context, context.gid)); return invoke(buildRequestContext('removeDownloadResult', context, context.gid));
}, },
removeDownloadResultMulti: function (context) { removeDownloadResultMulti: function (context) {
var contexts = []; var contexts = [];
for (var i = 0; i < context.gids.length; i++) { for (var i = 0; i < context.gids.length; i++) {
contexts.push({ contexts.push({
silent: !!context.silent,
gid: context.gids[i] gid: context.gids[i]
}); });
} }
return invokeMulti(this.removeDownloadResult, contexts, 'gid', context.callback); return invokeMulti(this.removeDownloadResult, contexts, context.callback);
}, },
getVersion: function (context) { getVersion: function (context) {
return invoke('getVersion', buildRequestContext(context)); return invoke(buildRequestContext('getVersion', context));
}, },
getSessionInfo: function (context) { getSessionInfo: function (context) {
return invoke('getSessionInfo', buildRequestContext(context)); return invoke(buildRequestContext('getSessionInfo', context));
}, },
shutdown: function (context) { shutdown: function (context) {
return invoke('shutdown', buildRequestContext(context)); return invoke(buildRequestContext('shutdown', context));
}, },
forceShutdown: function (context) { forceShutdown: function (context) {
return invoke('forceShutdown', buildRequestContext(context)); return invoke(buildRequestContext('forceShutdown', context));
}, },
saveSession: function (context) { saveSession: function (context) {
return invoke('saveSession', buildRequestContext(context)); return invoke(buildRequestContext('saveSession', context));
}, },
multicall: function (context) { multicall: function (context) {
var requestContext = { return invoke(buildRequestContext('system.multicall', context, context.methods));
params: [],
silent: context.silent === true,
callback: context.callback
};
if (angular.isArray(context.methods) && context.methods.length > 0) {
for (var i = 0; i < context.methods.length; i++) {
var method = context.methods[i];
requestContext.params.push([method]);
}
}
return invoke('system.multicall', requestContext);
}, },
listMethods: function (context) { listMethods: function (context) {
return invoke('system.listMethods', buildRequestContext(context)); return invoke(buildRequestContext('system.listMethods', context));
} }
}; };
}]); }]);

View file

@ -106,22 +106,25 @@
return options; return options;
}, },
getGlobalOption: function (callback) { getGlobalOption: function (callback, silent) {
return aria2RpcService.getGlobalOption({ return aria2RpcService.getGlobalOption({
silent: !!silent,
callback: callback callback: callback
}); });
}, },
setGlobalOption: function (key, value, callback) { setGlobalOption: function (key, value, callback, silent) {
var data = {}; var data = {};
data[key] = value; data[key] = value;
return aria2RpcService.changeGlobalOption({ return aria2RpcService.changeGlobalOption({
options: data, options: data,
silent: !!silent,
callback: callback callback: callback
}); });
}, },
getAria2Status: function (callback) { getAria2Status: function (callback, silent) {
return aria2RpcService.getVersion({ return aria2RpcService.getVersion({
silent: !!silent,
callback: callback callback: callback
}) })
}, },
@ -138,13 +141,15 @@
} }
}); });
}, },
saveSession: function (callback) { saveSession: function (callback, silent) {
return aria2RpcService.saveSession({ return aria2RpcService.saveSession({
silent: !!silent,
callback: callback callback: callback
}) })
}, },
shutdown: function (callback) { shutdown: function (callback, silent) {
return aria2RpcService.shutdown({ return aria2RpcService.shutdown({
silent: !!silent,
callback: callback callback: callback
}) })
} }

View file

@ -1,7 +1,7 @@
(function () { (function () {
'use strict'; 'use strict';
angular.module('ariaNg').factory('aria2TaskService', ['$q', '$translate', 'aria2RpcService', function ($q, $translate, aria2RpcService) { angular.module('ariaNg').factory('aria2TaskService', ['$q', '$translate', 'aria2RpcService', 'ariaNgCommonService', function ($q, $translate, aria2RpcService, ariaNgCommonService) {
var getFileNameFromPath = function (path) { var getFileNameFromPath = function (path) {
if (!path) { if (!path) {
return path; return path;
@ -114,12 +114,12 @@
return invokeMethod({ return invokeMethod({
requestParams: full ? aria2RpcService.getFullTaskParams() : aria2RpcService.getBasicTaskParams(), requestParams: full ? aria2RpcService.getFullTaskParams() : aria2RpcService.getBasicTaskParams(),
silent: !!silent, silent: !!silent,
callback: function (result) { callback: function (response) {
if (!callback) { if (!callback) {
return; return;
} }
callback(result); callback(response);
} }
}); });
}, },
@ -127,33 +127,38 @@
return aria2RpcService.tellStatus({ return aria2RpcService.tellStatus({
gid: gid, gid: gid,
silent: !!silent, silent: !!silent,
callback: function (result) { callback: function (response) {
if (!callback) { if (!callback) {
return; return;
} }
var task = processDownloadTask(result); if (response.success) {
callback(task); processDownloadTask(response.data);
}
callback(response);
} }
}); });
}, },
getTaskOptions: function (gid, callback) { getTaskOptions: function (gid, callback, silent) {
return aria2RpcService.getOption({ return aria2RpcService.getOption({
gid: gid, gid: gid,
silent: !!silent,
callback: callback callback: callback
}); });
}, },
setTaskOption: function (gid, key, value, callback) { setTaskOption: function (gid, key, value, callback, silent) {
var data = {}; var data = {};
data[key] = value; data[key] = value;
return aria2RpcService.changeOption({ return aria2RpcService.changeOption({
gid: gid, gid: gid,
options: data, options: data,
silent: !!silent,
callback: callback callback: callback
}); });
}, },
selectTaskFile: function (gid, selectedFileIndexArr, callback) { selectTaskFile: function (gid, selectedFileIndexArr, callback, silent) {
var selectedFileIndex = ''; var selectedFileIndex = '';
for (var i = 0; i < selectedFileIndexArr.length; i++) { for (var i = 0; i < selectedFileIndexArr.length; i++) {
@ -164,41 +169,45 @@
selectedFileIndex += selectedFileIndexArr[i]; selectedFileIndex += selectedFileIndexArr[i];
} }
return this.setTaskOption(gid, 'select-file', selectedFileIndex, callback); return this.setTaskOption(gid, 'select-file', selectedFileIndex, callback, silent);
}, },
getBtTaskPeers: function (gid, callback, silent) { getBtTaskPeers: function (gid, callback, silent) {
return aria2RpcService.getPeers({ return aria2RpcService.getPeers({
gid: gid, gid: gid,
silent: !!silent, silent: !!silent,
callback: function (result) { callback: function (response) {
if (!callback) { if (!callback) {
return; return;
} }
if (result) { if (response.success) {
for (var i = 0; i < result.length; i++) { var peers = response.data;
var peer = result[i];
for (var i = 0; i < peers.length; i++) {
var peer = peers[i];
peer.completePercent = estimateCompletedPercentFromBitField(peer.bitfield) * 100; peer.completePercent = estimateCompletedPercentFromBitField(peer.bitfield) * 100;
} }
} }
callback(result); callback(response);
} }
}); });
}, },
startTasks: function (gids, callback) { startTasks: function (gids, callback, silent) {
return aria2RpcService.unpauseMulti({ return aria2RpcService.unpauseMulti({
gids: gids, gids: gids,
silent: !!silent,
callback: callback callback: callback
}); });
}, },
pauseTasks: function (gids, callback) { pauseTasks: function (gids, callback, silent) {
return aria2RpcService.forcePauseMulti({ return aria2RpcService.forcePauseMulti({
gids: gids, gids: gids,
silent: !!silent,
callback: callback callback: callback
}); });
}, },
removeTasks: function (tasks, callback) { removeTasks: function (tasks, callback, silent) {
var runningTaskGids = []; var runningTaskGids = [];
var stoppedTaskGids = []; var stoppedTaskGids = [];
@ -211,16 +220,19 @@
} }
var promises = []; var promises = [];
var results = {
runningResult: null, var hasSuccess = false;
stoppedResult: null var hasError = false;
}; var results = [];
if (runningTaskGids.length > 0) { if (runningTaskGids.length > 0) {
promises.push(aria2RpcService.forceRemoveMulti({ promises.push(aria2RpcService.forceRemoveMulti({
gids: runningTaskGids, gids: runningTaskGids,
callback: function (result) { silent: !!silent,
results.runningResult = result; callback: function (response) {
ariaNgCommonService.pushArrayTo(results, response.results);
hasSuccess = hasSuccess | response.hasSuccess;
hasError = hasError | response.hasError;
} }
})); }));
} }
@ -228,28 +240,37 @@
if (stoppedTaskGids.length > 0) { if (stoppedTaskGids.length > 0) {
promises.push(aria2RpcService.removeDownloadResultMulti({ promises.push(aria2RpcService.removeDownloadResultMulti({
gids: stoppedTaskGids, gids: stoppedTaskGids,
callback: function (result) { silent: !!silent,
results.stoppedResult = result; callback: function (response) {
ariaNgCommonService.pushArrayTo(results, response.results);
hasSuccess = hasSuccess | response.hasSuccess;
hasError = hasError | response.hasError;
} }
})); }));
} }
return $q.all(promises).then(function () { return $q.all(promises).then(function () {
if (callback) { if (callback) {
callback(results); callback({
hasSuccess: !!hasSuccess,
hasError: !!hasError,
results: results
});
} }
}); });
}, },
changeTaskPosition: function (gid, position, callback) { changeTaskPosition: function (gid, position, callback, silent) {
return aria2RpcService.changePosition({ return aria2RpcService.changePosition({
gid: gid, gid: gid,
pos: position, pos: position,
how: 'POS_SET', how: 'POS_SET',
silent: !!silent,
callback: callback callback: callback
}) })
}, },
clearStoppedTasks: function (callback) { clearStoppedTasks: function (callback, silent) {
return aria2RpcService.purgeDownloadResult({ return aria2RpcService.purgeDownloadResult({
silent: !!silent,
callback: callback callback: callback
}); });
}, },

View file

@ -40,16 +40,12 @@
context: context context: context
}); });
if (content.error && context.errorCallback) { if (content.result && context.successCallback) {
context.errorCallback(content.error); context.successCallback(context.id, content.result);
} }
if (context.callback) { if (content.error && context.errorCallback) {
if (content.result) { context.errorCallback(context.id, content.error);
context.callback(content.result);
} else if (content.error) {
context.callback(content.error);
}
} }
delete sendIdStates[uniqueId]; delete sendIdStates[uniqueId];

View file

@ -11,7 +11,7 @@
<a class="pointer-cursor" ng-click="context.currentTab = 'filelist'" translate>Files</a> <a class="pointer-cursor" ng-click="context.currentTab = 'filelist'" translate>Files</a>
</li> </li>
<li ng-class="{'active': context.currentTab == 'btpeers'}" ng-if="task && task.status == 'active' && task.bittorrent"> <li ng-class="{'active': context.currentTab == 'btpeers'}" ng-if="task && task.status == 'active' && task.bittorrent">
<a class="pointer-cursor" ng-click="context.currentTab = 'btpeers'" translate>Peers</a> <a class="pointer-cursor" ng-click="context.currentTab = 'btpeers';loadBtPeers(task);" translate>Peers</a>
</li> </li>
<li ng-class="{'active': context.currentTab == 'settings'}" ng-if="task && (task.status == 'active' || task.status == 'waiting' || task.status == 'paused')" class="slim"> <li ng-class="{'active': context.currentTab == 'settings'}" ng-if="task && (task.status == 'active' || task.status == 'waiting' || task.status == 'paused')" class="slim">
<a class="pointer-cursor" ng-click="context.currentTab = 'settings';loadTaskOption(task);"> <a class="pointer-cursor" ng-click="context.currentTab = 'settings';loadTaskOption(task);">