aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs
blob: f265c5dbfe7520c23c7d94c812fe8e563020cf7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
generated by cgit v1.3.1 (git 2.54.0) at 2026-06-30 13:12:37 +0000
 


} /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core.Commands;
using Tango.Core.Helpers;
using Tango.Explorer;
using Tango.PPC.Common;
using Tango.PPC.Common.MachineUpdate;
using Tango.PPC.UI.Dialogs;
using Tango.PPC.UI.ViewsContracts;

namespace Tango.PPC.UI.ViewModels
{
    public class MachineUpdateViewVM : PPCViewModel<IMachineUpdateView>
    {
        public enum MachineUpdateView
        {
            UpdateCheckView,
            UpdateCheckErrorView,
            UpdateAvailableView,
            UpToDateView,
            UpdateProgressView,
            UpdateDbProgressView,
            UpdateCompletedView,
            UpdateFailedView,
            UpdateFromPackageView,
            UpdateFailedFromPackageView,
        }

        private MachineUpdateResult _update_result;
        private DbCompareResult _db_compare_result;
        private bool _isChecking;

        #region Properties

        /// <summary>
        /// Gets or sets the machine update manager.
        /// </summary>
        public IMachineUpdateManager MachineUpdateManager { get; set; }

        private String _latestVersion;
        /// <summary>
        /// Gets or sets the latest version.
        /// </summary>
        public String LatestVersion
        {
            get { return _latestVersion; }
            set { _latestVersion = value; RaisePropertyChangedAuto(); }
        }

        private bool _isDbUpdate;
        /// <summary>
        /// Gets or sets a value indicating whether this instance is database update.
        /// </summary>
        public bool IsDbUpdate
        {
            get { return _isDbUpdate; }
            set { _isDbUpdate = value; RaisePropertyChangedAuto(); }
        }

        private String _failedError;
        /// <summary>
        /// Gets or sets the setup failed error.
        /// </summary>
        public String FailedError
        {
            get { return _failedError; }
            set { _failedError = value; RaisePropertyChangedAuto(); }
        }

        #endregion

        #region Commands

        /// <summary>
        /// Gets or sets the complete command.
        /// </summary>
        public RelayCommand CompleteCommand { get; set; }

        /// <summary>
        /// Gets or sets the install command.
        /// </summary>
        public RelayCommand UpdateCommand { get; set; }

        /// <summary>
        /// Gets or sets the restart command.
        /// </summary>
        public RelayCommand RestartCommand { get; set; }

        /// <summary>
        /// Gets or sets the close command.
        /// </summary>
        public RelayCommand CloseCommand { get; set; }

        /// <summary>
        /// Gets or sets to application command.
        /// </summary>
        public RelayCommand ToApplicationCommand { get; set; }

        #endregion

        #region Constructors

        public MachineUpdateViewVM(IMachineUpdateManager machineUpdateManager)
        {
            MachineUpdateManager = machineUpdateManager;

            CompleteCommand = new RelayCommand(CompleteUpdate);
            UpdateCommand = new RelayCommand(Update);
            RestartCommand = new RelayCommand(CheckForUpdates);
            CloseCommand = new RelayCommand(() =>
            {
                NavigationManager.NavigateTo(Common.Navigation.NavigationView.HomeModule);
                NavigateTo(MachineUpdateView.UpdateCheckView);
            });

            ToApplicationCommand = new RelayCommand(() =>
            {
                NavigationManager.NavigateTo(Common.Navigation.NavigationView.HomeModule);
                NavigateTo(MachineUpdateView.UpdateCheckView);
            });
        }

        #endregion

        #region Update

        public async void CheckForUpdates()
        {
            await NavigateTo(MachineUpdateView.UpdateCheckView);

            if (_isChecking) return;

            try
            {
                _isChecking = true;
                IsDbUpdate = false;

                await Task.Delay(2000);
                if (!await ConnectivityProvider.CheckInternetConnection())
                {
                    _isChecking = false;
                    await NavigateTo(MachineUpdateView.UpdateCheckErrorView);
                    return;
                }

                var response = await MachineUpdateManager.CheckForUpdate(MachineProvider.Machine.SerialNumber);

                if (response.IsUpdateAvailable)
                {
                    LatestVersion = response.Version;
                    await NavigateTo(MachineUpdateView.UpdateAvailableView);
                }
                else
                {
                    _db_compare_result = await MachineUpdateManager.UpdateDBCheck(MachineProvider.Machine.SerialNumber);

                    if (_db_compare_result.RequiresUpdate)
                    {
                        IsDbUpdate = true;
                        await NavigateTo(MachineUpdateView.UpdateAvailableView);
                    }
                    else
                    {
                        await NavigateTo(MachineUpdateView.UpToDateView);
                    }
                }
            }
            catch (Exception ex)
            {
                FailedError = ex.FlattenMessage();
                LogManager.Log(ex, "Error while trying to check for updates.");
                await NavigateTo(MachineUpdateView.UpdateFailedView);
            }
            finally
            {
                _isChecking = false;
            }
        }

