aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/FSE/Modules/Tango.FSE.PPCConsole/ViewModels/LogsViewVM.cs
blob: 4fcfa53ebbc8afc9ed36b068d0cf4011754e649b (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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using Tango.Core;
using Tango.Core.Commands;
using Tango.Core.Helpers;
using Tango.FSE.Common;
using Tango.FSE.Common.Connection;
using Tango.FSE.Common.Dialogs;
using Tango.FSE.Common.FileSystem;
using Tango.FSE.Common.Logging;
using Tango.Logging;
using Tango.PPC.Shared.Logs;
using Tango.SharedUI.Components;
using static Tango.SharedUI.Controls.NavigationControl;

namespace Tango.FSE.PPCConsole.ViewModels
{
    public class LogsViewVM : FSEViewModel, INavigationViewModel
    {
        private bool _loaded;

        private List<RemoteLogFileModel<LogItemBase>> _logFiles;
        /// <summary>
        /// Gets or sets the remote log files.
        /// </summary>
        public List<RemoteLogFileModel<LogItemBase>> LogFiles
        {
            get { return _logFiles; }
            set { _logFiles = value; RaisePropertyChangedAuto(); }
        }

        private RemoteLogFileModel<LogItemBase> _selectedLogFile;
        /// <summary>
        /// Gets or sets the selected remote log file.
        /// </summary>
        public RemoteLogFileModel<LogItemBase> SelectedLogFile
        {
            get { return _selectedLogFile; }
            set { _selectedLogFile = value; RaisePropertyChangedAuto(); OnSelectedLogFileChanged(); }
        }

        private ObservableCollection<LogItemBase> _applicationLogs;
        /// <summary>
        /// Gets or sets the application logs.
        /// </summary>
        public ObservableCollection<LogItemBase> ApplicationLogs
        {
            get { return _applicationLogs; }
            set { _applicationLogs = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets or sets the application logs view.
        /// </summary>
        public ICollectionView ApplicationLogsView { get; set; }

        /// <summary>
        /// Gets or sets the selected application logs categories.
        /// </summary>
        public SelectedObjectCollection<LogCategory> SelectedApplicationLogsCategories { get; set; }

        private String _applicationLogsFilter;
        /// <summary>
        /// Gets or sets the application logs filter.
        /// </summary>
        public String ApplicationLogsFilter
        {
            get { return _applicationLogsFilter; }
            set { _applicationLogsFilter = value; RaisePropertyChangedAuto(); ApplicationLogsView.Refresh(); }
        }

        /// <summary>
        /// Opens the detailed application log dialog.
        /// </summary>
        public RelayCommand<LogItemBase> OpenApplicationLogItemCommand { get; set; }

        /// <summary>
        /// Exports the selected log file to local disk.
        /// </summary>
        public RelayCommand ExportLogFileCommand { get; set; }

        /// <summary>
        /// Exports all the downloaded log files to disk.
        /// </summary>
        public RelayCommand ExportAllDownloadedLogFilesCommand { get; set; }

        /// <summary>
        /// Downloads all the available log files.
        /// </summary>
        public RelayCommand DownloadAllLogFilesCommand { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="LogsViewVM"/> class.
        /// </summary>
        public LogsViewVM()
        {
            ApplicationLogs = new ObservableCollection<LogItemBase>();
            InitCollectionView();

            SelectedApplicationLogsCategories = new SelectedObjectCollection<LogCategory>(new ObservableCollection<LogCategory>()
            {
                LogCategory.Info,
                LogCategory.Warning,
                LogCategory.Error,
                LogCategory.Critical,
            }, new ObservableCollection<LogCategory>()
            {
                LogCategory.Info,
                LogCategory.Warning,
                LogCategory.Error,
                LogCategory.Critical,
            });

            SelectedApplicationLogsCategories.SynchedSource.CollectionChanged += (_, __) => ApplicationLogsView.Refresh();

            OpenApplicationLogItemCommand = new RelayCommand<LogItemBase>(OpenApplicationLogItem);

            ExportLogFileCommand = new RelayCommand(ExportSelectedLogFile);
            ExportAllDownloadedLogFilesCommand = new RelayCommand(ExportAllDownloadedLogFiles);
            DownloadAllLogFilesCommand = new RelayCommand(DownloadAllLogFiles);
        }

        private void InitCollectionView()
        {
            ApplicationLogsView = CollectionViewSource.GetDefaultView(ApplicationLogs);
            ApplicationLogsView.Filter = FilterApplicationLogs;
        }

        public override void OnApplicationStarted()
        {
            base.OnApplicationStarted();
            MachineProvider.MachineConnected += MachineProvider_MachineConnected;
        }

        private void MachineProvider_MachineConnected(object sender, MachineConnectedEventArgs e)
        {
            if (e.DifferentFromPrevious)
            {
                _loaded = false;

                if (MachineProvider.ConnectionType.IsRemote() && IsVisible)
                {
                    LoadLogFiles();
                }
            }
        }

        public override void OnNavigatedTo()
        {
            base.OnNavigatedTo();

            if (!_loaded && MachineProvider.IsPPCAvailable)
            {
                LoadLogFiles();
            }
        }

        private async void LoadLogFiles()
        {
            if (!MachineProvider.ConnectionType.IsRemote() || !IsFree) return;

            try
            {
                IsFree = false;
                var logFiles = await LoggingProvider.GetApplicationLogFiles();
                LogFiles = logFiles.Select(x =>
                {

                    var model = new RemoteLogFileModel<LogItemBase>(new ApplicationLogFileParser());
                    model.RemoteLogFile = x;
                    model.DownloadCompleted += OnRemoteLogFileDownloadCompleted;
                    return model;

                }).ToList();
                SelectedLogFile = LogFiles.FirstOrDefault();
                _loaded = true;
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error loading log files.");
                NotificationProvider.PushErrorReportingSnackbar(ex, "PPC Module Error", "Could not initialize the remote PPC logs history.");
            }
            finally
            {
                IsFree = true;
            }
        }

        private void OnRemoteLogFileDownloadCompleted(object sender, EventArgs e)
        {
            if (SelectedLogFile == sender)
            {
                OnSelectedLogFileChanged();
            }
        }

        private void OnSelectedLogFileChanged()
        {
            if (SelectedLogFile == null) return;

            InvokeUI(() =>
            {
                ApplicationLogs = new ObservableCollection<LogItemBase>(SelectedLogFile.LogItems);
                InitCollectionView();
            });
        }

        private async void OpenApplicationLogItem(LogItemBase logItem)
        {
            await NotificationProvider.ShowDialog(new ApplicationLogItemViewVM() { LogItem = logItem });
        }

        private bool FilterApplicationLogs(object obj)
        {
            var log = obj as LogItemBase;
            return SelectedApplicationLogsCategories.SynchedSource.Contains(log.Category) && (String.IsNullOrWhiteSpace(ApplicationLogsFilter) || log.Message.ToLower().Contains(ApplicationLogsFilter.ToLower()));
        }

        private async void ExportSelectedLogFile()
        {
            if (SelectedLogFile != null && SelectedLogFile.Status == RemoteLogFileStatus.Downloaded)
            {
                var result = await StorageProvider.SaveFile("Export Log File", "Application Log Files|*.log", SelectedLogFile.RemoteLogFile.Name, ".log");
                if (result)
                {
                    using (NotificationProvider.PushTaskItem("Exporting log file..."))
                    {
                        try
                        {
                            File.Copy(SelectedLogFile.TemporaryFile, result.SelectedItem, true);
                            await NotificationProvider.ShowSuccess("Log file exported successfully.");
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex, "Error exporting application log file.");
                            await NotificationProvider.ShowError($"Could not export the log file.\n{ex.FlattenMessage()}");
                        }
                    }
                }
            }
            else
            {
                await NotificationProvider.ShowError("Please download the selected log file before trying to export.");
            }
        }

        private async void ExportAllDownloadedLogFiles()
        {
            var toExport = LogFiles.Where(x => x.Status == RemoteLogFileStatus.Downloaded).ToList();

            if (toExport.Count == 0)
            {
                await NotificationProvider.ShowError("Please download log files before trying to export.");
                return;
            }

            var result = await StorageProvider.SelectFolder("Export Log Files");
            if (result)
            {
                var count = toExport.Count;

                using (var task = NotificationProvider.PushTaskItem("Exporting log files..."))
                {
                    foreach (var logFile in toExport.ToList())
                    {
                        try
                        {
                            await Task.Delay(500);
                            File.Copy(logFile.TemporaryFile, Path.Combine(result.SelectedItem, logFile.RemoteLogFile.Name), true);
                            toExport.Remove(logFile);
                            task.UpdateProgress("Exporting log files...", count - toExport.Count, count, false);
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex, $"Error exporting application log file '{logFile.RemoteLogFile.Name}'.");
                            await NotificationProvider.ShowError($"Could not export '{logFile.RemoteLogFile.Name}'.\n{ex.FlattenMessage()}");
                        }
                    }
                }

                await NotificationProvider.ShowSuccess($"Successfully exported {count - toExport.Count} out of {count} log files.");
            }
        }

        private async void DownloadAllLogFiles()
        {
            var toDownload = LogFiles.Where(x => x.Status == RemoteLogFileStatus.None || x.Status == RemoteLogFileStatus.Failed).ToList();

            if (toDownload.Count == 0)
            {
                await NotificationProvider.ShowInfo("All log files have been downloaded.");
                return;
            }

            var totalSize = FileHelper.GetFriendlyFileSize(toDownload.Select(x => x.RemoteLogFile.Length).Sum());

            if (await NotificationProvider.ShowWarningQuestion($"Are you sure you wish to download the entire history of log files?\nTotal size: {totalSize}", "DOWNLOAD", "CANCEL"))
            {
                foreach (var logFile in toDownload)
                {
                    logFile.DownloadLogFile();
                }
            }
        }
    }
}