Welcome to mirror list, hosted at ThFree Co, Russian Federation.

App.xaml.cs « NextcloudApp - github.com/nextcloud/windows-universal.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 3a8e2a9832d671e3a97ebc1cda75e2a256755cb6 (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.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Microsoft.Practices.Unity;
using Prism.Unity.Windows;
using Prism.Windows.AppModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Resources;
using Windows.Security.Credentials;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Newtonsoft.Json;
using NextcloudApp.Models;
using NextcloudApp.Services;
using NextcloudApp.Utils;
using NextcloudClient.Exceptions;
using NextcloudClient.Types;
using Prism.Windows.Mvvm;
using Microsoft.QueryStringDotNET;
using Windows.UI.Notifications;
using System.Diagnostics;

namespace NextcloudApp
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : PrismUnityApplication
    {
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            InitializeComponent();
            UnhandledException += OnUnhandledException;
        }

        private async void OnUnhandledException(object sender, UnhandledExceptionEventArgs args)
        {
            var exceptionStackTrace = string.Empty;
            try
            {
                exceptionStackTrace = args.Exception.StackTrace + "";
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch { }

            var exceptionMessage = args.Message;
            var exceptionType = string.Empty;
            var innerExceptionType = string.Empty;
            var exceptionHashCode = string.Empty;

            if (args.Exception != null)
            {
                // Tasks will throw a canceled exception if they get canceled
                // We don't care, but avoid closing the app
                if (args.Exception.GetType() == typeof(TaskCanceledException))
                {
                    args.Handled = true;
                    return;
                }
                if (args.Exception.GetType() == typeof(OperationCanceledException))
                {
                    args.Handled = true;
                    return;
                }
                if (args.Exception.GetType() == typeof(FileNotFoundException))
                {
                    args.Handled = true;
                    return;
                }
                // Temporary Workaround for WP10
                if (args.Exception.GetType() == typeof(ArgumentException))
                {
                    args.Handled = true;
                    return;
                }
                if (args.Exception.GetType() == typeof(ResponseError))
                {
                    args.Handled = true;
                    ResponseErrorHandlerService.HandleException((ResponseError)args.Exception);
                    return;
                }

                // 0x8000000B, E_BOUNDS, System.Exception, OutOfBoundsException
                if ((uint)args.Exception.HResult == 0x80004004)
                {
                    args.Handled = true;
                    return;
                }

                // 0x80072EE7, ERROR_WINHTTP_NAME_NOT_RESOLVED, The server name or address could not be resolved
                if ((uint)args.Exception.HResult == 0x80072EE7)
                {
                    args.Handled = true;
                    var resourceLoader = Container.Resolve<IResourceLoader>();
                    var dialogService = Container.Resolve<DialogService>();
                    var dialog = new ContentDialog
                    {
                        Title = resourceLoader.GetString("AnErrorHasOccurred"),
                        Content = new TextBlock
                        {
                            Text = resourceLoader.GetString("ServerNameOrAddressCouldNotBeResolved"),
                            TextWrapping = TextWrapping.WrapWholeWords,
                            Margin = new Thickness(0, 20, 0, 0)
                        },
                        PrimaryButtonText = resourceLoader.GetString("OK")
                    };
                    await dialogService.ShowAsync(dialog);
                    return;
                }

                exceptionType = args.Exception.GetType().ToString();
                if (args.Exception.InnerException != null)
                {
                    innerExceptionType = args.Exception.InnerException.GetType().ToString();
                }
                exceptionHashCode = string.IsNullOrEmpty(exceptionStackTrace)
                    ? args.Exception.GetHashCode().ToString()
                    : exceptionStackTrace.GetHashCode().ToString();
            }

            if (args.Handled)
            {
                return;
            }
            args.Handled = true;
            await
                ExceptionReportService.Handle(exceptionType, exceptionMessage, exceptionStackTrace,
                    innerExceptionType, exceptionHashCode);
        }

        protected override UIElement CreateShell(Frame rootFrame)
        {
            var shell = Container.Resolve<AppShell>();
            shell.SetContentFrame(rootFrame);
            return shell;
        }

        protected override Task OnSuspendingApplicationAsync()
        {
            var task = base.OnSuspendingApplicationAsync();
            // Stop Background Sync Tasks
            List<FolderSyncInfo> activeSyncs = SyncDbUtils.GetActiveSyncInfos();
            foreach(var fsi in activeSyncs)
            {
                ToastNotificationService.ShowSyncSuspendedNotification(fsi);
                SyncDbUtils.UnlockFolderSyncInfo(fsi);
            }
            return task;
        }

        protected override Task OnInitializeAsync(IActivatedEventArgs args)
        {
            Container.RegisterInstance(new DialogService());
            Container.RegisterInstance<IResourceLoader>(new ResourceLoaderAdapter(new ResourceLoader()));

            var task = base.OnInitializeAsync(args);

            DeviceGestureService.GoBackRequested += DeviceGestureServiceOnGoBackRequested;

            // Just count total app starts
            SettingsService.Instance.LocalSettings.AppTotalRuns = SettingsService.Instance.LocalSettings.AppTotalRuns + 1;

            // Count app starts after last update
            var currentVersion =
                $"{Package.Current.Id.Version.Major}.{Package.Current.Id.Version.Minor}.{Package.Current.Id.Version.Build}.{Package.Current.Id.Version.Revision}";
            if (currentVersion == SettingsService.Instance.LocalSettings.AppRunsAfterLastUpdateVersion)
            {
                SettingsService.Instance.LocalSettings.AppRunsAfterLastUpdate = SettingsService.Instance.LocalSettings.AppRunsAfterLastUpdate + 1;
            }
            else
            {
                SettingsService.Instance.LocalSettings.AppRunsAfterLastUpdateVersion = currentVersion;
                SettingsService.Instance.LocalSettings.AppRunsAfterLastUpdate = 1;
                SettingsService.Instance.LocalSettings.ShowUpdateMessage = true;
            }

            MigrationService.Instance.StartMigration();

            return task;
        }

        protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
        {
            if (
                string.IsNullOrEmpty(SettingsService.Instance.LocalSettings.ServerAddress) ||
                string.IsNullOrEmpty(SettingsService.Instance.LocalSettings.Username)
            )
            {
                NavigationService.Navigate(PageTokens.Login.ToString(), null);
            }
            else
            {
                var vault = new PasswordVault();

                IReadOnlyList<PasswordCredential> credentialList = null;
                try
                {
                    credentialList = vault.FindAllByResource(SettingsService.Instance.LocalSettings.ServerAddress);
                }
                catch
                {
                    // ignored
                }
                var credential = credentialList.FirstOrDefault(item => item.UserName.Equals(SettingsService.Instance.LocalSettings.Username));

                if (credential != null)
                {
                    credential.RetrievePassword();
                    if (!string.IsNullOrEmpty(credential.Password))
                    {
                        // Remove unnecessary notifications whenever the app is used.
                        ToastNotificationManager.History.RemoveGroup(ToastNotificationService.SYNCACTION);
                        PinStartPageParameters pageParameters = null;
                        if (!string.IsNullOrEmpty(args.Arguments))
                        {
                            var tmpResourceInfo = JsonConvert.DeserializeObject<ResourceInfo>(args.Arguments);
                            if (tmpResourceInfo != null)
                            {
                                pageParameters = new PinStartPageParameters()
                                {
                                    ResourceInfo = tmpResourceInfo,
                                    PageTarget = tmpResourceInfo.IsDirectory() ? PageTokens.DirectoryList.ToString() : PageTokens.FileInfo.ToString()
                                };

                            }
                        }

                        if (SettingsService.Instance.LocalSettings.UseWindowsHello)
                        {
                            NavigationService.Navigate(
                                PageTokens.Verification.ToString(),
                                pageParameters?.Serialize());
                        }
                        else
                        {
                            NavigationService.Navigate(
                                pageParameters!=null ? pageParameters.PageTarget : PageTokens.DirectoryList.ToString(), 
                                pageParameters?.Serialize());
                        }
                    }
                    else
                    {
                        NavigationService.Navigate(
                            PageTokens.Login.ToString(), 
                            null);
                    }
                }
                else
                {
                    NavigationService.Navigate(
                        PageTokens.Login.ToString(), 
                        null);
                }
            }

            // Ensure the current window is active
            Window.Current.Activate();
            
            return Task.FromResult(true);
        }

        protected override Task OnActivateApplicationAsync(IActivatedEventArgs e)
        {
            // Remove unnecessary notifications whenever the app is used.
            ToastNotificationManager.History.RemoveGroup(ToastNotificationService.SYNCACTION);
            // Handle toast activation
            if (e is ToastNotificationActivatedEventArgs)
            {
                var toastActivationArgs = e as ToastNotificationActivatedEventArgs;
                // Parse the query string
                QueryString args = QueryString.Parse(toastActivationArgs.Argument);
                // See what action is being requested 
                switch (args["action"])
                {
                    // Nothing to do here
                    case ToastNotificationService.SYNCACTION:
                        NavigationService.Navigate(PageTokens.DirectoryList.ToString(), null);
                        break;
                    // Open Conflict Page
                    case ToastNotificationService.SYNCONFLICTACTION:
                        ToastNotificationManager.History.RemoveGroup(ToastNotificationService.SYNCONFLICTACTION);
                        NavigationService.Navigate(PageTokens.SyncConflict.ToString(), null);
                        break;
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();
            return Task.FromResult(true);
        }

        private void DeviceGestureServiceOnGoBackRequested(object sender, DeviceGestureEventArgs e)
        {
            var appShell = (AppShell)Window.Current.Content;
            var contentFrame = (Frame)appShell.GetContentFrame();
            var page = (SessionStateAwarePage)contentFrame.Content;
            var revertable = page?.DataContext as IRevertState;
            if (revertable == null || !revertable.CanRevertState())
            {
                return;
            }
            e.Handled = true;
            e.Cancel = true;
            revertable.RevertState();
        }
    }
}