public async Task AddServer([NotNull] string address, IProgress<string> progress = null, CancellationToken cancellation = default(CancellationToken)) {
if (address == null) throw new ArgumentNullException(nameof(address));
// assume address is something like [HOSTNAME]:[HTTP PORT]
string ip;
int port;
if (!KunosApiProvider.ParseAddress(address, out ip, out port)) {
throw new Exception(ToolsStrings.Online_CannotParseAddress);
}
if (port > 0) {
progress?.Report(ToolsStrings.Online_GettingInformationDirectly);
var information = await KunosApiProvider.TryToGetInformationDirectAsync(ip, port);
if (cancellation.IsCancellationRequested) return;
// assume address is [HOSTNAME]:[TCP PORT]
if (information == null) {
progress?.Report(ToolsStrings.Online_TryingToFindOutHttpPort);
var pair = await KunosApiProvider.TryToPingServerAsync(ip, port, SettingsHolder.Online.PingTimeout);
if (cancellation.IsCancellationRequested) return;
if (pair != null) {
progress?.Report(ToolsStrings.Online_GettingInformationDirectly_SecondAttempt);
information = await KunosApiProvider.TryToGetInformationDirectAsync(ip, pair.Item1);
if (cancellation.IsCancellationRequested) return;
}
}
if (information == null) {
throw new Exception(ToolsStrings.Online_CannotAccessServer);
}
AddToSavedList(information.Ip, information.PortC);
CreateAndAddEntry(information);
} else {
// assume address is [HOSTNAME]
progress?.Report(ToolsStrings.Common_Scanning);
var scanned = 0;
var found = 0;
var total = SettingsHolder.Online.PortsEnumeration.ToPortsDiapason().Count();
await SettingsHolder.Online.PortsEnumeration.ToPortsDiapason().Select(async p => {
var pair = await KunosApiProvider.TryToPingServerAsync(ip, p, SettingsHolder.Online.ScanPingTimeout);
if (pair != null && pair.Item1 > 1024 && pair.Item1 < 65536) {
if (cancellation.IsCancellationRequested) return;
var information = await KunosApiProvider.TryToGetInformationDirectAsync(ip, pair.Item1);
if (cancellation.IsCancellationRequested) return;
if (information != null) {
AddToSavedList(ip, pair.Item1);
found++;
try {
CreateAndAddEntry(information);
} catch (Exception e) {
if (e.Message != ToolsStrings.Common_IdIsTaken) {
Logging.Warning("Scan add error: " + e);
}
}
}
}
scanned++;
if (progress == null) return;
progress.Report(string.Format(ToolsStrings.Online_ScanningProgress, scanned, total,
PluralizingConverter.PluralizeExt(found, ToolsStrings.Online_ScanningProgress_Found)));
}).WhenAll(200, cancellation);
if (found == 0) {
throw new InformativeException(ToolsStrings.Online_ScanningNothingFound, ToolsStrings.Online_ScanningNothingFound_Commentary);
}
}
}