Skip to content

Commit

Permalink
fix(Update): Rework the way update are check to trigger a check when …
Browse files Browse the repository at this point in the history
…the setting is changed.

Fixes #641
  • Loading branch information
Belphemur committed May 15, 2021
1 parent 8823e7a commit dfd2f55
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 80 deletions.
58 changes: 0 additions & 58 deletions SoundSwitch/Framework/Updater/IntervalUpdateChecker.cs

This file was deleted.

34 changes: 34 additions & 0 deletions SoundSwitch/Framework/Updater/Job/CheckForUpdateOnceJob.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Job.Scheduler.Job;
using Job.Scheduler.Job.Action;
using Job.Scheduler.Job.Exception;
using Serilog;

namespace SoundSwitch.Framework.Updater.Job
{
public class CheckForUpdateOnceJob : IJob
{
private readonly UpdateChecker _updateChecker;

public CheckForUpdateOnceJob(UpdateChecker updateChecker)
{
_updateChecker = updateChecker;
}

public Task ExecuteAsync(CancellationToken cancellationToken)
{
return _updateChecker.CheckForUpdate(cancellationToken);
}

public Task OnFailure(JobException exception)
{
Log.Warning(exception, "Couldn't check for update");
return Task.CompletedTask;
}

public IRetryAction FailRule { get; } = new RetryNTimes(3, TimeSpan.FromMinutes(1));
public TimeSpan? MaxRuntime { get; }
}
}
41 changes: 41 additions & 0 deletions SoundSwitch/Framework/Updater/Job/CheckForUpdateRecurringJob.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Job.Scheduler.Job;
using Job.Scheduler.Job.Action;
using Job.Scheduler.Job.Exception;
using Serilog;
using SoundSwitch.Framework.Configuration;

namespace SoundSwitch.Framework.Updater.Job
{
public class CheckForUpdateRecurringJob : IRecurringJob
{
private readonly UpdateChecker _updateChecker;

public CheckForUpdateRecurringJob(UpdateChecker updateChecker)
{
_updateChecker = updateChecker;
}

public Task ExecuteAsync(CancellationToken cancellationToken)
{
if (AppConfigs.Configuration.UpdateMode == UpdateMode.Never)
{
return Task.CompletedTask;
}

return _updateChecker.CheckForUpdate(cancellationToken);
}

public Task OnFailure(JobException exception)
{
Log.Warning(exception, "Couldn't check for update");
return Task.CompletedTask;
}

public IRetryAction FailRule { get; } = new AlwaysRetry(TimeSpan.FromMinutes(30));
public TimeSpan? MaxRuntime { get; }
public TimeSpan Delay { get; } = TimeSpan.FromSeconds(AppConfigs.Configuration.UpdateCheckInterval);
}
}
18 changes: 12 additions & 6 deletions SoundSwitch/Framework/Updater/UpdateChecker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sentry;
using Serilog;
Expand Down Expand Up @@ -46,7 +48,6 @@ public UpdateChecker(Uri releaseUrl, bool checkBeta)

