Replace WebClient with HttpClient

This commit is contained in:
teinarss
2021-02-21 16:56:55 +01:00
committed by Paul Chote
parent ed43071792
commit 7073279ab8
17 changed files with 604 additions and 562 deletions

View File

@@ -1,96 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System;
using System.ComponentModel;
using System.Net;
namespace OpenRA
{
public class Download
{
readonly object syncObject = new object();
WebClient wc;
public static string FormatErrorMessage(Exception e)
{
var ex = e as WebException;
if (ex == null)
return e.Message;
switch (ex.Status)
{
case WebExceptionStatus.RequestCanceled:
return "Cancelled";
case WebExceptionStatus.NameResolutionFailure:
return "DNS lookup failed";
case WebExceptionStatus.Timeout:
return "Connection timeout";
case WebExceptionStatus.ConnectFailure:
return "Cannot connect to remote server";
case WebExceptionStatus.ProtocolError:
return "File not found on remote server";
default:
return ex.Message;
}
}
void EnableTLS12OnWindows()
{
// Enable TLS 1.2 on Windows: .NET 4.7 on Windows 10 only supports obsolete protocols by default
// SecurityProtocolType.Tls12 is not defined in the .NET 4.5 reference dlls used by mono,
// so we must use the enum's constant value directly
if (Platform.CurrentPlatform == PlatformType.Windows)
ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;
}
public Download(string url, string path, Action<DownloadProgressChangedEventArgs> onProgress, Action<AsyncCompletedEventArgs> onComplete)
{
EnableTLS12OnWindows();
lock (syncObject)
{
wc = new WebClient { Proxy = null };
wc.DownloadProgressChanged += (_, a) => onProgress(a);
wc.DownloadFileCompleted += (_, a) => { DisposeWebClient(); onComplete(a); };
wc.DownloadFileAsync(new Uri(url), path);
}
}
public Download(string url, Action<DownloadProgressChangedEventArgs> onProgress, Action<DownloadDataCompletedEventArgs> onComplete)
{
EnableTLS12OnWindows();
lock (syncObject)
{
wc = new WebClient { Proxy = null };
wc.DownloadProgressChanged += (_, a) => onProgress(a);
wc.DownloadDataCompleted += (_, a) => { DisposeWebClient(); onComplete(a); };
wc.DownloadDataAsync(new Uri(url));
}
}
void DisposeWebClient()
{
lock (syncObject)
{
wc.Dispose();
wc = null;
}
}
public void CancelAsync()
{
lock (syncObject)
wc?.CancelAsync();
}
}
}

View File

