Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / Preferences / PreferencesViewModel.cs @ 6f03d6e1

History | View | Annotate | Download (19.7 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="PreferencesViewModel.cs" company="GRNet">
4
 * 
5
 * Copyright 2011-2012 GRNET S.A. All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or
8
 * without modification, are permitted provided that the following
9
 * conditions are met:
10
 *
11
 *   1. Redistributions of source code must retain the above
12
 *      copyright notice, this list of conditions and the following
13
 *      disclaimer.
14
 *
15
 *   2. Redistributions in binary form must reproduce the above
16
 *      copyright notice, this list of conditions and the following
17
 *      disclaimer in the documentation and/or other materials
18
 *      provided with the distribution.
19
 *
20
 *
21
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 * The views and conclusions contained in the software and
35
 * documentation are those of the authors and should not be
36
 * interpreted as representing official policies, either expressed
37
 * or implied, of GRNET S.A.
38
 * </copyright>
39
 * -----------------------------------------------------------------------
40
 */
41
#endregion
42

    
43

    
44
using System.Collections.Concurrent;
45
using System.Collections.Generic;
46
using System.ComponentModel.Composition;
47
using System.Diagnostics;
48
using System.IO;
49
using System.Reflection;
50
using System.Threading.Tasks;
51
using System.Windows;
52
using System.Windows.Forms;
53
using Caliburn.Micro;
54
using Pithos.Client.WPF.Configuration;
55
using Pithos.Client.WPF.Properties;
56
using Pithos.Client.WPF.SelectiveSynch;
57
using Pithos.Core;
58
using Pithos.Interfaces;
59
using System;
60
using System.Linq;
61
using Screen = Caliburn.Micro.Screen;
62

    
63
namespace Pithos.Client.WPF.Preferences
64
{
65
    /// <summary>
66
    /// The preferences screen displays user and account settings and updates the PithosMonitor
67
    /// classes when account settings change.
68
    /// </summary>
69
    /// <remarks>
70
    /// The class is a single ViewModel for all Preferences tabs. It can be broken in separate
71
    /// ViewModels, one for each tab.
72
    /// </remarks>
73
    [Export]
74
    public class PreferencesViewModel : Screen
75
    {
76
        private readonly IEventAggregator _events;
77

    
78
        //Logging in the Pithos client is provided by log4net
79
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
80

    
81
        private PithosSettings _settings;
82
        public PithosSettings Settings
83
        {
84
            get { return _settings; }
85
            set
86
            {
87
                _settings = value;
88
                NotifyOfPropertyChange(()=>Settings);
89
            }
90
        }
91

    
92
        private ObservableConcurrentCollection<AccountViewModel> _accounts;
93
        public ObservableConcurrentCollection<AccountViewModel> Accounts
94
        {
95
            get { return _accounts; }
96
            set 
97
            { 
98
                _accounts = value;
99
                NotifyOfPropertyChange(()=>Accounts);
100
            }
101
        }
102
        
103
        public bool StartOnSystemStartup { get; set; }
104

    
105
        public ShellViewModel Shell { get;  set; }
106
        //ShellExtensionController _extensionController=new ShellExtensionController();
107

    
108
        public PreferencesViewModel(IWindowManager windowManager, IEventAggregator events, ShellViewModel shell, PithosSettings settings, string currentTab)
109
        {
110
            // ReSharper disable DoNotCallOverridableMethodsInConstructor
111
            //Caliburn.Micro uses DisplayName for the view's title
112
            DisplayName = "Pithos Preferences";
113
            // ReSharper restore DoNotCallOverridableMethodsInConstructor
114

    
115
            _windowManager = windowManager;
116
            _events = events;
117

    
118
            Shell = shell;
119
            
120
            Settings=settings;
121
            Accounts = new ObservableConcurrentCollection<AccountViewModel>();
122
            if (settings.Accounts == null)
123
            {
124
                settings.Accounts=new AccountsCollection();
125
                settings.Save();
126
            }
127
            var accountVMs = from account in settings.Accounts
128
                             select new AccountViewModel(account);
129

    
130
            Accounts.AddFromEnumerable(accountVMs);
131
            
132
            var startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
133
            _shortcutPath = Path.Combine(startupPath, "Pithos.lnk");
134

    
135

    
136
            StartOnSystemStartup = File.Exists(_shortcutPath);
137

    
138
            SelectedTab = currentTab;
139
        }
140

    
141
        private string _selectedTab="General";
142
        public string SelectedTab
143
        {
144
            get { return _selectedTab; }
145
            set
146
            {
147
                _selectedTab = value??"General";
148
                NotifyOfPropertyChange(()=>SelectedTab);
149
                NotifyOfPropertyChange(() => AccountTabSelected);
150
            }
151
        }
152

    
153

    
154
        public bool AccountTabSelected
155
        {
156
            get { return _selectedTab == "AccountTab"; }
157
        }
158
        #region Preferences Properties
159

    
160
        private bool _noProxy;
161
        public bool NoProxy
162
        {
163
            get { return _noProxy; }
164
            set
165
            {
166
                _noProxy = value;
167
                NotifyOfPropertyChange(()=>NoProxy);
168
            }
169
        }
170

    
171

    
172
        private bool _defaultProxy;
173

    
174
        public bool DefaultProxy
175
        {
176
            get { return _defaultProxy; }
177
            set
178
            {
179
                _defaultProxy = value;
180
                NotifyOfPropertyChange(() => DefaultProxy);
181
            }
182
        }
183

    
184

    
185
        private bool _manualProxy;
186

    
187
        public bool ManualProxy
188
        {
189
            get { return _manualProxy; }
190
            set
191
            {
192
                _manualProxy = value;
193
                NotifyOfPropertyChange(() => ManualProxy);
194
            }
195
        }
196
        #endregion
197

    
198

    
199
        public int StartupDelay
200
        {
201
            get { return (int) Settings.StartupDelay.TotalMinutes; }
202
            set
203
            {
204
                if (value<0)
205
                    throw new ArgumentOutOfRangeException("value",Resources.PreferencesViewModel_StartupDelay_Greater_or_equal_to_0);
206
                Settings.StartupDelay = TimeSpan.FromMinutes(value);
207
                NotifyOfPropertyChange(()=>StartupDelay);
208
            }
209
        }
210
       
211
        #region Commands
212
        
213
        public bool CanSelectiveSyncFolders
214
        {
215
            get { return CurrentAccount != null; }
216
        }
217

    
218
        public void SelectiveSyncFolders()
219
        {
220
            var monitor = Shell.Monitors[CurrentAccount.AccountName];
221
            
222

    
223
            var model = new SelectiveSynchViewModel(monitor,_events,CurrentAccount.Account);
224
            if (_windowManager.ShowDialog(model) == true)
225
            {
226
                
227
            }
228
        }
229

    
230
        public async Task RefreshApiKey()
231
        {
232
            _events.Publish(new Notification { Title = "Authorization failed", Message = "Your API Key has probably expired. You will be directed to a page where you can renew it", Level = TraceLevel.Error });
233

    
234
            try
235
            {
236

    
237
                var credentials = await PithosAccount.RetrieveCredentials(Settings.PithosLoginUrl);
238
                //The server will return credentials for a different account, not just the current account
239
                //We need to find the correct account first
240
                var account = Accounts.First(act => act.AccountName == credentials.UserName);
241
                account.ApiKey = credentials.Password;                
242
                account.IsExpired = false;
243
                Settings.Save();
244
                TaskEx.Delay(10000).ContinueWith(_ =>Shell.MonitorAccount(account.Account));
245
                NotifyOfPropertyChange(() => Accounts);
246
            }
247
            catch (AggregateException exc)
248
            {
249
                string message = String.Format("API Key retrieval failed");
250
                Log.Error(message, exc.InnerException);
251
                _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
252
            }
253
            catch (Exception exc)
254
            {
255
                string message = String.Format("API Key retrieval failed");
256
                Log.Error(message, exc);
257
                _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
258
            }
259

    
260
        }
261

    
262
    
263
        public void OpenLogPath()
264
        {
265
            Shell.OpenLogPath();
266
        }
267

    
268
        public void OpenLogConsole()
269
        {
270
            var logView=IoC.Get<LogConsole.LogConsoleViewModel>();            
271
            _windowManager.ShowWindow(logView);
272
        }
273

    
274
        public void SaveChanges()
275
        {
276
            DoSave();
277
            TryClose(true);
278
        }
279

    
280
        public void RejectChanges()
281
        {
282
            Settings.Reload();
283
            TryClose(false);
284
        }
285

    
286
        public void ApplyChanges()
287
        {
288
            DoSave();
289
        }
290

    
291
        private void DoSave()
292
        {
293
            //SetStartupMode();            
294

    
295
            //Ensure we save the settings changes first
296
            foreach (var account in _accountsToRemove)
297
            {
298
                Settings.Accounts.Remove(account);
299
            }
300

    
301
            foreach (var account in _accountsToAdd)
302
            {
303
                Settings.Accounts.Add(account);    
304
            }
305
            
306
            Settings.Save();
307

    
308

    
309
            foreach (var account in _accountsToRemove)
310
            {
311
                Shell.RemoveMonitor(account.AccountName);
312
                Shell.RemoveAccountFromDatabase(account);
313
            }
314

    
315
            foreach (var account in Settings.Accounts)
316
            {                                
317
                Shell.MonitorAccount(account);
318
            }
319

    
320
            NotifyOfPropertyChange(()=>Settings);
321
        }
322

    
323
     /*   public void ChangePithosFolder()
324
        {
325
            var browser = new FolderBrowserDialog();
326
            browser.SelectedPath = Settings.PithosPath;
327
            var result = browser.ShowDialog((IWin32Window)GetView());
328
            if (result == DialogResult.OK)
329
            {
330
                var newPath = browser.SelectedPath;
331
                var accountName = CurrentAccount.AccountName;
332
                var monitor = Shell.Monitors[accountName];
333
                monitor.Stop();
334
                
335
                Shell.Monitors.Remove(accountName);
336

    
337
                Directory.Move(Settings.PithosPath, newPath);
338
                Settings.PithosPath = newPath;
339
                Settings.Save();
340

    
341
                Shell.MonitorAccount(CurrentAccount);
342

    
343
                NotifyOfPropertyChange(() => Settings);                
344
            }
345
        }
346
*/
347

    
348

    
349
        readonly List<AccountSettings> _accountsToAdd=new List<AccountSettings>();
350
       public void AddAccount()
351
       {
352
           var wizard = new AddAccountViewModel();
353
           if (_windowManager.ShowDialog(wizard) == true)
354
           {
355
               string selectedPath = wizard.AccountPath;
356
               var initialRootPath = wizard.ShouldCreateOkeanosFolder?
357
                   Path.Combine(selectedPath, "Okeanos")
358
                   :selectedPath;
359
               var actualRootPath= initialRootPath;
360
               if (wizard.ShouldCreateOkeanosFolder)
361
               {
362
                   int attempt = 1;
363
                   while (Directory.Exists(actualRootPath) || File.Exists(actualRootPath))
364
                   {
365
                       actualRootPath = String.Format("{0} {1}", initialRootPath, attempt++);
366
                   }
367
               }
368

    
369
               var newAccount = new AccountSettings
370
                                    {
371
                                        AccountName = wizard.AccountName,
372
                                        ServerUrl=wizard.CurrentServer,
373
                                        ApiKey=wizard.Token,
374
                                        RootPath = actualRootPath,
375
                                        IsActive=wizard.IsAccountActive
376
                                    };
377
               _accountsToAdd.Add(newAccount);
378
               var accountVm = new AccountViewModel(newAccount);
379
               (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVm);
380
               CurrentAccount = accountVm;
381
               NotifyOfPropertyChange(() => Accounts);
382
               NotifyOfPropertyChange(() => Settings);   
383
           }
384

    
385

    
386
            
387
       }
388

    
389
        public async void AddPithosAccount()
390
       {
391
            var credentials=await PithosAccount.RetrieveCredentials(Settings.PithosLoginUrl);
392
            var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
393
            var accountVM = new AccountViewModel(account);
394
            if (account == null)
395
            {
396
                account=new AccountSettings{
397
                    AccountName=credentials.UserName,
398
                    ApiKey=credentials.Password
399
                };
400
                Settings.Accounts.Add(account);
401
                accountVM = new AccountViewModel(account);
402
                (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVM);
403
            }
404
            else
405
            {
406
                account.ApiKey=credentials.Password;
407
            }
408
            //SelectedAccountIndex= Settings.Accounts.IndexOf(account);
409
            CurrentAccount = accountVM;
410
            NotifyOfPropertyChange(() => Accounts);
411
            NotifyOfPropertyChange(()=>Settings);                       
412
       }
413

    
414

    
415
        readonly List<AccountSettings> _accountsToRemove = new List<AccountSettings>();
416
        public void RemoveAccount()
417
        {
418
            Accounts.TryRemove(CurrentAccount);
419
            _accountsToRemove.Add(CurrentAccount.Account);
420

    
421
            CurrentAccount = null;
422
            NotifyOfPropertyChange(() => Accounts);
423

    
424
            
425
            //NotifyOfPropertyChange("Settings.Accounts");
426
        }
427

    
428
        public bool CanRemoveAccount
429
        {
430
            get { return (CurrentAccount != null); }
431
        }
432

    
433

    
434

    
435
        public bool ExtensionsActivated
436
        {
437
            get { return Settings.ExtensionsActivated; }
438
            set
439
            {
440
                if (Settings.ExtensionsActivated == value)
441
                    return;
442

    
443
                Settings.ExtensionsActivated = value;
444

    
445
/*
446
                if (value)
447
                    _extensionController.RegisterExtensions();
448
                else
449
                {
450
                    _extensionController.UnregisterExtensions();
451
                }
452
*/
453
                NotifyOfPropertyChange(() => ExtensionsActivated);
454
            }
455
        }
456

    
457
        public bool DebugLoggingEnabled
458
        {
459
            get { return Settings.DebugLoggingEnabled; }
460
            set { 
461
                Settings.DebugLoggingEnabled = value;
462
                NotifyOfPropertyChange(()=>DebugLoggingEnabled);
463
            }
464
        }
465
       
466
        #endregion
467

    
468
       /* private int _selectedAccountIndex;
469
        public int SelectedAccountIndex
470
        {
471
            get { return _selectedAccountIndex; }
472
            set
473
            {
474
                //var accountCount=Settings.Accounts.Count;
475
                //if (accountCount == 0)
476
                //    return;
477
                //if (0 <= value && value < accountCount)
478
                //    _selectedAccountIndex = value;
479
                //else
480
                //    _selectedAccountIndex = 0;
481
                _selectedAccountIndex = value;
482
                NotifyOfPropertyChange(() => CurrentAccount);
483
                NotifyOfPropertyChange(() => CanRemoveAccount);
484
                NotifyOfPropertyChange(()=>SelectedAccountIndex);
485
            }
486
        }*/
487

    
488
        private AccountViewModel _currentAccount;
489
        private readonly IWindowManager _windowManager;
490
        private readonly string _shortcutPath;
491

    
492

    
493
        
494
        public AccountViewModel CurrentAccount
495
        {
496
            get { return _currentAccount; }
497
            set
498
            {
499
                _currentAccount = value;
500
                NotifyOfPropertyChange(()=>CurrentAccount);
501
                NotifyOfPropertyChange(() => CanRemoveAccount);
502
                NotifyOfPropertyChange(() => CanSelectiveSyncFolders);
503
                NotifyOfPropertyChange(() => CanMoveAccountFolder);
504
            }
505
        }
506

    
507
/*
508
        public AccountSettings CurrentAccount
509
        {
510
            get {
511
                if (0 <= SelectedAccountIndex && SelectedAccountIndex < Settings.Accounts.Count)                    
512
                    return Settings.Accounts[SelectedAccountIndex];
513
                return null;
514
            }
515

    
516
        }
517
*/
518

    
519

    
520
        public bool CanMoveAccountFolder
521
        {
522
            get { return CurrentAccount != null; }
523
        }
524

    
525
    public void MoveAccountFolder()
526
    {
527

    
528
        using (var dlg = new FolderBrowserDialog())
529
        {
530
            var currentFolder = CurrentAccount.RootPath;
531
            dlg.SelectedPath = currentFolder;
532
            //Ask the user to select a folder
533
            //Note: We need a parent window here, which we retrieve with GetView            
534
            var view = (Window)GetView();            
535
            if (DialogResult.OK != dlg.ShowDialog(new Wpf32Window(view)))
536
                return;            
537

    
538
            var newPath= dlg.SelectedPath;                
539
            //Find the account's monitor and stop it
540
            PithosMonitor monitor;
541
            if (Shell.Monitors.TryGetValue(CurrentAccount.AccountName, out monitor))
542
            {
543
                monitor.Stop();
544

    
545

    
546
                var oldPath = monitor.RootPath;
547
                //The old directory may not exist eg. if we create an account for the first time
548
                if (Directory.Exists(oldPath))
549
                {
550
                    //If it does, do the move
551

    
552
                    //Now Create all of the directories
553
                    foreach (string dirPath in Directory.EnumerateDirectories(oldPath, "*",
554
                                                           SearchOption.AllDirectories))
555
                        Directory.CreateDirectory(dirPath.Replace(oldPath, newPath));
556

    
557
                    //Copy all the files
558
                    foreach (string newFilePath in Directory.EnumerateFiles(oldPath, "*.*",
559
                                                                            SearchOption.AllDirectories))
560
                        File.Copy(newFilePath, newFilePath.Replace(oldPath, newPath));
561

    
562
                    Directory.Delete(oldPath, true);
563

    
564
                    //We also need to change the path of the existing file states
565
                    monitor.MoveFileStates(oldPath, newPath);
566
                }
567
            }
568
            //Replace the old rootpath with the new
569
            CurrentAccount.RootPath = newPath;
570
            //TODO: This will save all settings changes. Too coarse grained, need to fix at a later date
571
            Settings.Save();            
572
            //And start the monitor on the new RootPath            
573
            if (monitor != null)
574
            {
575
                monitor.RootPath = newPath;
576
                if (CurrentAccount.IsActive)
577
                    monitor.Start();
578
            }
579
            else
580
                Shell.MonitorAccount(CurrentAccount.Account);
581
            //Finally, notify that the Settings, CurrentAccount have changed
582
            NotifyOfPropertyChange(() => CurrentAccount);
583
            NotifyOfPropertyChange(() => Settings);
584

    
585
        }
586
    }
587
    }
588
}