Statistics
| Branch: | Revision:

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

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

    
263
        }
264

    
265
    
266
        public void OpenLogPath()
267
        {
268
            Shell.OpenLogPath();
269
        }
270

    
271
        public void OpenLogConsole()
272
        {
273
            var logView=IoC.Get<LogConsole.LogConsoleViewModel>();            
274
            _windowManager.ShowWindow(logView);
275
        }
276

    
277
        public void SaveChanges()
278
        {
279
            DoSave();
280
            TryClose(true);
281
        }
282

    
283
        public void RejectChanges()
284
        {
285
            Settings.Reload();
286
            TryClose(false);
287
        }
288

    
289
        public void ApplyChanges()
290
        {
291
            DoSave();
292
        }
293

    
294
        private void DoSave()
295
        {
296
            //SetStartupMode();            
297

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

    
304
            foreach (var account in _accountsToAdd)
305
            {
306
                Settings.Accounts.Add(account);    
307
            }
308

    
309
            Settings.Save();
310

    
311

    
312
            try
313
            {
314
                foreach (var account in _accountsToRemove)
315
                {
316
                    Shell.RemoveMonitor(account.AccountName);
317
                    Shell.RemoveAccountFromDatabase(account);
318
                }
319

    
320
                foreach (var account in Settings.Accounts)
321
                {
322
                    Shell.MonitorAccount(account);
323
                }
324
            }                
325
            finally
326
            {
327
                _accountsToRemove.Clear();
328
                _accountsToAdd.Clear();
329
            }
330

    
331
            NotifyOfPropertyChange(()=>Settings);
332
        }
333

    
334
     /*   public void ChangePithosFolder()
335
        {
336
            var browser = new FolderBrowserDialog();
337
            browser.SelectedPath = Settings.PithosPath;
338
            var result = browser.ShowDialog((IWin32Window)GetView());
339
            if (result == DialogResult.OK)
340
            {
341
                var newPath = browser.SelectedPath;
342
                var accountName = CurrentAccount.AccountName;
343
                var monitor = Shell.Monitors[accountName];
344
                monitor.Stop();
345
                
346
                Shell.Monitors.Remove(accountName);
347

    
348
                Directory.Move(Settings.PithosPath, newPath);
349
                Settings.PithosPath = newPath;
350
                Settings.Save();
351

    
352
                Shell.MonitorAccount(CurrentAccount);
353

    
354
                NotifyOfPropertyChange(() => Settings);                
355
            }
356
        }
357
*/
358

    
359

    
360
        readonly List<AccountSettings> _accountsToAdd=new List<AccountSettings>();
361
       public void AddAccount()
362
       {
363
           var wizard = new AddAccountViewModel();
364
           if (_windowManager.ShowDialog(wizard) == true)
365
           {
366
               string selectedPath = wizard.AccountPath;
367
               var initialRootPath = wizard.ShouldCreateOkeanosFolder?
368
                   Path.Combine(selectedPath, "Okeanos")
369
                   :selectedPath;
370
               var actualRootPath= initialRootPath;
371
               if (wizard.ShouldCreateOkeanosFolder)
372
               {
373
                   int attempt = 1;
374
                   while (Directory.Exists(actualRootPath) || File.Exists(actualRootPath))
375
                   {
376
                       actualRootPath = String.Format("{0} {1}", initialRootPath, attempt++);
377
                   }
378
               }
379

    
380
               var newAccount = new AccountSettings
381
                                    {
382
                                        AccountName = wizard.AccountName,
383
                                        ServerUrl=wizard.CurrentServer,
384
                                        ApiKey=wizard.Token,
385
                                        RootPath = actualRootPath,
386
                                        IsActive=wizard.IsAccountActive
387
                                    };
388
               _accountsToAdd.Add(newAccount);
389
               var accountVm = new AccountViewModel(newAccount);
390
               (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVm);
391
               CurrentAccount = accountVm;
392
               NotifyOfPropertyChange(() => Accounts);
393
               NotifyOfPropertyChange(() => Settings);   
394
           }
395

    
396

    
397
            
398
       }
399

    
400
        public void AddPithosAccount()
401
       {
402
            var credentials=PithosAccount.RetrieveCredentials(Settings.PithosLoginUrl);
403
            if (credentials == null)
404
                return;
405
            var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
406
            var accountVM = new AccountViewModel(account);
407
            if (account == null)
408
            {
409
                account=new AccountSettings{
410
                    AccountName=credentials.UserName,
411
                    ApiKey=credentials.Password
412
                };
413
                Settings.Accounts.Add(account);
414
                accountVM = new AccountViewModel(account);
415
                (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVM);
416
            }
417
            else
418
            {
419
                account.ApiKey=credentials.Password;
420
            }
421
            //SelectedAccountIndex= Settings.Accounts.IndexOf(account);
422
            CurrentAccount = accountVM;
423
            NotifyOfPropertyChange(() => Accounts);
424
            NotifyOfPropertyChange(()=>Settings);                       
425
       }
426

    
427

    
428
        readonly List<AccountSettings> _accountsToRemove = new List<AccountSettings>();
429
        public void RemoveAccount()
430
        {
431
            Accounts.TryRemove(CurrentAccount);
432
            _accountsToRemove.Add(CurrentAccount.Account);
433

    
434
            CurrentAccount = null;
435
            NotifyOfPropertyChange(() => Accounts);
436

    
437
            
438
            //NotifyOfPropertyChange("Settings.Accounts");
439
        }
