Removing Squirrel dll. unsure on updating so i kept that logic in

This commit is contained in:
Clint Rutkas 2020-04-03 17:30:33 -07:00
parent 5b02501038
commit 35e9091863
6 changed files with 71 additions and 243 deletions

View File

@ -1,146 +0,0 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using JetBrains.Annotations;
using Squirrel;
using Newtonsoft.Json;
using Wox.Core.Resource;
using Wox.Plugin.SharedCommands;
using Wox.Infrastructure;
using Wox.Infrastructure.Http;
using Wox.Infrastructure.Logger;
using System.IO;
namespace Wox.Core
{
public class Updater
{
public string GitHubRepository { get; }
public Updater(string gitHubRepository)
{
GitHubRepository = gitHubRepository;
}
public async Task UpdateApp(bool silentIfLatestVersion = true)
{
UpdateManager updateManager;
UpdateInfo newUpdateInfo;
try
{
updateManager = await GitHubUpdateManager(GitHubRepository);
}
catch (Exception e) when (e is HttpRequestException || e is WebException || e is SocketException)
{
Log.Exception($"|Updater.UpdateApp|Please check your connection and proxy settings to api.github.com.", e);
return;
}
try
{
// UpdateApp CheckForUpdate will return value only if the app is squirrel installed
newUpdateInfo = await updateManager.CheckForUpdate().NonNull();
}
catch (Exception e) when (e is HttpRequestException || e is WebException || e is SocketException)
{
Log.Exception($"|Updater.UpdateApp|Check your connection and proxy settings to api.github.com.", e);
updateManager.Dispose();
return;
}
var newReleaseVersion = Version.Parse(newUpdateInfo.FutureReleaseEntry.Version.ToString());
var currentVersion = Version.Parse(Constant.Version);
Log.Info($"|Updater.UpdateApp|Future Release <{newUpdateInfo.FutureReleaseEntry.Formatted()}>");
if (newReleaseVersion <= currentVersion)
{
if (!silentIfLatestVersion)
MessageBox.Show("You already have the latest Wox version");
updateManager.Dispose();
return;
}
try
{
await updateManager.DownloadReleases(newUpdateInfo.ReleasesToApply);
}
catch (Exception e) when (e is HttpRequestException || e is WebException || e is SocketException)
{
Log.Exception($"|Updater.UpdateApp|Check your connection and proxy settings to github-cloud.s3.amazonaws.com.", e);
updateManager.Dispose();
return;
}
await updateManager.ApplyReleases(newUpdateInfo);
if (Constant.IsPortableMode)
{
var targetDestination = updateManager.RootAppDirectory + $"\\app-{newReleaseVersion.ToString()}\\{Constant.PortableFolderName}";
FilesFolders.Copy(Constant.PortableDataPath, targetDestination);
if (!FilesFolders.VerifyBothFolderFilesEqual(Constant.PortableDataPath, targetDestination))
MessageBox.Show(string.Format("Wox was not able to move your user profile data to the new update version. Please manually" +
"move your profile data folder from {0} to {1}", Constant.PortableDataPath, targetDestination));
}
else
{
await updateManager.CreateUninstallerRegistryEntry();
}
var newVersionTips = NewVersinoTips(newReleaseVersion.ToString());
MessageBox.Show(newVersionTips);
Log.Info($"|Updater.UpdateApp|Update success:{newVersionTips}");
// always dispose UpdateManager
updateManager.Dispose();
}
[UsedImplicitly]
private class GithubRelease
{
[JsonProperty("prerelease")]
public bool Prerelease { get; [UsedImplicitly] set; }
[JsonProperty("published_at")]
public DateTime PublishedAt { get; [UsedImplicitly] set; }
[JsonProperty("html_url")]
public string HtmlUrl { get; [UsedImplicitly] set; }
}
/// https://github.com/Squirrel/Squirrel.Windows/blob/master/src/Squirrel/UpdateManager.Factory.cs
private async Task<UpdateManager> GitHubUpdateManager(string repository)
{
var uri = new Uri(repository);
var api = $"https://api.github.com/repos{uri.AbsolutePath}/releases";
var json = await Http.Get(api);
var releases = JsonConvert.DeserializeObject<List<GithubRelease>>(json);
var latest = releases.Where(r => !r.Prerelease).OrderByDescending(r => r.PublishedAt).First();
var latestUrl = latest.HtmlUrl.Replace("/tag/", "/download/");
var client = new WebClient { Proxy = Http.WebProxy() };
var downloader = new FileDownloader(client);
var manager = new UpdateManager(latestUrl, urlDownloader: downloader);
return manager;
}
public string NewVersinoTips(string version)
{
var translater = InternationalizationManager.Instance;
var tips = string.Format(translater.GetTranslation("newVersionTips"), version);
return tips;
}
}
}