@@ -0,0 +1,63 @@
#region Copyright & License Information
/*
* Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace OpenRA
{
public delegate void OnProgress(long total, long totalRead, int progressPercentage);
public static class HttpExtension
{
public static async Task ReadAsStreamWithProgress(this HttpResponseMessage response, Stream outputStream, OnProgress onProgress, CancellationToken token)
{
var total = response.Content.Headers.ContentLength ?? -1;
var canReportProgress = total > 0;
#if !MONO
using (var contentStream = await response.Content.ReadAsStreamAsync(token))
#else
using (var contentStream = await response.Content.ReadAsStreamAsync())
#endif
{
var totalRead = 0L;
var buffer = new byte[8192];
var hasMoreToRead = true;
do
{
var read = await contentStream.ReadAsync(buffer.AsMemory(0, buffer.Length), token);
if (read == 0)
hasMoreToRead = false;
else
{
await outputStream.WriteAsync(buffer.AsMemory(0, read), token);
totalRead += read;
if (canReportProgress)
{
var progressPercentage = (int)((double)totalRead / total * 100);
onProgress?.Invoke(total, totalRead, progressPercentage);
}
}
}
while (hasMoreToRead && !token.IsCancellationRequested);
onProgress?.Invoke(total, totalRead, 100);
}
}
}
}

View File

@@ -12,10 +12,10 @@
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using OpenRA.Support;
namespace OpenRA
{
@@ -76,17 +76,16 @@ namespace OpenRA
if (State != LinkState.Unlinked && State != LinkState.Linked && State != LinkState.ConnectionFailed)
return;
Action<DownloadDataCompletedEventArgs> onQueryComplete = i =>
Task.Run(async () =>
{
try
{
if (i.Error != null)
{
innerState = LinkState.ConnectionFailed;
return;
}
var client = HttpClientFactory.Create();
var yaml = MiniYaml.FromString(Encoding.UTF8.GetString(i.Result)).First();
var httpResponseMessage = await client.GetAsync(playerDatabase.Profile + Fingerprint);
var result = await httpResponseMessage.Content.ReadAsStringAsync();
var yaml = MiniYaml.FromString(result).First();
if (yaml.Key == "Player")
{
innerData = FieldLoader.Load<PlayerProfile>(yaml.Value);
@@ -110,10 +109,9 @@ namespace OpenRA
{
onComplete?.Invoke();
}
};
});
innerState = LinkState.CheckingLink;
new Download(playerDatabase.Profile + Fingerprint, _ => { }, onQueryComplete);
}
public void GenerateKeypair()

View File

@@ -14,9 +14,8 @@ using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenRA.FileSystem;
using OpenRA.Graphics;
using OpenRA.Primitives;
@@ -179,24 +178,16 @@ namespace OpenRA
var url = repositoryUrl + "hash/" + string.Join(",", maps.Keys) + "/yaml";
Action<DownloadDataCompletedEventArgs> onInfoComplete = i =>
Task.Run(async () =>
{
if (i.Error != null)
{
Log.Write("debug", "Remote map query failed with error: {0}", Download.FormatErrorMessage(i.Error));
Log.Write("debug", "URL was: {0}", url);
foreach (var p in maps.Values)
p.UpdateRemoteSearch(MapStatus.Unavailable, null);
queryFailed?.Invoke();
return;
}
var data = Encoding.UTF8.GetString(i.Result);
try
{
var yaml = MiniYaml.FromString(data);
var client = HttpClientFactory.Create();
var httpResponseMessage = await client.GetAsync(url);
var result = await httpResponseMessage.Content.ReadAsStringAsync();
var yaml = MiniYaml.FromString(result);
foreach (var kv in yaml)
maps[kv.Key].UpdateRemoteSearch(MapStatus.DownloadAvailable, kv.Value, mapDetailsReceived);
@@ -206,13 +197,15 @@ namespace OpenRA
}
catch (Exception e)
{
Log.Write("debug", "Can't parse remote map search data:\n{0}", data);
Log.Write("debug", "Exception: {0}", e);
Log.Write("debug", "Remote map query failed with error: {0}", e);
Log.Write("debug", "URL was: {0}", url);
foreach (var p in maps.Values)
p.UpdateRemoteSearch(MapStatus.Unavailable, null);
queryFailed?.Invoke();
}
};
new Download(url, _ => { }, onInfoComplete);
});
}
void LoadAsyncInternal()

View File

@@ -14,13 +14,15 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenRA.FileFormats;
using OpenRA.FileSystem;
using OpenRA.Graphics;
using OpenRA.Primitives;
using OpenRA.Support;
namespace OpenRA
{
@@ -166,7 +168,6 @@ namespace OpenRA
}
}
Download download;
public long DownloadBytes { get; private set; }
public int DownloadPercentage { get; private set; }
@@ -435,43 +436,38 @@ namespace OpenRA
}
var mapInstallPackage = installLocation.Key as IReadWritePackage;
new Thread(() =>
Task.Run(async () =>
{
// Request the filename from the server
// Run in a worker thread to avoid network delays
var mapUrl = mapRepositoryUrl + Uid;
var mapFilename = string.Empty;
try
{
var request = WebRequest.Create(mapUrl);
request.Method = "HEAD";
using (var res = request.GetResponse())
void OnDownloadProgress(long total, long received, int percentage)
{
// Map not found
if (res.Headers["Content-Disposition"] == null)
DownloadBytes = total;
DownloadPercentage = percentage;
}
var client = HttpClientFactory.Create();
var response = await client.GetAsync(mapUrl, HttpCompletionOption.ResponseHeadersRead);
if (!response.IsSuccessStatusCode)
{
innerData.Status = MapStatus.DownloadError;
return;
}
mapFilename = res.Headers["Content-Disposition"].Replace("attachment; filename = ", "");
}
response.Headers.TryGetValues("Content-Disposition", out var values);
var mapFilename = values.First().Replace("attachment; filename = ", "");
Action<DownloadProgressChangedEventArgs> onDownloadProgress = i => { DownloadBytes = i.BytesReceived; DownloadPercentage = i.ProgressPercentage; };
Action<DownloadDataCompletedEventArgs> onDownloadComplete = i =>
{
download = null;
var fileStream = new MemoryStream();
if (i.Error != null)
{
Log.Write("debug", "Remote map download failed with error: {0}", Download.FormatErrorMessage(i.Error));
Log.Write("debug", "URL was: {0}", mapUrl);
await response.ReadAsStreamWithProgress(fileStream, OnDownloadProgress, CancellationToken.None);
innerData.Status = MapStatus.DownloadError;
return;
}
mapInstallPackage.Update(mapFilename, i.Result);
mapInstallPackage.Update(mapFilename, fileStream.ToArray());
Log.Write("debug", "Downloaded map to '{0}'", mapFilename);
Game.RunAfterTick(() =>
{
@@ -484,25 +480,13 @@ namespace OpenRA
onSuccess();
}
});
};
download = new Download(mapUrl, onDownloadProgress, onDownloadComplete);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
innerData.Status = MapStatus.DownloadError;
}
}).Start();
}
public void CancelInstall()
{
if (download == null)
return;
download.CancelAsync();
download = null;
});
}
public void Invalidate()

View File

@@ -41,6 +41,7 @@
<PackageReference Include="SharpZipLib" Version="1.3.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" />
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<AdditionalFiles Include="../stylecop.json" />
</ItemGroup>
<ItemGroup Condition="'$(Mono)' == ''">

View File

@@ -9,13 +9,12 @@
*/
#endregion
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using OpenRA.FileFormats;
using OpenRA.Graphics;
using OpenRA.Primitives;
using OpenRA.Support;
namespace OpenRA
{
@@ -39,14 +38,16 @@ namespace OpenRA
var spriteSize = IconSize * density;
var sprite = sheetBuilder.Allocate(new Size(spriteSize, spriteSize), 1f / density);
Action<DownloadDataCompletedEventArgs> onComplete = i =>
Task.Run(async () =>
{
if (i.Error != null)
return;
try
{
var icon = new Png(new MemoryStream(i.Result));
var client = HttpClientFactory.Create();
var httpResponseMessage = await client.GetAsync(url);
var result = await httpResponseMessage.Content.ReadAsStreamAsync();
var icon = new Png(result);
if (icon.Width == spriteSize && icon.Height == spriteSize)
{
Game.RunAfterTick(() =>
@@ -57,9 +58,7 @@ namespace OpenRA
}
}
catch { }
};
new Download(url, _ => { }, onComplete);
});
return sprite;
}

