mattercontrol/AboutPage/UpdateControlData.cs

448 lines
13 KiB
C#
Raw Normal View History

/*
Copyright (c) 2014, Lars Brubaker
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.
*/
using MatterHackers.Agg;
2014-06-19 16:09:38 -07:00
using MatterHackers.Agg.PlatformAbstract;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.SettingsManagement;
using MatterHackers.MatterControl.VersionManagement;
2015-04-08 15:20:10 -07:00
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
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;
2015-04-08 15:20:10 -07:00
private int downloadPercent;
private int downloadSize;
2015-04-07 15:54:20 -07:00
public int DownloadPercent { get { return downloadPercent; } }
2015-04-07 15:54:20 -07:00
public enum UpdateRequestType { UserRequested, Automatic, FirstTimeEver };
2015-04-08 15:20:10 -07:00
private UpdateRequestType updateRequestType;
2015-04-07 15:54:20 -07:00
public enum UpdateStatusStates { MayBeAvailable, CheckingForUpdate, UpdateAvailable, UpdateDownloading, ReadyToInstall, UpToDate, UnableToConnectToServer };
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(DataStorage.ApplicationDataStorage.Instance.PublicDataStoragePath, "updates");
#else
private static string applicationDataPath = DataStorage.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;
2015-04-07 15:54:20 -07:00
public UpdateStatusStates UpdateStatus
{
get
{
return updateStatus;
}
}
2015-04-08 15:20:10 -07:00
private void CheckVersionStatus()
2015-04-07 15:54:20 -07:00
{
string currentBuildToken = ApplicationSettings.Instance.get("CurrentBuildToken");
string updateFileName = Path.Combine(updateFileLocation, string.Format("{0}.{1}", currentBuildToken, InstallerExtension));
string applicationBuildToken = VersionInfo.Instance.BuildToken;
if (applicationBuildToken == currentBuildToken || currentBuildToken == null)
{
SetUpdateStatus(UpdateStatusStates.MayBeAvailable);
}
else if (System.IO.File.Exists(updateFileName))
{
SetUpdateStatus(UpdateStatusStates.ReadyToInstall);
}
else
{
SetUpdateStatus(UpdateStatusStates.UpdateAvailable);
}
}
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);
}
}
2015-04-08 15:20:10 -07:00
private string InstallerExtension
2015-04-07 15:54:20 -07:00
{
get
{
2014-10-31 10:19:50 -07:00
if (OsInformation.OperatingSystem == OSType.Mac)
{
return "pkg";
}
else if (OsInformation.OperatingSystem == OSType.X11)
{
return "tar.gz";
}
2014-10-31 10:19:50 -07:00
else if (OsInformation.OperatingSystem == OSType.Android)
{
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 void CheckForUpdateUserRequested()
{
updateRequestType = UpdateRequestType.UserRequested;
CheckForUpdate();
}
2015-04-08 15:20:10 -07:00
private void CheckForUpdate()
2015-04-07 15:54:20 -07:00
{
if (!WaitingToCompleteTransaction())
{
SetUpdateStatus(UpdateStatusStates.CheckingForUpdate);
LatestVersionRequest request = new LatestVersionRequest();
2015-04-07 15:54:20 -07:00
request.RequestSucceeded += new EventHandler(onVersionRequestSucceeded);
2015-06-17 16:55:49 -07:00
request.RequestFailed += onVersionRequestFailed;
2015-04-07 15:54:20 -07:00
request.Request();
}
}
2015-07-31 12:22:32 -07:00
private static string updateAvailableMessage = "There is a recommended update available for MatterControl. Would you like to download it now?".Localize();
private static string updateAvailableTitle = "Recommended Update Available".Localize();
private static string downloadNow = "Download Now".Localize();
private static string remindMeLater = "Remind Me Later".Localize();
2015-04-08 15:20:10 -07:00
private void onVersionRequestSucceeded(object sender, EventArgs e)
2015-04-07 15:54:20 -07:00
{
string currentBuildToken = ApplicationSettings.Instance.get("CurrentBuildToken");
string updateFileName = Path.Combine(updateFileLocation, string.Format("{0}.{1}", currentBuildToken, InstallerExtension));
string applicationBuildToken = VersionInfo.Instance.BuildToken;
if (applicationBuildToken == currentBuildToken)
{
SetUpdateStatus(UpdateStatusStates.UpToDate);
}
else if (System.IO.File.Exists(updateFileName))
{
SetUpdateStatus(UpdateStatusStates.ReadyToInstall);
}
else
{
SetUpdateStatus(UpdateStatusStates.UpdateAvailable);
if (updateRequestType == UpdateRequestType.FirstTimeEver)
{
UiThread.RunOnIdle(() =>
2015-04-07 15:54:20 -07:00
{
StyledMessageBox.ShowMessageBox(ProcessDialogResponse, updateAvailableMessage, updateAvailableTitle, StyledMessageBox.MessageType.YES_NO, downloadNow, remindMeLater);
// 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 = FindNamedWidgetRecursive(ApplicationController.Instance.MainView, "About Tab");
Tab aboutTab = aboutTabWidget as Tab;
if (aboutTab != null)
{
aboutTab.TabBarContaningTab.SelectTab(aboutTab);
}
}
}
2015-04-08 15:20:10 -07:00
private static GuiWidget FindNamedWidgetRecursive(GuiWidget root, string name)
2015-04-07 15:54:20 -07:00
{
foreach (GuiWidget child in root.Children)
{
if (child.Name == name)
{
return child;
}
2015-04-07 15:54:20 -07:00
GuiWidget foundWidget = FindNamedWidgetRecursive(child, name);
if (foundWidget != null)
{
return foundWidget;
}
}
return null;
}
private void onVersionRequestFailed(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("CurrentBuildToken");
if (downloadToken == null)
{
#if DEBUG
throw new Exception("Build token should not be null");
#endif
//
}
else
{
downloadAttempts++;
SetUpdateStatus(UpdateStatusStates.UpdateDownloading);
string downloadUri = string.Format("https://mattercontrol.appspot.com/downloads/development/{0}", ApplicationSettings.Instance.get("CurrentBuildToken"));
//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;
}
if (!System.IO.Directory.Exists(updateFileLocation))
{
System.IO.Directory.CreateDirectory(updateFileLocation);
}
updateFileName = Path.Combine(updateFileLocation, string.Format("{0}.{1}", downloadToken, InstallerExtension));
webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
webClient.DownloadFileAsync(new Uri(downloadUri), updateFileName);
}
}
}
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)
{
this.downloadPercent = (int)(e.BytesReceived * 100 / downloadSize);
}
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
if (System.IO.File.Exists(updateFileName))
{
System.IO.File.Delete(updateFileName);
}
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()
{
CheckVersionStatus();
if (ApplicationSettings.Instance.get("ClientToken") != null
|| OemSettings.Instance.CheckForUpdatesOnFirstRun)
{
if (ApplicationSettings.Instance.get("ClientToken") == null)
{
updateRequestType = UpdateRequestType.FirstTimeEver;
}
else
{
updateRequestType = UpdateRequestType.Automatic;
}
//If we have already requested an update once, check on load
CheckForUpdate();
}
else
{
DataStorage.ApplicationSession firstSession;
firstSession = DataStorage.Datastore.Instance.dbSQLite.Table<DataStorage.ApplicationSession>().OrderBy(v => v.SessionStart).Take(1).FirstOrDefault();
if (firstSession != null
&& DateTime.Compare(firstSession.SessionStart.AddDays(7), DateTime.Now) < 0)
{
SetUpdateStatus(UpdateStatusStates.UpdateAvailable);
}
}
}
public void OnUpdateStatusChanged(EventArgs e)
{
UpdateStatusChanged.CallEvents(this, e);
}
public static EventHandler InstallUpdateFromMainActivity = null;
public bool InstallUpdate()
2015-04-07 15:54:20 -07:00
{
string downloadToken = ApplicationSettings.Instance.get("CurrentBuildToken");
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("CurrentReleaseVersion");
string friendlyFileName = Path.Combine(updateFileLocation, "MatterControlSetup-{0}.{1}".FormatWith(releaseVersion, InstallerExtension));
#endif
2015-04-07 15:54:20 -07:00
if (System.IO.File.Exists(friendlyFileName))
{
System.IO.File.Delete(friendlyFileName);
}
2015-04-07 15:54:20 -07:00
try
{
//Change download file to friendly file name
System.IO.File.Move(updateFileName, friendlyFileName);
2015-04-08 18:09:37 -07:00
#if __ANDROID__
2015-04-07 15:54:20 -07:00
if (InstallUpdateFromMainActivity != null)
{
InstallUpdateFromMainActivity(this, null);
}
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 = MatterControlApplication.Instance as SystemWindow;
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();
2015-04-07 15:54:20 -07:00
if (System.IO.File.Exists(friendlyFileName))
{
System.IO.File.Delete(friendlyFileName);
}
}
2015-04-07 15:54:20 -07:00
return false;
}
}
2015-04-08 15:20:10 -07:00
}