View File

@ -58,7 +58,6 @@
</PackageReference>
<PackageReference Include="JetBrains.Annotations" Version="2019.1.3" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="ppy.squirrel.windows" Version="1.9.0.4" />
<PackageReference Include="PropertyChanged.Fody" Version="3.2.6" />
<PackageReference Include="SharpZipLib" Version="1.2.0" />
<PackageReference Include="System.Runtime" Version="4.3.1" />

View File

@ -25,7 +25,6 @@ namespace Wox
private Settings _settings;
private MainViewModel _mainVM;
private SettingWindowViewModel _settingsVM;
private readonly Updater _updater = new Updater(Wox.Properties.Settings.Default.GithubRepo);
private readonly Alphabet _alphabet = new Alphabet();
private StringMatcher _stringMatcher;
@ -53,7 +52,7 @@ namespace Wox
ImageLoader.Initialize();
_settingsVM = new SettingWindowViewModel(_updater);
_settingsVM = new SettingWindowViewModel();
_settings = _settingsVM.Settings;
_alphabet.Initialize(_settings);
@ -83,40 +82,11 @@ namespace Wox
RegisterExitEvents();
AutoStartup();
AutoUpdates();
_mainVM.MainWindowVisibility = _settings.HideOnStartup ? Visibility.Hidden : Visibility.Visible;
Log.Info("|App.OnStartup|End Wox startup ---------------------------------------------------- ");
});
}
private void AutoStartup()
{
}
//[Conditional("RELEASE")]
private void AutoUpdates()
{
Task.Run(async () =>
{
if (_settings.AutoUpdates)
{
// check udpate every 5 hours
var timer = new Timer(1000 * 60 * 60 * 5);
timer.Elapsed += async (s, e) =>
{
await _updater.UpdateApp();
};
timer.Start();
// check updates on startup
await _updater.UpdateApp();
}
});
}
private void RegisterExitEvents()
{
AppDomain.CurrentDomain.ProcessExit += (s, e) => Dispose();

View File

@ -4,8 +4,7 @@ using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using Squirrel;
using Wox.Core;
using Wox.Core.Plugin;
using Wox.Core.Resource;
using Wox.Helper;
@ -63,12 +62,12 @@ namespace Wox
// which will cause ungraceful exit
SaveAppAllSettings();
UpdateManager.RestartApp();
Squirrel.UpdateManager.RestartApp();
}
public void CheckForNewUpdate()
{
_settingsVM.UpdateApp();
//_settingsVM.UpdateApp();
}
public void SaveAppAllSettings()
@ -101,7 +100,7 @@ namespace Wox
{
Application.Current.Dispatcher.Invoke(() =>
{
var msg = useMainWindowAsOwner ? new Msg {Owner = Application.Current.MainWindow} : new Msg();
var msg = useMainWindowAsOwner ? new Msg { Owner = Application.Current.MainWindow } : new Msg();
msg.Show(title, subTitle, iconPath);
});
}

View File