        private async void Update()
        {
            if (!IsDbUpdate)
            {
                await NavigateTo(MachineUpdateView.UpdateProgressView);

                LogManager.Log("Starting machine update...");

                try
                {
                    _update_result = await MachineUpdateManager.Update(MachineProvider.Machine.SerialNumber);
                    LogManager.Log("Machine update completed.");
                    await NavigateTo(MachineUpdateView.UpdateCompletedView);
                }
                catch (Exception ex)
                {
                    FailedError = ex.FlattenMessage();
                    LogManager.Log(ex, "Machine update failed.");
                    await NavigateTo(MachineUpdateView.UpdateFailedView);
                }
            }
            else
            {
                await NavigateTo(MachineUpdateView.UpdateDbProgressView);
                LogManager.Log("Starting database update...");

                try
                {
                    await MachineUpdateManager.UpdateDB(_db_compare_result, MachineProvider.Machine.SerialNumber);
                    LogManager.Log("Database update completed.");
                    await NavigateTo(MachineUpdateView.UpdateCompletedView);
                }
                catch (Exception ex)
                {
                    FailedError = ex.FlattenMessage();
                    LogManager.Log(ex, "Database update failed.");
                    await NavigateTo(MachineUpdateView.UpdateFailedView);
                }
            }
        }

        #endregion

        #region Complete

        private void CompleteUpdate()
        {
            LogManager.Log("Completing machine update...");

            if (!IsDbUpdate)
            {
                String updater_exe = Path.Combine(_update_result.UpdatePackagePath, "Tango.PPC.Updater.exe");
                ApplicationManager.UpdateApplication(updater_exe, PathHelper.GetStartupPath());
            }
            else
            {
                LogManager.Log("Restarting Application...");
                ApplicationManager.Restart();
            }
        }

        #endregion

        #region Override Methods

        /// <summary>
        /// Called when the application has been started.
        /// </summary>
        public override void OnApplicationStarted()
        {

        }

        /// <summary>
        /// Navigates to the specified view.
        /// </summary>
        /// <param name="view">The view.</param>
        private Task NavigateTo(MachineUpdateView view)
        {
            return View.NavigateTo(view);
        }

        /// <summary>
        /// Called when the application is ready and all modules views are loaded.
        /// </summary>
        public override void OnApplicationReady()
        {
            base.OnApplicationReady();

            StorageProvider.RegisterFileHandler(ExplorerFileDefinition.Update.Extension, HandleSoftwareUpdatePackageLoaded);
        }

        #endregion

        #region Handle USB Update

        private async void HandleSoftwareUpdatePackageLoaded(ExplorerFileItem fileItem)
        {
            UpdatePackageFile packageFile = null;

            try
            {
                packageFile = await MachineUpdateManager.GetUpdatePackageFileInfo(fileItem.Path);
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, $"Error loading update package file from {fileItem.Path}.");
                await NotificationProvider.ShowError("An error occurred while trying to load the selected software update package. Please make sure the package is valid.");
                return;
            }

            if (ApplicationManager.Version <= packageFile.Version)
            {
                await NotificationProvider.ShowError($"The selected update package (v{packageFile.Version.ToString()}) contains an older software version.");
                return;
            }

            UpdateFromFileViewVM vm = new UpdateFromFileViewVM();
            vm.Version = packageFile.Version.ToString();

            await NotificationProvider.ShowDialog(vm);

            if (vm.DialogResult)
            {
                await NavigationManager.NavigateTo(Common.Navigation.NavigationView.MachineUpdateView);
                await NavigateTo(MachineUpdateView.UpdateFromPackageView);

                LogManager.Log("Starting machine update from package...");

                try
                {
                    _update_result = await MachineUpdateManager.UpdateFromTUP(fileItem.Path);
                    LogManager.Log("Machine update from package completed.");
                    await NavigateTo(MachineUpdateView.UpdateCompletedView);
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Machine update from package failed.");
                    await NavigateTo(MachineUpdateView.UpdateFailedFromPackageView);
                }
            }
        }

        #endregion
    }
}