aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs
blob: 4cc4ee46f46021e6dd0ea60a30410872e6d6859a (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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.Common.Web;
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;
        private CheckForUpdateResponse _checkUpdateResponse;

        #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);
                _checkUpdateResponse = response;

                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, _checkUpdateResponse.SetupFirmware, _checkUpdateResponse.SetupFPGA);
                    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);

            if (ApplicationManager.IsAfterUpdate)
            {
                RunPostUpdatePackages();
            }
        }

        #endregion

        #region Post Update Packages

        private async void RunPostUpdatePackages()
        {
            await Task.Delay(1000);

            LogManager.Log("Application was loaded after an update. Checking for required post-update packages...");

            bool required = false;

            try
            {
                required = await MachineUpdateManager.PostUpdatePackagesRequired();
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error checking for post-update packages.");
            }

            if (required)
            {
                LogManager.Log("Post-update packages found and needs to be installed. Navigating to machine update and running post-update packages...");
                await NavigationManager.NavigateTo(Common.Navigation.NavigationView.MachineUpdateView);
                await NavigateTo(MachineUpdateView.UpdateProgressView);
                try
                {
                    var result = await MachineUpdateManager.RunPostUpdatePackages();

                    LogManager.Log("Post-update packages installed successfully.");

                    await Task.Delay(2000);

                    if (result.RestartRequired)
                    {
                        LogManager.Log("Restart required. Restarting...");
                        ApplicationManager.Restart();
                    }
                    else
                    {
                        await NavigationManager.NavigateTo(Common.Navigation.NavigationView.LayoutView);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Error occurred while running post-update packages.");
                }
            }
            else
            {
                LogManager.Log("No post-update packages installation required.");
            }
        }

        #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
    }
}