View File

@@ -18,6 +18,7 @@ using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenRA.FileFormats;
using OpenRA.Network;
using OpenRA.Primitives;
@@ -560,15 +561,16 @@ namespace OpenRA.Server
{
waitingForAuthenticationCallback++;
Action<DownloadDataCompletedEventArgs> onQueryComplete = i =>
Task.Run(async () =>
{
var httpClient = HttpClientFactory.Create();
var httpResponseMessage = await httpClient.GetAsync(playerDatabase.Profile + handshake.Fingerprint);
var result = await httpResponseMessage.Content.ReadAsStringAsync();
PlayerProfile profile = null;
if (i.Error == null)
{
try
{
var yaml = MiniYaml.FromString(Encoding.UTF8.GetString(i.Result)).First();
var yaml = MiniYaml.FromString(result).First();
if (yaml.Key == "Player")
{
profile = FieldLoader.Load<PlayerProfile>(yaml.Value);
@@ -603,10 +605,6 @@ namespace OpenRA.Server
newConn.Socket.RemoteEndPoint, handshake.Fingerprint);
Log.Write("server", ex.ToString());
}
}
else
Log.Write("server", "{0} failed to authenticate as {1} (server error: `{2}`)",
newConn.Socket.RemoteEndPoint, handshake.Fingerprint, i.Error);
delayedActions.Add(() =>
{
@@ -636,9 +634,7 @@ namespace OpenRA.Server
waitingForAuthenticationCallback--;
}, 0);
};
new Download(playerDatabase.Profile + handshake.Fingerprint, _ => { }, onQueryComplete);
});
}
else
{

View File

@@ -0,0 +1,48 @@
#region Copyright & License Information
/*
* Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System;
using System.Net.Http;
namespace OpenRA.Support
{
public class HttpClientFactory
{
#if !MONO
const int MaxConnectionPerServer = 20;
static readonly TimeSpan ConnectionLifeTime = TimeSpan.FromMinutes(1);
#endif
static readonly Lazy<HttpMessageHandler> Handler = new Lazy<HttpMessageHandler>(GetHandler);
public static HttpClient Create()
{
return new HttpClient(Handler.Value, false);
}
static HttpMessageHandler GetHandler()
{
#if !MONO
return new SocketsHttpHandler
{
// https://github.com/dotnet/corefx/issues/26895
// https://github.com/dotnet/corefx/issues/26331
// https://github.com/dotnet/corefx/pull/26839
PooledConnectionLifetime = ConnectionLifeTime,
PooledConnectionIdleTimeout = ConnectionLifeTime,
MaxConnectionsPerServer = MaxConnectionPerServer
};
#else
return new HttpClientHandler();
#endif
}
}
}

View File

@@ -0,0 +1,61 @@
#region Copyright & License Information
/*
* Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace OpenRA.Support
{
public class HttpQueryBuilder : IEnumerable
{
readonly string url;
readonly List<Parameter> parameters = new List<Parameter>();
public HttpQueryBuilder(string url)
{
this.url = url;
}
public void Add(string name, object value)
{
parameters.Add(new Parameter
{
Name = name,
Value = Uri.EscapeUriString(value.ToString())
});
}
public override string ToString()
{
var builder = new StringBuilder(url);
builder.Append("?");
foreach (var parameter in parameters)
builder.Append($"{parameter.Name}={parameter.Value}&");
return builder.ToString();
}
class Parameter
{
public string Name { get; set; }
public string Value { get; set; }
}
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
}

View File

@@ -33,6 +33,7 @@
<PackageReference Include="Pfim" Version="0.9.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" />
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<AdditionalFiles Include="../stylecop.json" />
</ItemGroup>
<Target Name="DisableAnalyzers" BeforeTargets="CoreCompile" Condition="'$(Configuration)'=='Release'">

View File

@@ -11,12 +11,13 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BeaconLib;
using OpenRA.Network;
using OpenRA.Server;
using OpenRA.Support;
using S = OpenRA.Server.Server;
namespace OpenRA.Mods.Common.Server
@@ -41,7 +42,7 @@ namespace OpenRA.Mods.Common.Server
bool isInitialPing = true;
volatile bool isBusy;
Queue<string> masterServerMessages = new Queue<string>();
readonly Queue<string> masterServerMessages = new Queue<string>();
static MasterServerPinger()
{
@@ -108,15 +109,16 @@ namespace OpenRA.Mods.Common.Server
{
isBusy = true;
Task.Run(() =>
Task.Run(async () =>
{
try
{
var endpoint = server.ModData.Manifest.Get<WebServices>().ServerAdvertise;
using (var wc = new WebClient())
{
wc.Proxy = null;
var masterResponseText = wc.UploadString(endpoint, postData);
var client = HttpClientFactory.Create();
var response = await client.PostAsync(endpoint, new StringContent(postData));
var masterResponseText = await response.Content.ReadAsStringAsync();
if (isInitialPing)
{
@@ -124,7 +126,7 @@ namespace OpenRA.Mods.Common.Server
var errorCode = 0;
var errorMessage = string.Empty;
if (masterResponseText.Length > 0)
if (!string.IsNullOrWhiteSpace(masterResponseText))
{
var regex = new Regex(@"^\[(?<code>-?\d+)\](?<message>.*)");
var match = regex.Match(masterResponseText);
@@ -152,7 +154,6 @@ namespace OpenRA.Mods.Common.Server
}
}
}
}
catch (Exception ex)
{
Log.Write("server", ex.ToString());

View File

@@ -10,8 +10,8 @@
#endregion
using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using OpenRA.Support;
namespace OpenRA.Mods.Common
{
@@ -31,16 +31,23 @@ namespace OpenRA.Mods.Common
public void CheckModVersion()
{
Action<DownloadDataCompletedEventArgs> onComplete = i =>
Task.Run(async () =>
{
if (i.Error != null)
return;
try
var queryURL = new HttpQueryBuilder(VersionCheck)
{
var data = Encoding.UTF8.GetString(i.Result);
{ "protocol", VersionCheckProtocol },
{ "engine", Game.EngineVersion },
{ "mod", Game.ModData.Manifest.Id },
{ "version", Game.ModData.Manifest.Metadata.Version }
}.ToString();
var client = HttpClientFactory.Create();
var httpResponseMessage = await client.GetAsync(queryURL);
var result = await httpResponseMessage.Content.ReadAsStringAsync();
var status = ModVersionStatus.Latest;
switch (data)
switch (result)
{
case "outdated": status = ModVersionStatus.Outdated; break;
case "unknown": status = ModVersionStatus.Unknown; break;
@@ -48,17 +55,7 @@ namespace OpenRA.Mods.Common
}
Game.RunAfterTick(() => ModVersionStatus = status);
}
catch { }
};
var queryURL = VersionCheck + "?protocol={0}&engine={1}&mod={2}&version={3}".F(
VersionCheckProtocol,
Uri.EscapeUriString(Game.EngineVersion),
Uri.EscapeUriString(Game.ModData.Manifest.Id),
Uri.EscapeUriString(Game.ModData.Manifest.Metadata.Version));
new Download(queryURL, _ => { }, onComplete);
});
}
}
}

View File

@@ -11,10 +11,10 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using ICSharpCode.SharpZipLib.Zip;
using OpenRA.Support;
using OpenRA.Widgets;
@@ -65,47 +65,35 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var cancelButton = panel.Get<ButtonWidget>("CANCEL_BUTTON");
var file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Action deleteTempFile = () =>
{
Log.Write("install", "Deleting temporary file " + file);
File.Delete(file);
};
Action<DownloadProgressChangedEventArgs> onDownloadProgress = i =>
void OnDownloadProgress(long total, long read, int progressPercentage)
{
var dataReceived = 0.0f;
var dataTotal = 0.0f;
var mag = 0;
var dataSuffix = "";
if (i.TotalBytesToReceive < 0)
if (total < 0)
{
mag = (int)Math.Log(i.BytesReceived, 1024);
dataReceived = i.BytesReceived / (float)(1L << (mag * 10));
mag = (int)Math.Log(read, 1024);
dataReceived = read / (float)(1L << (mag * 10));
dataSuffix = SizeSuffixes[mag];
getStatusText = () => "Downloading from {2} {0:0.00} {1}".F(dataReceived,
dataSuffix,
downloadHost ?? "unknown host");
getStatusText = () => "Downloading from {2} {0:0.00} {1}".F(dataReceived, dataSuffix, downloadHost ?? "unknown host");
progressBar.Indeterminate = true;
}
else
{
mag = (int)Math.Log(i.TotalBytesToReceive, 1024);
dataTotal = i.TotalBytesToReceive / (float)(1L << (mag * 10));
dataReceived = i.BytesReceived / (float)(1L << (mag * 10));
mag = (int)Math.Log(total, 1024);
dataTotal = total / (float)(1L << (mag * 10));
dataReceived = read / (float)(1L << (mag * 10));
dataSuffix = SizeSuffixes[mag];
getStatusText = () => "Downloading from {4} {1:0.00}/{2:0.00} {3} ({0}%)".F(i.ProgressPercentage,
dataReceived, dataTotal, dataSuffix,
downloadHost ?? "unknown host");
getStatusText = () => "Downloading from {4} {1:0.00}/{2:0.00} {3} ({0}%)".F(progressPercentage, dataReceived, dataTotal, dataSuffix, downloadHost ?? "unknown host");
progressBar.Indeterminate = false;
}
progressBar.Percentage = i.ProgressPercentage;
};
progressBar.Percentage = progressPercentage;
}
Action<string> onExtractProgress = s => Game.RunAfterTick(() => getStatusText = () => s);
@@ -120,20 +108,35 @@ namespace OpenRA.Mods.Common.Widgets.Logic
cancelButton.OnClick = Ui.CloseWindow;
});
Action<AsyncCompletedEventArgs> onDownloadComplete = i =>
Action<string> downloadUrl = url =>
{
if (i.Cancelled)
{
deleteTempFile();
Game.RunAfterTick(Ui.CloseWindow);
return;
}
Log.Write("install", "Downloading " + url);
if (i.Error != null)
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
downloadHost = new Uri(url).Host;
cancelButton.OnClick = () =>
{
deleteTempFile();
onError(Download.FormatErrorMessage(i.Error));
return;
tokenSource.Cancel();
Game.RunAfterTick(Ui.CloseWindow);
};
retryButton.OnClick = ShowDownloadDialog;
Task.Run(async () =>
{
var file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
try
{
var client = HttpClientFactory.Create();
var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);
using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.ReadWrite, 8192, true))
{
await response.ReadAsStreamWithProgress(fileStream, OnDownloadProgress, token);
}
// Validate integrity
@@ -162,7 +165,6 @@ namespace OpenRA.Mods.Common.Widgets.Logic
if (!archiveValid)
{
onError("Archive validation failed");
deleteTempFile();
return;
}
}
@@ -197,7 +199,11 @@ namespace OpenRA.Mods.Common.Widgets.Logic
z.Close();
}
Game.RunAfterTick(() => { Ui.CloseWindow(); onSuccess(); });
Game.RunAfterTick(() =>
{
Ui.CloseWindow();
onSuccess();
});
}
catch (Exception e)
{
@@ -211,46 +217,31 @@ namespace OpenRA.Mods.Common.Widgets.Logic
onError("Archive extraction failed");
}
}
catch (Exception e)
{
onError(e.ToString());
}
finally
{
deleteTempFile();
File.Delete(file);
}
};
Action<string> downloadUrl = url =>
{
Log.Write("install", "Downloading " + url);
downloadHost = new Uri(url).Host;
var dl = new Download(url, file, onDownloadProgress, onDownloadComplete);
cancelButton.OnClick = dl.CancelAsync;
retryButton.OnClick = ShowDownloadDialog;
}, token);
};
if (download.MirrorList != null)
{
Log.Write("install", "Fetching mirrors from " + download.MirrorList);
Action<DownloadDataCompletedEventArgs> onFetchMirrorsComplete = i =>
Task.Run(async () =>
{
progressBar.Indeterminate = true;
if (i.Cancelled)
{
Game.RunAfterTick(Ui.CloseWindow);
return;
}
if (i.Error != null)
{
onError(Download.FormatErrorMessage(i.Error));
return;
}
var client = HttpClientFactory.Create();
var httpResponseMessage = await client.GetAsync(download.MirrorList);
var result = await httpResponseMessage.Content.ReadAsStringAsync();
try
{
var data = Encoding.UTF8.GetString(i.Result);
var mirrorList = data.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
var mirrorList = result.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
downloadUrl(mirrorList.Random(new MersenneTwister()));
}
catch (Exception e)
@@ -259,11 +250,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
Log.Write("install", e.ToString());
onError("Online mirror is not available. Please install from an original disc.");
}
};
var updateMirrors = new Download(download.MirrorList, onDownloadProgress, onFetchMirrorsComplete);
cancelButton.OnClick = updateMirrors.CancelAsync;
retryButton.OnClick = ShowDownloadDialog;
});
}
else
downloadUrl(download.URL);

View File

@@ -14,7 +14,9 @@ using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using OpenRA.Network;
using OpenRA.Support;
using OpenRA.Widgets;
namespace OpenRA.Mods.Common.Widgets.Logic
@@ -274,19 +276,47 @@ namespace OpenRA.Mods.Common.Widgets.Logic
{
if (!fetchedNews)
{
Task.Run(async () =>
{
try
{
var client = HttpClientFactory.Create();
// Send the mod and engine version to support version-filtered news (update prompts)
var newsURL = "{0}?version={1}&mod={2}&modversion={3}".F(
webServices.GameNews,
Uri.EscapeUriString(Game.EngineVersion),
Uri.EscapeUriString(Game.ModData.Manifest.Id),
Uri.EscapeUriString(Game.ModData.Manifest.Metadata.Version));
var url = new HttpQueryBuilder(webServices.GameNews)
{
{ "version", Game.EngineVersion },
{ "mod", Game.ModData.Manifest.Id },
{ "modversion", Game.ModData.Manifest.Metadata.Version }
}.ToString();
// Parameter string is blank if the player has opted out
newsURL += SystemInfoPromptLogic.CreateParameterString();
url += SystemInfoPromptLogic.CreateParameterString();
new Download(newsURL, cacheFile, e => { },
e => NewsDownloadComplete(e, cacheFile, currentNews,
() => OpenNewsPanel(newsButton)));
var response = await client.GetStringAsync(url);
await File.WriteAllTextAsync(cacheFile, response);
Game.RunAfterTick(() => // run on the main thread
{
fetchedNews = true;
var newNews = ParseNews(cacheFile);
if (newNews == null)
return;
DisplayNews(newNews);
if (currentNews == null || newNews.Any(n => !currentNews.Select(c => c.DateTime).Contains(n.DateTime)))
OpenNewsPanel(newsButton);
});
}
catch (Exception e)
{
Game.RunAfterTick(() => // run on the main thread
{
SetNewsStatus("Failed to retrieve news: {0}".F(e));
});
}
});
}
newsButton.OnClick = () => OpenNewsPanel(newsButton);
@@ -364,28 +394,6 @@ namespace OpenRA.Mods.Common.Widgets.Logic
return null;
}
void NewsDownloadComplete(AsyncCompletedEventArgs e, string cacheFile, NewsItem[] oldNews, Action onNewsDownloaded)
{
Game.RunAfterTick(() => // run on the main thread
{
if (e.Error != null)
{
SetNewsStatus("Failed to retrieve news: {0}".F(Download.FormatErrorMessage(e.Error)));
return;
}
fetchedNews = true;
var newNews = ParseNews(cacheFile);
if (newNews == null)
return;
DisplayNews(newNews);
if (oldNews == null || newNews.Any(n => !oldNews.Select(c => c.DateTime).Contains(n.DateTime)))
onNewsDownloaded();
});
}
void DisplayNews(IEnumerable<NewsItem> newsItems)
{
newsPanel.RemoveChildren();

View File

@@ -11,10 +11,10 @@
using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using OpenRA.Graphics;
using OpenRA.Network;
using OpenRA.Support;
using OpenRA.Widgets;
namespace OpenRA.Mods.Common.Widgets.Logic
@@ -157,13 +157,16 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var messageText = "Loading player profile...";
var messageWidth = messageFont.Measure(messageText).X + 2 * message.Bounds.Left;
Action<DownloadDataCompletedEventArgs> onQueryComplete = i =>
Task.Run(async () =>
{
try
{
if (i.Error == null)
{
var yaml = MiniYaml.FromString(Encoding.UTF8.GetString(i.Result)).First();
var httpClient = HttpClientFactory.Create();
var httpResponseMessage = await httpClient.GetAsync(playerDatabase.Profile + client.Fingerprint);
var result = await httpResponseMessage.Content.ReadAsStringAsync();
var yaml = MiniYaml.FromString(result).First();
if (yaml.Key == "Player")
{
profile = FieldLoader.Load<PlayerProfile>(yaml.Value);
@@ -231,7 +234,6 @@ namespace OpenRA.Mods.Common.Widgets.Logic
});
}
}
}
catch (Exception e)
{
Log.Write("debug", "Failed to parse player data result with exception: {0}", e);
@@ -245,15 +247,13 @@ namespace OpenRA.Mods.Common.Widgets.Logic
header.Bounds.Width = widget.Bounds.Width = messageWidth;
}
}
};
});
message.GetText = () => messageText;
header.Bounds.Height += messageHeader.Bounds.Height;
header.Bounds.Width = widget.Bounds.Width = messageWidth;
widget.Bounds.Height = header.Bounds.Height;
badgeContainer.Visible = false;
new Download(playerDatabase.Profile + client.Fingerprint, _ => { }, onQueryComplete);
}
}

View File

@@ -12,12 +12,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using BeaconLib;
using OpenRA.Network;
using OpenRA.Primitives;
using OpenRA.Server;
using OpenRA.Support;
using OpenRA.Traits;
using OpenRA.Widgets;
@@ -59,7 +59,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
SearchStatus searchStatus = SearchStatus.Fetching;
Download currentQuery;
bool activeQuery;
IEnumerable<BeaconLocation> lanGameLocations;
public string ProgressLabelText()
@@ -322,23 +322,31 @@ namespace OpenRA.Mods.Common.Widgets.Logic
public void RefreshServerList()
{
// Query in progress
if (currentQuery != null)
if (activeQuery)
return;
searchStatus = SearchStatus.Fetching;
Action<DownloadDataCompletedEventArgs> onComplete = i =>
var queryURL = new HttpQueryBuilder(services.ServerList)
{
currentQuery = null;
{ "protocol", GameServer.ProtocolVersion },
{ "engine", Game.EngineVersion },
{ "mod", Game.ModData.Manifest.Id },
{ "version", Game.ModData.Manifest.Metadata.Version }
}.ToString();
List<GameServer> games = null;
if (i.Error == null)
Task.Run(async () =>
{
games = new List<GameServer>();
var games = new List<GameServer>();
var client = HttpClientFactory.Create();
var httpResponseMessage = await client.GetAsync(queryURL);
var result = await httpResponseMessage.Content.ReadAsStringAsync();
activeQuery = true;
try
{
var data = Encoding.UTF8.GetString(i.Result);
var yaml = MiniYaml.FromString(data);
var yaml = MiniYaml.FromString(result);
foreach (var node in yaml)
{
try
@@ -357,7 +365,6 @@ namespace OpenRA.Mods.Common.Widgets.Logic
{
searchStatus = SearchStatus.Failed;
}
}
var lanGames = new List<GameServer>();
foreach (var bl in lanGameLocations)
@@ -398,15 +405,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic
games = groupedLanGames.ToList();
Game.RunAfterTick(() => RefreshServerListInner(games));
};
var queryURL = services.ServerList + "?protocol={0}&engine={1}&mod={2}&version={3}".F(
GameServer.ProtocolVersion,
Uri.EscapeUriString(Game.EngineVersion),
Uri.EscapeUriString(Game.ModData.Manifest.Id),
Uri.EscapeUriString(Game.ModData.Manifest.Metadata.Version));
currentQuery = new Download(queryURL, _ => { }, onComplete);
activeQuery = false;
});
}
int GroupSortOrder(GameServer testEntry)