@ -0,0 +1,65 @@
// code block is from
// unblocking https://github.com/Squirrel/Squirrel.Windows/blob/master/src/Squirrel/UpdateManager.cs
// https://github.com/Squirrel/Squirrel.Windows/blob/develop/COPYING
// license is MIT
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
namespace Squirrel
{
public sealed partial class UpdateManager
{
public static void RestartApp(string exeToStart = null, string arguments = null)
{
// NB: Here's how this method works:
//
// 1. We're going to pass the *name* of our EXE and the params to
// Update.exe
// 2. Update.exe is going to grab our PID (via getting its parent),
// then wait for us to exit.
// 3. We exit cleanly, dropping any single-instance mutexes or
// whatever.
// 4. Update.exe unblocks, then we launch the app again, possibly
// launching a different version than we started with (this is why
// we take the app's *name* rather than a full path)
exeToStart = exeToStart ?? Path.GetFileName(Assembly.GetEntryAssembly().Location);
var argsArg = arguments != null ?
string.Format("-a \"{0}\"", arguments) : "";
Process.Start(getUpdateExe(), string.Format("--processStartAndWait {0} {1}", exeToStart, argsArg));
// NB: We have to give update.exe some time to grab our PID, but
// we can't use WaitForInputIdle because we probably don't have
// whatever WaitForInputIdle considers a message loop.
Thread.Sleep(500);
Environment.Exit(0);
}
static string getUpdateExe()
{
var assembly = Assembly.GetEntryAssembly();
// Are we update.exe?
if (assembly != null &&
Path.GetFileName(assembly.Location).Equals("update.exe", StringComparison.OrdinalIgnoreCase) &&
assembly.Location.IndexOf("app-", StringComparison.OrdinalIgnoreCase) == -1 &&
assembly.Location.IndexOf("SquirrelTemp", StringComparison.OrdinalIgnoreCase) == -1)
{
return Path.GetFullPath(assembly.Location);
}
assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
var updateDotExe = Path.Combine(Path.GetDirectoryName(assembly.Location), "..\\Update.exe");
var target = new FileInfo(updateDotExe);
if (!target.Exists) throw new Exception("Update.exe not found, not a Squirrel-installed app?");
return target.FullName;
}
}
}

View File

@ -21,12 +21,10 @@ namespace Wox.ViewModel
{
public class SettingWindowViewModel : BaseModel
{
private readonly Updater _updater;
private readonly WoxJsonStorage<Settings> _storage;
public SettingWindowViewModel(Updater updater)
public SettingWindowViewModel()
{
_updater = updater;
_storage = new WoxJsonStorage<Settings>();
Settings = _storage.Load();
Settings.PropertyChanged += (s, e) =>
@ -42,11 +40,6 @@ namespace Wox.ViewModel
public Settings Settings { get; set; }
public async void UpdateApp()
{
await _updater.UpdateApp(false);
}
public void Save()
{
_storage.Save();
@ -95,50 +88,6 @@ namespace Wox.ViewModel
public List<Language> Languages => _translater.LoadAvailableLanguages();
public IEnumerable<int> MaxResultsRange => Enumerable.Range(2, 16);
public string TestProxy()
{
var proxyServer = Settings.Proxy.Server;
var proxyUserName = Settings.Proxy.UserName;
if (string.IsNullOrEmpty(proxyServer))
{
return InternationalizationManager.Instance.GetTranslation("serverCantBeEmpty");
}
if (Settings.Proxy.Port <= 0)
{
return InternationalizationManager.Instance.GetTranslation("portCantBeEmpty");
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_updater.GitHubRepository);
if (string.IsNullOrEmpty(proxyUserName) || string.IsNullOrEmpty(Settings.Proxy.Password))
{
request.Proxy = new WebProxy(proxyServer, Settings.Proxy.Port);
}
else
{
request.Proxy = new WebProxy(proxyServer, Settings.Proxy.Port)
{
Credentials = new NetworkCredential(proxyUserName, Settings.Proxy.Password)
};
}
try
{
var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
return InternationalizationManager.Instance.GetTranslation("proxyIsCorrect");
}
else
{
return InternationalizationManager.Instance.GetTranslation("proxyConnectFailed");
}
}
catch
{
return InternationalizationManager.Instance.GetTranslation("proxyConnectFailed");
}
}
#endregion
#region plugin
@ -254,11 +203,6 @@ namespace Wox.ViewModel
Title = "Install plugins from: ",
SubTitle = Plugin
},
new Result
{
Title = $"Open Source: {_updater.GitHubRepository}",
SubTitle = "Please star it!"
}
};
var vm = new ResultsViewModel();
vm.AddResults(results, "PREVIEW");
@ -365,9 +309,6 @@ namespace Wox.ViewModel
#endregion
#region about
public string Github => _updater.GitHubRepository;
public string ReleaseNotes => _updater.GitHubRepository + @"/releases/latest";
public static string Version => Constant.Version;
public string ActivatedTimes => string.Format(_translater.GetTranslation("about_activate_times"), Settings.ActivateTimes);
#endregion