Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
peters committed Apr 25, 2023
2 parents a195a1c + 1badbd0 commit c54d61f
Show file tree
Hide file tree
Showing 12 changed files with 62 additions and 110 deletions.
2 changes: 1 addition & 1 deletion GitVersion.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
next-version: 5.2.0
next-version: 5.2.2
mode: ContinuousDeployment
continuous-delivery-fallback-tag: ''
branches:
Expand Down
2 changes: 0 additions & 2 deletions snapx-dev.cmd

This file was deleted.

3 changes: 0 additions & 3 deletions snapx-dev.sh

This file was deleted.

4 changes: 2 additions & 2 deletions src/Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<AvaloniaVersion>11.0.0-preview6</AvaloniaVersion>
<AvaloniaVersion>11.0.0-preview7</AvaloniaVersion>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
Expand All @@ -16,7 +16,7 @@
<PackageVersion Include="LightInject" Version="6.6.3" />
<PackageVersion Include="MessagePack" Version="2.5.108" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageVersion Include="Mono.Cecil" Version="0.11.4" />
<PackageVersion Include="Mono.Cecil" Version="0.11.5" />
<PackageVersion Include="Moq" Version="4.18.4" />
<PackageVersion Include="NLog" Version="5.1.3" />
<PackageVersion Include="NuGet.Packaging.Core" Version="6.5.0" />
Expand Down
4 changes: 2 additions & 2 deletions src/Snap.Installer/ViewModels/AvaloniaMainWindowViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,15 @@ public AvaloniaMainWindowViewModel([NotNull] ISnapInstallerEmbeddedResources sna

public Task SetStatusTextAsync(string text)
{
return Dispatcher.UIThread.InvokeAsync(() => StatusText = text);
return Dispatcher.UIThread.InvokeAsync(() => StatusText = text).GetTask();
}

public Task SetErrorAsync()
{
return Dispatcher.UIThread.InvokeAsync(() =>
{
StatusTextBrush = (IImmutableBrush)Brush.Parse("#B80F0A");
});
}).GetTask();
}

public void OnInitialized()
Expand Down
34 changes: 4 additions & 30 deletions src/Snap.Installer/Windows/CustomChromeWindow.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;
using System.Runtime.InteropServices;
using Avalonia.Controls;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;

Expand All @@ -10,39 +8,15 @@ internal class CustomChromeWindow : Window
{
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
var thisHandle = PlatformImpl.Handle.Handle;

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
NativeMethodsWindows.FocusThisWindow(thisHandle);
}

Focus();
base.OnApplyTemplate(e);
}

protected override void OnPointerPressed(PointerPressedEventArgs e)
{
BeginMoveDrag(e);

base.OnPointerPressed(e);
}

protected override void HandleWindowStateChanged(WindowState state)
{
WindowState = WindowState.Normal;
}

protected static class NativeMethodsWindows
{
[DllImport("user32", SetLastError = true, EntryPoint = "SetActiveWindow")]
static extern IntPtr SetActiveWindow(IntPtr hWnd);
[DllImport("user32", SetLastError = true, EntryPoint = "SetForegroundWindow")]
static extern bool SetForegroundWindow(IntPtr hWnd);

public static void FocusThisWindow(IntPtr hWnd)
{
SetActiveWindow(hWnd);
SetForegroundWindow(hWnd);
}
}
}
protected override void HandleWindowStateChanged(WindowState state) => WindowState = WindowState.Normal;
}
41 changes: 23 additions & 18 deletions src/Snap.Tests/Core/SnapUpdateManagerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Moq;
using Newtonsoft.Json;
using NuGet.Configuration;
using NuGet.Versioning;
using Snap.AnyOS;
Expand All @@ -24,7 +26,7 @@

namespace Snap.Tests.Core;