private bool ProcessRelease(GitHubRelease serverRelease)
{

Log.Information("Checking version {version} ", serverRelease);
if (serverRelease.prerelease && !Beta)
{
Expand All @@ -64,6 +65,7 @@ private bool ProcessRelease(GitHubRelease serverRelease)
{
return false;
}

var changelog = Regex.Split(serverRelease.body, "\r\n|\r|\n");
var release = new Release(version, installer, serverRelease.name);
release.Changelog.AddRange(changelog);
Expand All @@ -75,23 +77,27 @@ private bool ProcessRelease(GitHubRelease serverRelease)
{
Log.Error(ex, "Exception while getting release");
}
return false;

return false;
}

/// <summary>
/// Check for update
/// </summary>
public void CheckForUpdate()
public async Task CheckForUpdate(CancellationToken token)
{
using var httpClient = new HttpClient(new SentryHttpMessageHandler());
var releases = httpClient.GetFromJsonAsync<GitHubRelease[]>(_releaseUrl).GetAwaiter().GetResult();
foreach (var _ in (releases ?? Array.Empty<GitHubRelease>()).SkipWhile(release => !ProcessRelease(release))) ;
var releases = await httpClient.GetFromJsonAsync<GitHubRelease[]>(_releaseUrl, token);
foreach (var release in releases ?? Array.Empty<GitHubRelease>())
{
token.ThrowIfCancellationRequested();
ProcessRelease(release);
}
}

public class NewReleaseEvent : EventArgs
{
public Release Release { get;}
public Release Release { get; }

public NewReleaseEvent(Release release)
{
Expand Down
47 changes: 31 additions & 16 deletions SoundSwitch/Model/AppModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Job.Scheduler.Builder;
using Job.Scheduler.Scheduler;
using NAudio.CoreAudioApi;
using RailSharp;
using Serilog;
Expand All @@ -30,6 +33,7 @@
using SoundSwitch.Framework.Profile;
using SoundSwitch.Framework.Profile.Trigger;
using SoundSwitch.Framework.Updater;
using SoundSwitch.Framework.Updater.Job;
using SoundSwitch.Framework.WinApi;
using SoundSwitch.Framework.WinApi.Keyboard;
using SoundSwitch.Localization;
Expand All @@ -43,8 +47,9 @@ public class AppModel : IAppModel
{
private bool _initialized;
private readonly NotificationManager _notificationManager;
private IntervalUpdateChecker _updateChecker;
private readonly DebounceDispatcher _dispatcher = new DebounceDispatcher();
private UpdateChecker _updateChecker;
private readonly DebounceDispatcher _dispatcher = new();
private readonly IJobScheduler _jobScheduler = new JobScheduler(new JobRunnerBuilder());

private AppModel()
{
Expand Down Expand Up @@ -139,6 +144,11 @@ public UpdateMode UpdateMode
get => AppConfigs.Configuration.UpdateMode;
set
{
if (value != AppConfigs.Configuration.UpdateMode && value != UpdateMode.Never)
{
CheckForUpdate();
}

AppConfigs.Configuration.UpdateMode = value;
AppConfigs.Configuration.Save();
}
Expand Down Expand Up @@ -230,15 +240,16 @@ public void InitializeMain()
AppConfigs.Configuration.RecordingHotKey.Enabled = false;
saveConfig = true;
}

if (!RegisterHotKey(AppConfigs.Configuration.MuteRecordingHotKey))
{
AppConfigs.Configuration.MuteRecordingHotKey.Enabled = false;
saveConfig = true;
}

if (!AppConfigs.Configuration.MigratedFields.Contains($"{nameof(SwitchForegroundProgram)}_cleanup")
&& AppConfigs.Configuration.MigratedFields.Contains($"{nameof(SwitchForegroundProgram)}_force_off") &&
!AppConfigs.Configuration.SwitchForegroundProgram)
&& AppConfigs.Configuration.MigratedFields.Contains($"{nameof(SwitchForegroundProgram)}_force_off") &&
!AppConfigs.Configuration.SwitchForegroundProgram)
{
AppConfigs.Configuration.MigratedFields.Add($"{nameof(SwitchForegroundProgram)}_cleanup");
try
Expand Down Expand Up @@ -276,22 +287,25 @@ public void InitializeMain()

private void InitUpdateChecker()
{
if (AppConfigs.Configuration.UpdateMode == UpdateMode.Never)
{
return;
}
#if DEBUG
const string url = "https://www.aaflalo.me/api.json";
#else
const string url = "https://api.github.com/repos/Belphemur/SoundSwitch/releases";
#endif
_updateChecker = new IntervalUpdateChecker(new Uri(url),
AppConfigs.Configuration.UpdateCheckInterval,
AppConfigs.Configuration.IncludeBetaVersions);
_updateChecker = new UpdateChecker(new Uri(url), AppConfigs.Configuration.IncludeBetaVersions);

_updateChecker.UpdateAvailable += (sender, @event) => NewVersionReleased?.Invoke(this,
new NewReleaseAvailableEvent(@event.Release, AppConfigs.Configuration.UpdateMode));
_updateChecker.CheckForUpdate();

_jobScheduler.ScheduleJob(new CheckForUpdateRecurringJob(_updateChecker));
}

/// <summary>
/// For the app to check for update
/// </summary>
public void CheckForUpdate()
{
_jobScheduler.ScheduleJob(new CheckForUpdateOnceJob(_updateChecker));
}

public event EventHandler<DeviceListChanged> SelectedDeviceChanged;
Expand Down Expand Up @@ -355,14 +369,13 @@ public bool UnselectDevice(DeviceFullInfo device)

#region Hot keys


public bool SetHotkeyCombination(HotKey hotKey, HotKeyAction action, bool force = false)
{
var confHotKey = action switch
{
HotKeyAction.Playback => AppConfigs.Configuration.PlaybackHotKey,
HotKeyAction.Recording => AppConfigs.Configuration.RecordingHotKey,
HotKeyAction.Mute => AppConfigs.Configuration.MuteRecordingHotKey,
HotKeyAction.Mute => AppConfigs.Configuration.MuteRecordingHotKey,
_ => throw new ArgumentOutOfRangeException(nameof(action), action, null)
};

Expand All @@ -382,10 +395,10 @@ public bool SetHotkeyCombination(HotKey hotKey, HotKeyAction action, bool force

switch (action)
{
case HotKeyAction.Playback:
case HotKeyAction.Playback:
AppConfigs.Configuration.PlaybackHotKey = hotKey;
break;
case HotKeyAction.Recording:
case HotKeyAction.Recording:
AppConfigs.Configuration.RecordingHotKey = hotKey;
break;
case HotKeyAction.Mute:
Expand Down Expand Up @@ -503,6 +516,8 @@ public void Dispose()
TrayIcon?.Dispose();
ActiveAudioDeviceLister?.Dispose();
ActiveUnpluggedAudioLister?.Dispose();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1));
_jobScheduler.StopAsync(cts.Token).GetAwaiter().GetResult();
}
}
}
1 change: 1 addition & 0 deletions SoundSwitch/SoundSwitch.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
<ItemGroup>
<PackageReference Include="AuthenticodeExaminer" Version="0.3.0" />
<PackageReference Include="ContribSentry" Version="4.0.0" />
<PackageReference Include="Job.Scheduler" Version="2.2.0" />
<PackageReference Include="Markdig" Version="0.24.0" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="NAudio" Version="2.0.0" />
Expand Down

0 comments on commit dfd2f55

Please sign in to comment.