mattercontrol/original/MatterControlLib/DialogPages/UpdateControlData.cs

429 lines
12 KiB
C#
Raw Normal View History

/*
2018-11-20 12:48:42 -08:00
Copyright (c) 2018, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
2015-04-08 15:20:10 -07:00
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
2015-04-08 15:20:10 -07:00
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
2015-04-08 15:20:10 -07:00
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
2015-04-08 15:20:10 -07:00
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
2017-08-20 15:52:43 -07:00
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
2018-01-13 13:27:34 -08:00
using System.Timers;
using MatterHackers.Agg;
using MatterHackers.Agg.Platform;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.SettingsManagement;
using MatterHackers.MatterControl.VersionManagement;
namespace MatterHackers.MatterControl
{
2015-04-07 15:54:20 -07:00
public class UpdateControlData
{
2015-04-08 15:20:10 -07:00
private WebClient webClient;
private int downloadSize;
2018-11-20 12:59:13 -08:00
public int DownloadPercent { get; private set; }
public enum UpdateStatusStates { MayBeAvailable, CheckingForUpdate, UpdateAvailable, UpdateDownloading, ReadyToInstall, UpToDate, UnableToConnectToServer, UpdateRequired };
2015-04-08 15:20:10 -07:00
private bool WaitingToCompleteTransaction()
2015-04-07 15:54:20 -07:00
{
switch (UpdateStatus)
{
case UpdateStatusStates.CheckingForUpdate:
case UpdateStatusStates.UpdateDownloading:
return true;
default:
return false;
}
}
public RootedObjectEventHandler UpdateStatusChanged = new RootedObjectEventHandler();
#if __ANDROID__
static string updateFileLocation = Path.Combine(ApplicationDataStorage.Instance.PublicDataStoragePath, "updates");
#else
private static string applicationDataPath = ApplicationDataStorage.ApplicationUserDataPath;
2015-04-08 15:20:10 -07:00
private static string updateFileLocation = Path.Combine(applicationDataPath, "updates");
2015-04-07 15:54:20 -07:00
#endif
2015-04-08 15:20:10 -07:00
private UpdateStatusStates updateStatus;
2018-11-20 12:48:42 -08:00
public UpdateStatusStates UpdateStatus => updateStatus;
2015-04-07 15:54:20 -07:00
2015-04-08 15:20:10 -07:00
private void CheckVersionStatus()
2015-04-07 15:54:20 -07:00
{
string currentBuildToken = ApplicationSettings.Instance.get(LatestVersionRequest.VersionKey.CurrentBuildToken);
2015-04-07 15:54:20 -07:00
string updateFileName = Path.Combine(updateFileLocation, string.Format("{0}.{1}", currentBuildToken, InstallerExtension));
string applicationBuildToken = VersionInfo.Instance.BuildToken;
if (applicationBuildToken == currentBuildToken || currentBuildToken == null)
{
SetUpdateStatus(UpdateStatusStates.MayBeAvailable);
}
2018-11-20 12:48:42 -08:00
else if (File.Exists(updateFileName))
2015-04-07 15:54:20 -07:00
{
SetUpdateStatus(UpdateStatusStates.ReadyToInstall);
}
else
{
SetUpdateStatus(UpdateStatusStates.UpdateAvailable);
}
}
2018-01-13 13:27:34 -08:00
private static bool haveShowUpdateRequired = false;
2015-04-08 15:20:10 -07:00
private void SetUpdateStatus(UpdateStatusStates updateStatus)
2015-04-07 15:54:20 -07:00
{
if (this.updateStatus != updateStatus)
{
this.updateStatus = updateStatus;
OnUpdateStatusChanged(null);
if (this.UpdateRequired && !haveShowUpdateRequired)
{
haveShowUpdateRequired = true;
2021-07-07 18:06:06 -07:00
if (!GuiWidget.TouchScreenMode)
{
UiThread.RunOnIdle(() => DialogWindow.Show<CheckForUpdatesPage>());
}
}
2015-04-07 15:54:20 -07:00
}
}
2015-04-08 15:20:10 -07:00
private string InstallerExtension
2015-04-07 15:54:20 -07:00
{
get
{
if (AggContext.OperatingSystem == OSType.Mac)
2014-10-31 10:19:50 -07:00
{
2021-01-08 16:01:43 -08:00
return "pkg";
2014-10-31 10:19:50 -07:00
}
else if (AggContext.OperatingSystem == OSType.X11)
{
2019-01-30 11:14:07 -08:00
return "deb";
}
else if (AggContext.OperatingSystem == OSType.Android)
2014-10-31 10:19:50 -07:00
{
return "apk";
}
2015-04-07 15:54:20 -07:00
else
{
return "exe";
}
}
}
2015-04-08 15:20:10 -07:00
private static UpdateControlData instance;
2015-04-07 15:54:20 -07:00
static public UpdateControlData Instance
{
get
{
if (instance == null)
{
instance = new UpdateControlData();
}
2015-04-07 15:54:20 -07:00
return instance;
}
}
public bool UpdateRequired
{
get
{
2018-11-20 12:48:42 -08:00
return updateStatus == UpdateStatusStates.UpdateAvailable
&& ApplicationSettings.Instance.get(LatestVersionRequest.VersionKey.UpdateRequired) == "True";
}
}
2018-01-13 13:27:34 -08:00
public void CheckForUpdate()
2015-04-07 15:54:20 -07:00
{
if (!WaitingToCompleteTransaction())
{
SetUpdateStatus(UpdateStatusStates.CheckingForUpdate);
2018-11-20 12:30:41 -08:00
var request = new LatestVersionRequest();
2018-11-20 12:34:06 -08:00
request.RequestSucceeded += VersionRequest_Succeeded;
request.RequestFailed += VersionRequest_Failed;
2015-04-07 15:54:20 -07:00
request.Request();
}
}
2018-11-20 12:34:06 -08:00
private void VersionRequest_Succeeded(object sender, EventArgs e)
2015-04-07 15:54:20 -07:00
{
string currentBuildToken = ApplicationSettings.Instance.get(LatestVersionRequest.VersionKey.CurrentBuildToken);
2015-04-07 15:54:20 -07:00
string updateFileName = Path.Combine(updateFileLocation, string.Format("{0}.{1}", currentBuildToken, InstallerExtension));
string applicationBuildToken = VersionInfo.Instance.BuildToken;
if (applicationBuildToken == currentBuildToken)
{
SetUpdateStatus(UpdateStatusStates.UpToDate);
}
2018-11-20 12:48:42 -08:00
else if (File.Exists(updateFileName))
2015-04-07 15:54:20 -07:00
{
SetUpdateStatus(UpdateStatusStates.ReadyToInstall);
}
else
{
SetUpdateStatus(UpdateStatusStates.UpdateAvailable);
2018-01-13 13:27:34 -08:00
bool firstUpdateRequest = ApplicationSettings.Instance.GetClientToken() == null;
if (firstUpdateRequest)
2015-04-07 15:54:20 -07:00
{
UiThread.RunOnIdle(() =>
2015-04-07 15:54:20 -07:00
{
2018-11-20 12:30:24 -08:00
StyledMessageBox.ShowMessageBox(
this.ProcessDialogResponse,
"There is a recommended update available for MatterControl. Would you like to download it now?".Localize(),
"Recommended Update Available".Localize(),
StyledMessageBox.MessageType.YES_NO,
"Download Now".Localize(),
"Remind Me Later".Localize());
2015-04-07 15:54:20 -07:00
// show a dialog to tell the user there is an update
});
}
}
}
2015-04-08 15:20:10 -07:00
private void ProcessDialogResponse(bool messageBoxResponse)
2015-04-07 15:54:20 -07:00
{
if (messageBoxResponse)
{
InitiateUpdateDownload();
// Switch to the about page so we can see the download progress.
GuiWidget aboutTabWidget = ApplicationController.Instance.MainView.FindDescendant("About Tab");
2017-10-14 21:28:48 -07:00
if (aboutTabWidget is Tab aboutTab)
2015-04-07 15:54:20 -07:00
{
aboutTab.TabBarContaningTab.SelectTab(aboutTab);
}
}
}
2018-11-20 12:34:06 -08:00
private void VersionRequest_Failed(object sender, ResponseErrorEventArgs e)
2015-04-07 15:54:20 -07:00
{
SetUpdateStatus(UpdateStatusStates.UpToDate);
}
2015-04-08 15:20:10 -07:00
private int downloadAttempts = 0;
private string updateFileName;
2015-04-07 15:54:20 -07:00
public void InitiateUpdateDownload()
{
downloadAttempts = 0;
DownloadUpdate();
}
2015-04-08 15:20:10 -07:00
private void DownloadUpdate()
2015-04-07 15:54:20 -07:00
{
(new Thread(new ThreadStart(() => DownloadUpdateTask()))).Start();
}
2015-04-08 15:20:10 -07:00
private void DownloadUpdateTask()
2015-04-07 15:54:20 -07:00
{
if (!WaitingToCompleteTransaction())
{
string downloadToken = ApplicationSettings.Instance.get(LatestVersionRequest.VersionKey.CurrentBuildToken);
2015-04-07 15:54:20 -07:00
if (downloadToken == null)
{
#if DEBUG
throw new Exception("Build token should not be null");
#endif
//
}
else
{
downloadAttempts++;
SetUpdateStatus(UpdateStatusStates.UpdateDownloading);
string downloadUri = $"{MatterControlApplication.MCWSBaseUri}/downloads/development/{ApplicationSettings.Instance.get(LatestVersionRequest.VersionKey.CurrentBuildToken)}";
2015-04-07 15:54:20 -07:00
//Make HEAD request to determine the size of the download (required by GAE)
System.Net.WebRequest request = System.Net.WebRequest.Create(downloadUri);
request.Method = "HEAD";
try
{
WebResponse response = request.GetResponse();
downloadSize = (int)response.ContentLength;
}
catch
{
GuiWidget.BreakInDebugger();
2015-04-07 15:54:20 -07:00
//Unknown download size
downloadSize = 0;
}
2018-11-20 12:48:42 -08:00
if (!Directory.Exists(updateFileLocation))
2015-04-07 15:54:20 -07:00
{
2018-11-20 12:48:42 -08:00
Directory.CreateDirectory(updateFileLocation);
2015-04-07 15:54:20 -07:00
}
updateFileName = Path.Combine(updateFileLocation, string.Format("{0}.{1}", downloadToken, InstallerExtension));
webClient = new WebClient();
2018-11-20 12:48:42 -08:00
webClient.DownloadFileCompleted += DownloadCompleted;
webClient.DownloadProgressChanged += DownloadProgressChanged;
2017-01-03 12:27:36 -08:00
try
{
webClient.DownloadFileAsync(new Uri(downloadUri), updateFileName);
}
catch
{
}
2015-04-07 15:54:20 -07:00
}
}
}
2015-04-08 15:20:10 -07:00
private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
2015-04-07 15:54:20 -07:00
{
if (downloadSize > 0)
{
2018-11-20 12:59:13 -08:00
this.DownloadPercent = (int)(e.BytesReceived * 100 / downloadSize);
2015-04-07 15:54:20 -07:00
}
2018-01-13 13:27:34 -08:00
UiThread.RunOnIdle(() => UpdateStatusChanged.CallEvents(this, e));
2015-04-07 15:54:20 -07:00
}
2015-04-08 15:20:10 -07:00
private void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
2015-04-07 15:54:20 -07:00
{
if (e.Error != null)
{
//Delete empty/partially downloaded file
2018-11-20 12:48:42 -08:00
if (File.Exists(updateFileName))
2015-04-07 15:54:20 -07:00
{
2018-11-20 12:48:42 -08:00
File.Delete(updateFileName);
2015-04-07 15:54:20 -07:00
}
2015-04-07 15:54:20 -07:00
//Try downloading again - one time
if (downloadAttempts == 1)
{
DownloadUpdate();
}
else
{
UiThread.RunOnIdle(() => SetUpdateStatus(UpdateStatusStates.UnableToConnectToServer));
2015-04-07 15:54:20 -07:00
}
}
else
{
UiThread.RunOnIdle(() => SetUpdateStatus(UpdateStatusStates.ReadyToInstall));
2015-04-07 15:54:20 -07:00
}
2015-04-07 15:54:20 -07:00
webClient.Dispose();
}
2015-04-07 15:54:20 -07:00
private UpdateControlData()
{
this.CheckVersionStatus();
// Always check for updates on startup
this.CheckForUpdate();
2018-01-13 13:27:34 -08:00
// Now that we are running, check for an update every 24 hours.
2018-11-20 12:48:42 -08:00
var checkUpdatesDaily = new System.Timers.Timer(24 * 60 * 60 * 1000); //one day in milliseconds
checkUpdatesDaily.Elapsed += DailyTimer_Elapsed;
checkUpdatesDaily.Start();
2018-01-13 13:27:34 -08:00
}
2018-11-20 12:48:42 -08:00
private void DailyTimer_Elapsed(object source, ElapsedEventArgs e)
2018-01-13 13:27:34 -08:00
{
CheckForUpdate();
2015-04-07 15:54:20 -07:00
}
public void OnUpdateStatusChanged(EventArgs e)
{
UpdateStatusChanged.CallEvents(this, e);
}
2018-12-17 16:14:09 -08:00
public static event EventHandler InstallUpdateFromMainActivity = null;
2015-04-07 15:54:20 -07:00
public bool InstallUpdate()
2015-04-07 15:54:20 -07:00
{
string downloadToken = ApplicationSettings.Instance.get(LatestVersionRequest.VersionKey.CurrentBuildToken);
2015-04-07 15:54:20 -07:00
string updateFileName = Path.Combine(updateFileLocation, "{0}.{1}".FormatWith(downloadToken, InstallerExtension));
#if __ANDROID__
string friendlyFileName = Path.Combine(updateFileLocation, "MatterControlSetup.apk");
#else
string releaseVersion = ApplicationSettings.Instance.get(LatestVersionRequest.VersionKey.CurrentReleaseVersion);
2015-04-07 15:54:20 -07:00
string friendlyFileName = Path.Combine(updateFileLocation, "MatterControlSetup-{0}.{1}".FormatWith(releaseVersion, InstallerExtension));
#endif
2018-11-20 12:48:42 -08:00
if (File.Exists(friendlyFileName))
2015-04-07 15:54:20 -07:00
{
2018-11-20 12:48:42 -08:00
File.Delete(friendlyFileName);
2015-04-07 15:54:20 -07:00
}
2015-04-07 15:54:20 -07:00
try
{
//Change download file to friendly file name
2018-11-20 12:48:42 -08:00
File.Move(updateFileName, friendlyFileName);
2017-01-26 16:50:35 -08:00
#if __ANDROID__
InstallUpdateFromMainActivity?.Invoke(this, null);
2015-04-07 15:54:20 -07:00
return true;
#else
2015-04-08 15:20:10 -07:00
int tries = 0;
do
{
Thread.Sleep(10);
} while (tries++ < 100 && !File.Exists(friendlyFileName));
//Run installer file
Process installUpdate = new Process();
installUpdate.StartInfo.FileName = friendlyFileName;
installUpdate.Start();
//Attempt to close current application
SystemWindow topSystemWindow = AppContext.RootSystemWindow;
2015-04-08 15:20:10 -07:00
if (topSystemWindow != null)
{
topSystemWindow.CloseOnIdle();
return true;
}
2015-04-07 15:54:20 -07:00
#endif
}
catch
{
GuiWidget.BreakInDebugger();
2018-11-20 12:48:42 -08:00
if (File.Exists(friendlyFileName))
2015-04-07 15:54:20 -07:00
{
2018-11-20 12:48:42 -08:00
File.Delete(friendlyFileName);
2015-04-07 15:54:20 -07:00
}
}
2015-04-07 15:54:20 -07:00
return false;
}
}
2018-01-13 13:27:34 -08:00
}