public class SnapUpdateManagerTests : IClassFixture<BaseFixture>, IClassFixture<BaseFixturePackaging>, IClassFixture<BaseFixtureNuget>
public sealed class SnapUpdateManagerTests : IClassFixture<BaseFixture>, IClassFixture<BaseFixturePackaging>, IClassFixture<BaseFixtureNuget>
{
readonly BaseFixture _baseFixture;
readonly BaseFixturePackaging _baseFixturePackaging;
Expand Down Expand Up @@ -80,26 +82,29 @@ public async Task TestGetSnapReleasesAsync_SnapHttpFeed(bool versionIsNull)

const string applicationId = "my-application-id";

_snapHttpClientMock.Setup(x => x.GetStreamAsync(It.IsAny<Uri>(), It.IsAny<Dictionary<string, string>>())).ReturnsAsync(() =>
_snapHttpClientMock.Setup(x => x.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<CancellationToken>())).ReturnsAsync(() =>
{
var jsonStr = JsonConvert.SerializeObject(snapPackageManagerHttpFeed);
var jsonStr = JsonSerializer.Serialize(snapPackageManagerHttpFeed);
var jsonBytes = Encoding.UTF8.GetBytes(jsonStr);
return new MemoryStream(jsonBytes);
}).Callback((Uri uri, IDictionary<string, string> headers) =>
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(new MemoryStream(jsonBytes))
};
}).Callback((HttpRequestMessage httpRequestMessage, CancellationToken _) =>
{
Assert.Equal(uri, snapPackageManagerHttpFeed.Source);
Assert.NotNull(headers);
Assert.Equal(4, headers.Count);
Assert.Collection(headers, pair => Assert.Equal("X-Snapx-App-Id", snapApp.Id));
Assert.Collection(headers, pair => Assert.Equal("X-Snapx-Channel", snapChannel.Name));
Assert.Collection(headers, pair => Assert.Equal("X-Snapx-Application-Id", applicationId));
Assert.Equal(snapPackageManagerHttpFeed.Source, httpRequestMessage.RequestUri);
Assert.NotNull(httpRequestMessage.Headers);
Assert.Equal(4, httpRequestMessage.Headers.Count());
Assert.Collection(httpRequestMessage.Headers, _ => Assert.Equal("X-Snapx-App-Id", snapApp.Id));
Assert.Collection(httpRequestMessage.Headers, _ => Assert.Equal("X-Snapx-Channel", snapChannel.Name));
Assert.Collection(httpRequestMessage.Headers, _ => Assert.Equal("X-Snapx-Application-Id", applicationId));
if (versionIsNull)
{
Assert.Collection(headers, pair => Assert.Null("X-Snapx-Application-Version"));
Assert.Collection(httpRequestMessage.Headers, _ => Assert.Null("X-Snapx-Application-Version"));
}
else
{
Assert.Collection(headers, pair => Assert.Equal("X-Snapx-Application-Version", snapApp.Version.ToNormalizedString()));
Assert.Collection(httpRequestMessage.Headers, _ => Assert.Equal("X-Snapx-Application-Version", snapApp.Version.ToNormalizedString()));
}
});

Expand All @@ -110,9 +115,9 @@ public async Task TestGetSnapReleasesAsync_SnapHttpFeed(bool versionIsNull)
Assert.Null(snapReleases);

_snapHttpClientMock.Verify(x =>
x.GetStreamAsync(
It.Is<Uri>(v => v == snapChannel.UpdateFeed.Source),
It.Is<Dictionary<string, string>>(v => v.Count == 4)), Times.Once);
x.SendAsync(
It.Is<HttpRequestMessage>(v => v.RequestUri == snapChannel.UpdateFeed.Source && v.Headers.Count() == 4),
It.IsAny<CancellationToken>()), Times.Once);
}

[InlineData("1.0.0")]
Expand Down Expand Up @@ -279,4 +284,4 @@ static void SetupUpdateManagerProgressSource(Mock<ISnapUpdateManagerProgressSour
It.IsAny<int>(), It.IsAny<long>(), It.IsAny<long>()));
progressSourceMock.Setup(x => x.RaiseTotalProgress(It.IsAny<int>()));
}
}
}
25 changes: 4 additions & 21 deletions src/Snap/Core/SnapHttpClient.cs
Original file line number Diff line number Diff line change
@@ -1,40 +1,23 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;