440

    
441
        public bool CanRemoveAccount
442
        {
443
            get { return (CurrentAccount != null); }
444
        }
445

    
446

    
447

    
448
        public bool ExtensionsActivated
449
        {
450
            get { return Settings.ExtensionsActivated; }
451
            set
452
            {
453
                if (Settings.ExtensionsActivated == value)
454
                    return;
455

    
456
                Settings.ExtensionsActivated = value;
457

    
458
/*
459
                if (value)
460
                    _extensionController.RegisterExtensions();
461
                else
462
                {
463
                    _extensionController.UnregisterExtensions();
464
                }
465
*/
466
                NotifyOfPropertyChange(() => ExtensionsActivated);
467
            }
468
        }
469

    
470
        public bool DebugLoggingEnabled
471
        {
472
            get { return Settings.DebugLoggingEnabled; }
473
            set { 
474
                Settings.DebugLoggingEnabled = value;
475
                NotifyOfPropertyChange(()=>DebugLoggingEnabled);
476
            }
477
        }
478
       
479
        #endregion
480

    
481
       /* private int _selectedAccountIndex;
482
        public int SelectedAccountIndex
483
        {
484
            get { return _selectedAccountIndex; }
485
            set
486
            {
487
                //var accountCount=Settings.Accounts.Count;
488
                //if (accountCount == 0)
489
                //    return;
490
                //if (0 <= value && value < accountCount)
491
                //    _selectedAccountIndex = value;
492
                //else
493
                //    _selectedAccountIndex = 0;
494
                _selectedAccountIndex = value;
495
                NotifyOfPropertyChange(() => CurrentAccount);
496
                NotifyOfPropertyChange(() => CanRemoveAccount);
497
                NotifyOfPropertyChange(()=>SelectedAccountIndex);
498
            }
499
        }*/
500

    
501
        private AccountViewModel _currentAccount;
502
        private readonly IWindowManager _windowManager;
503
        private readonly string _shortcutPath;
504

    
505

    
506
        
507
        public AccountViewModel CurrentAccount
508
        {
509
            get { return _currentAccount; }
510
            set
511
            {
512
                _currentAccount = value;
513
                NotifyOfPropertyChange(()=>CurrentAccount);
514
                NotifyOfPropertyChange(() => CanRemoveAccount);
515
                NotifyOfPropertyChange(() => CanSelectiveSyncFolders);
516
                NotifyOfPropertyChange(() => CanMoveAccountFolder);
517
            }
518
        }
519

    
520
/*
521
        public AccountSettings CurrentAccount
522
        {
523
            get {
524
                if (0 <= SelectedAccountIndex && SelectedAccountIndex < Settings.Accounts.Count)                    
525
                    return Settings.Accounts[SelectedAccountIndex];
526
                return null;
527
            }
528

    
529
        }
530
*/
531

    
532

    
533
        public bool CanMoveAccountFolder
534
        {
535
            get { return CurrentAccount != null; }
536
        }
537

    
538
    public void MoveAccountFolder()
539
    {
540

    
541
        using (var dlg = new FolderBrowserDialog())
542
        {
543
            var currentFolder = CurrentAccount.RootPath;
544
            dlg.SelectedPath = currentFolder;
545
            //Ask the user to select a folder
546
            //Note: We need a parent window here, which we retrieve with GetView            
547
            var view = (Window)GetView();            
548
            if (DialogResult.OK != dlg.ShowDialog(new Wpf32Window(view)))
549
                return;            
550

    
551
            var newPath= dlg.SelectedPath;                
552
            //Find the account's monitor and stop it
553
            PithosMonitor monitor;
554
            if (Shell.Monitors.TryGetValue(CurrentAccount.AccountName, out monitor))
555
            {
556
                monitor.Stop();
557

    
558

    
559
                var oldPath = monitor.RootPath;
560
                //The old directory may not exist eg. if we create an account for the first time
561
                if (Directory.Exists(oldPath))
562
                {
563
                    //If it does, do the move
564

    
565
                    //Now Create all of the directories
566
                    foreach (string dirPath in Directory.EnumerateDirectories(oldPath, "*",
567
                                                           SearchOption.AllDirectories))
568
                        Directory.CreateDirectory(dirPath.Replace(oldPath, newPath));
569

    
570
                    //Copy all the files
571
                    foreach (string newFilePath in Directory.EnumerateFiles(oldPath, "*.*",
572
                                                                            SearchOption.AllDirectories))
573
                        File.Copy(newFilePath, newFilePath.Replace(oldPath, newPath));
574

    
575
                    Directory.Delete(oldPath, true);
576

    
577
                    //We also need to change the path of the existing file states
578
                    monitor.MoveFileStates(oldPath, newPath);
579
                }
580
            }
581
            //Replace the old rootpath with the new
582
            CurrentAccount.RootPath = newPath;
583
            //TODO: This will save all settings changes. Too coarse grained, need to fix at a later date
584
            Settings.Save();            
585
            //And start the monitor on the new RootPath            
586
            if (monitor != null)
587
            {
588
                monitor.RootPath = newPath;
589
                if (CurrentAccount.IsActive)
590
                    monitor.Start();
591
            }
592
            else
593
                Shell.MonitorAccount(CurrentAccount.Account);
594
            //Finally, notify that the Settings, CurrentAccount have changed
595
            NotifyOfPropertyChange(() => CurrentAccount);
596
            NotifyOfPropertyChange(() => Settings);
597

    
598
        }
599
    }
600
    }
601
}