namespace Snap.Core;

public interface ISnapHttpClient
{
Task<Stream> GetStreamAsync(Uri requestUri, IDictionary<string, string> headers = null);
Task<HttpResponseMessage> SendAsync(HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken);
}

public sealed class SnapHttpClient : ISnapHttpClient
{
readonly HttpClient _httpClient;

public SnapHttpClient(HttpClient httpClient)
{
_httpClient = httpClient;
}

public async Task<Stream> GetStreamAsync(Uri requestUri, IDictionary<string, string> headers = null)
{
var httpResponseMessage = await _httpClient.GetAsync(requestUri);
if (headers != null)
{
foreach (var pair in headers)
{
httpResponseMessage.Headers.Add(pair.Key, pair.Value);
}
}
return await httpResponseMessage.Content.ReadAsStreamAsync();
}

public SnapHttpClient([NotNull] HttpClient httpClient) =>
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));

public Task<HttpResponseMessage> SendAsync(HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken) =>
_httpClient.SendAsync(httpRequestMessage, cancellationToken);
}
51 changes: 23 additions & 28 deletions src/Snap/Core/SnapPackageManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
Expand Down Expand Up @@ -73,7 +72,8 @@ public enum SnapPackageManagerRestoreType

internal interface ISnapPackageManager
{
Task<PackageSource> GetPackageSourceAsync(SnapApp snapApp, ILog logger = null, string applicationId = null);
Task<PackageSource> GetPackageSourceAsync(SnapApp snapApp, ILog logger = null, string applicationId = null,
CancellationToken cancellationToken = default);

Task<(SnapAppsReleases snapAppsReleases, PackageSource packageSource, MemoryStream releasesMemoryStream, bool nupkgNotFound)> GetSnapsReleasesAsync(
[NotNull] SnapApp snapApp, ILog logger = null, CancellationToken cancellationToken = default, string applicationId = null);
Expand All @@ -86,12 +86,6 @@ Task<SnapPackageManagerRestoreSummary> RestoreAsync([NotNull] string packagesDir
int checksumConcurrency = 1, int downloadConcurrency = 2, int restoreConcurrency = 1);
}

[JsonSerializable(typeof(SnapPackageManagerNugetHttpFeed))]
internal partial class SnapPackageManagerNugetHttpFeedContext : JsonSerializerContext
{

}

internal sealed class SnapPackageManagerNugetHttpFeed
{
[JsonInclude]
Expand Down Expand Up @@ -175,12 +169,11 @@ public SnapPackageManager([NotNull] ISnapFilesystem filesystem,
_snapFilesystem = snapFilesystem ?? throw new ArgumentNullException(nameof(snapFilesystem));
}

public async Task<PackageSource> GetPackageSourceAsync(
[NotNull] SnapApp snapApp,
ILog logger = null,
string applicationId = null)
public async Task<PackageSource> GetPackageSourceAsync([NotNull] SnapApp snapApp,
ILog logger = null,
string applicationId = null, CancellationToken cancellationToken = default)
{
if (snapApp == null) throw new ArgumentNullException(nameof(snapApp));
ArgumentNullException.ThrowIfNull(snapApp);

try
{
Expand All @@ -190,27 +183,29 @@ public async Task<PackageSource> GetPackageSourceAsync(
{
case SnapHttpFeed feed:
{
var headers = new Dictionary<string, string>
using var httpResponseMessage = await _snapHttpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, feed.Source)
{
{ "X-Snapx-App-Id", snapApp.Id},
{ "X-Snapx-Channel", channel.Name },
{ "X-Snapx-Application-Id", applicationId },
{ "X-Snapx-Application-Version", snapApp.Version?.ToNormalizedString() }
};

await using var stream = await _snapHttpClient.GetStreamAsync(feed.Source, headers);
stream.Seek(0, SeekOrigin.Begin);
Headers =
{
{ "X-Snapx-App-Id", snapApp.Id},
{ "X-Snapx-Channel", channel.Name },
{ "X-Snapx-Application-Id", applicationId },
{ "X-Snapx-Application-Version", snapApp.Version?.ToNormalizedString() }
}
}, cancellationToken);

await using var jsonStream = await stream.ReadToEndAsync();
httpResponseMessage.EnsureSuccessStatusCode();

await using var stream = await httpResponseMessage.Content.ReadAsStreamAsync(cancellationToken);

var packageManagerNugetHttp = await JsonSerializer.DeserializeAsync(jsonStream, new SnapPackageManagerNugetHttpFeedContext(new JsonSerializerOptions
var packageManagerNugetHttp = await JsonSerializer.DeserializeAsync<SnapPackageManagerNugetHttpFeed>(stream, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
}).SnapPackageManagerNugetHttpFeed);
}, cancellationToken: cancellationToken);

if (packageManagerNugetHttp == null)
{
throw new Exception($"Unable to deserialize nuget http feed. Url: {feed.Source}. Response length: {stream.Position}");
throw new Exception($"Unable to deserialize nuget http feed. Url: {feed.Source}.");
}

if (packageManagerNugetHttp.Source == null)
Expand Down Expand Up @@ -247,13 +242,13 @@ public async Task<PackageSource> GetPackageSourceAsync(
public async Task<(SnapAppsReleases snapAppsReleases, PackageSource packageSource, MemoryStream releasesMemoryStream, bool nupkgNotFound)> GetSnapsReleasesAsync(
SnapApp snapApp, ILog logger = null, CancellationToken cancellationToken = default, string applicationId = null)
{
if (snapApp == null) throw new ArgumentNullException(nameof(snapApp));
ArgumentNullException.ThrowIfNull(snapApp);

var packageId = snapApp.BuildNugetReleasesUpstreamId();

try
{
var packageSource = await GetPackageSourceAsync(snapApp, logger, applicationId);
var packageSource = await GetPackageSourceAsync(snapApp, logger, applicationId, cancellationToken);

var snapReleasesDownloadResult =
await _nugetService.DownloadLatestAsync(packageId, packageSource, false, true, cancellationToken);
Expand Down
2 changes: 1 addition & 1 deletion src/Snap/Core/SnapUpdateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ async Task<SnapApp> UpdateToLatestReleaseAsyncImpl(ISnapUpdateManagerProgressSou
var sw = new Stopwatch();
sw.Restart();

var packageSource = await _snapPackageManager.GetPackageSourceAsync(_snapApp, _logger, ApplicationId);
var packageSource = await _snapPackageManager.GetPackageSourceAsync(_snapApp, _logger, ApplicationId, cancellationToken);
if (packageSource == null)
{
_logger.Error("Unknown error resolving update feed.");
Expand Down
2 changes: 1 addition & 1 deletion src/Snapx/Program.CommandList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ static async Task<int> CommandListAsync([NotNull] ListOptions options, [NotNull]
continue;
}

var packageSource = await packageManager.GetPackageSourceAsync(snapApp, logger);
var packageSource = await packageManager.GetPackageSourceAsync(snapApp, logger, cancellationToken: cancellationToken);
snapAppsesPackageSources.Add((snapApp, snapApp.BuildNugetUpstreamId(), packageSource));

var table = tables.SingleOrDefault(x => x.snapApp.Id == snapApp.Id);
Expand Down
2 changes: 1 addition & 1 deletion src/Snapx/Program.CommandPack.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ static async Task<int> CommandPackAsync([NotNull] PackOptions packOptions, [NotN

logger.Info('-'.Repeat(TerminalBufferWidth));

var updateFeedPackageSource = await snapPackageManager.GetPackageSourceAsync(snapApp);
var updateFeedPackageSource = await snapPackageManager.GetPackageSourceAsync(snapApp, cancellationToken: cancellationToken);

logger.Info("Downloading releases nupkg.");

Expand Down

0 comments on commit c54d61f

Please sign in to comment.