Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / Preferences / PreferencesViewModel.cs @ 2475642e

History | View | Annotate | Download (28.5 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.Collections.Specialized;
47
using System.ComponentModel.Composition;
48
using System.Diagnostics;
49
using System.IO;
50
using System.Net;
51
using System.Reflection;
52
using System.Threading.Tasks;
53
using System.Windows;
54
using System.Windows.Forms;
55
using Caliburn.Micro;
56
using Pithos.Client.WPF.Configuration;
57
using Pithos.Client.WPF.Properties;
58
using Pithos.Client.WPF.SelectiveSynch;
59
using Pithos.Client.WPF.Utils;
60
using Pithos.Core;
61
using Pithos.Core.Agents;
62
using Pithos.Interfaces;
63
using System;
64
using System.Linq;
65
using Pithos.Network;
66
using MessageBox = System.Windows.MessageBox;
67
using Screen = Caliburn.Micro.Screen;
68

    
69
namespace Pithos.Client.WPF.Preferences
70
{
71
    /// <summary>
72
    /// The preferences screen displays user and account settings and updates the PithosMonitor
73
    /// classes when account settings change.
74
    /// </summary>
75
    /// <remarks>
76
    /// The class is a single ViewModel for all Preferences tabs. It can be broken in separate
77
    /// ViewModels, one for each tab.
78
    /// </remarks>
79
    [Export, PartCreationPolicy(CreationPolicy.Shared)]
80
    public class PreferencesViewModel : Screen
81
    {
82
        private readonly IEventAggregator _events;
83

    
84
        //Logging in the Pithos client is provided by log4net
85
        private static readonly log4net.ILog Log =
86
            log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
87

    
88
        private PithosSettings _settings;
89

    
90
        public PithosSettings Settings
91
        {
92
            get { return _settings; }
93
            set
94
            {
95
                _settings = value;
96
                NotifyOfPropertyChange(() => Settings);
97
            }
98
        }
99

    
100
        private ObservableConcurrentCollection<AccountViewModel> _accounts;
101

    
102
        public ObservableConcurrentCollection<AccountViewModel> Accounts
103
        {
104
            get { return _accounts; }
105
            set
106
            {
107
                _accounts = value;
108
                NotifyOfPropertyChange(() => Accounts);
109
            }
110
        }
111

    
112
        public bool StartOnSystemStartup { get; set; }
113

    
114
        public ShellViewModel Shell { get; set; }
115
        //ShellExtensionController _extensionController=new ShellExtensionController();
116

    
117
        [ImportingConstructor]
118
        public PreferencesViewModel(IWindowManager windowManager, IEventAggregator events, ShellViewModel shell,
119
                                    PithosSettings settings)
120
        {
121
            this.DisplayName = "Pithos+ Preferences";
122

    
123
            // ReSharper disable DoNotCallOverridableMethodsInConstructor
124
            //Caliburn.Micro uses DisplayName for the view's title
125
            DisplayName = "Pithos+ Preferences";
126
            // ReSharper restore DoNotCallOverridableMethodsInConstructor
127

    
128
            _windowManager = windowManager;
129
            _events = events;
130

    
131
            Shell = shell;
132

    
133
            Settings = settings;
134
            Accounts = new ObservableConcurrentCollection<AccountViewModel>();
135

    
136

    
137
            var startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
138
            _shortcutPath = Path.Combine(startupPath, "Pithos.lnk");
139

    
140

    
141
            StartOnSystemStartup = File.Exists(_shortcutPath);
142

    
143
            //SelectedTab = currentTab;
144
        }
145

    
146
        protected override void OnViewLoaded(object view)
147
        {
148
            base.OnViewLoaded(view);
149

    
150
            Settings.Reload();
151

    
152
            Accounts.Clear();
153

    
154
            if (Settings.Accounts == null)
155
            {
156
                Settings.Accounts = new AccountsCollection();
157
                Settings.Save();
158
            }
159
            var accountVMs = from account in Settings.Accounts
160
                             select new AccountViewModel(account);
161

    
162
            Accounts.AddFromEnumerable(accountVMs);
163
            if (Accounts.Count > 0)
164
                CurrentAccount = Accounts.First();
165

    
166
        }
167

    
168
        private string _selectedTab = "General";
169

    
170
        public string SelectedTab
171
        {
172
            get { return _selectedTab; }
173
            set
174
            {
175
                _selectedTab = value ?? "GeneralTab";
176
                NotifyOfPropertyChange(() => SelectedTab);
177
                NotifyOfPropertyChange(() => AccountTabSelected);
178
            }
179
        }
180

    
181

    
182
        public bool AccountTabSelected
183
        {
184
            get { return _selectedTab == "AccountTab"; }
185
        }
186

    
187
        #region Preferences Properties
188

    
189
        private bool _noProxy;
190

    
191
        public bool NoProxy
192
        {
193
            get { return _noProxy; }
194
            set
195
            {
196
                _noProxy = value;
197
                NotifyOfPropertyChange(() => NoProxy);
198
            }
199
        }
200

    
201

    
202
        private bool _defaultProxy;
203

    
204
        public bool DefaultProxy
205
        {
206
            get { return _defaultProxy; }
207
            set
208
            {
209
                _defaultProxy = value;
210
                NotifyOfPropertyChange(() => DefaultProxy);
211
            }
212
        }
213

    
214

    
215
        private bool _manualProxy;
216

    
217
        public bool ManualProxy
218
        {
219
            get { return _manualProxy; }
220
            set
221
            {
222
                _manualProxy = value;
223
                NotifyOfPropertyChange(() => ManualProxy);
224
            }
225
        }
226

    
227
        #endregion
228

    
229

    
230
        public int StartupDelay
231
        {
232
            get { return (int) Settings.StartupDelay.TotalMinutes; }
233
            set
234
            {
235
                if (value < 0)
236
                    throw new ArgumentOutOfRangeException("value",
237
                                                          Resources.
238
                                                              PreferencesViewModel_StartupDelay_Greater_or_equal_to_0);
239
                Settings.StartupDelay = TimeSpan.FromMinutes(value);
240
                NotifyOfPropertyChange(() => StartupDelay);
241
            }
242
        }
243

    
244
        #region Commands
245

    
246
        public bool CanSelectiveSyncFolders
247
        {
248
            get { return CurrentAccount != null && CurrentAccount.SelectiveSyncEnabled; }
249
        }
250

    
251
        public void SelectiveSyncFolders()
252
        {
253
            //var monitor = Shell.Monitors[CurrentAccount.AccountKey];
254

    
255

    
256
            var model = new SelectiveSynchViewModel(_events, CurrentAccount.Account, CurrentAccount.ApiKey, false);
257
            if (_windowManager.ShowDialog(model) == true)
258
            {
259

    
260
            }
261
        }
262

    
263
        /* private bool _networkTracing;
264
        public bool NetworkTracing
265
        {
266
            get { return _networkTracing; }
267
            set
268
            {
269
                _networkTracing = value;
270
                
271
            }
272
        }*/
273

    
274
        public void RefreshApiKey()
275
        {
276
            //_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 });
277
            if (CurrentAccount == null)
278
                return;
279
            try
280
            {
281

    
282
                var name = CurrentAccount.AccountName;
283

    
284
                var loginUri = new Uri(CurrentAccount.ServerUrl).Combine("login");
285
                var credentials = PithosAccount.RetrieveCredentials(loginUri.ToString(), name);
286
                if (credentials == null)
287
                    return;
288
                //The server will return credentials for a different account, not just the current account
289
                //We need to find the correct account first
290
                var account =
291
                    Accounts.First(
292
                        act => act.AccountName == credentials.UserName && act.ServerUrl == CurrentAccount.ServerUrl);
293
                account.ApiKey = credentials.Password;
294
                account.IsExpired = false;
295
                Settings.Save();
296
                TaskEx.Delay(10000).ContinueWith(_ => Shell.MonitorAccount(account.Account));
297
                NotifyOfPropertyChange(() => Accounts);
298
            }
299
            catch (AggregateException exc)
300
            {
301
                string message = String.Format("API Key retrieval failed");
302
                Log.Error(message, exc.InnerException);
303
                _events.Publish(new Notification
304
                                    {Title = "Authorization failed", Message = message, Level = TraceLevel.Error});
305
            }
306
            catch (Exception exc)
307
            {
308
                string message = String.Format("API Key retrieval failed");
309
                Log.Error(message, exc);
310
                _events.Publish(new Notification
311
                                    {Title = "Authorization failed", Message = message, Level = TraceLevel.Error});
312
            }
313

    
314
        }
315

    
316
        public bool CanWipeAccount
317
        {
318
            get { return CurrentAccount != null 
319
                && Shell.Monitors.ContainsKey(CurrentAccount.AccountKey)
320
                && Shell.Monitors[CurrentAccount.AccountKey].CloudClient!=null;
321
            }
322
        }
323

    
324
        public async void WipeAccount()
325
        {
326
            PithosMonitor aMonitor;
327
            if (Shell.Monitors.TryGetValue(CurrentAccount.AccountKey, out aMonitor))
328
            {
329
                if (aMonitor.CloudClient == null)
330
                {
331
                    Log.ErrorFormat("Tried to wipe account [{0}] before authenticating",CurrentAccount.AccountKey);
332
                    return;
333
                }
334
                var message = String.Format("You are about to wipe all data in the {0} account at {1}. Are you sure?",
335
                                            CurrentAccount.AccountName, CurrentAccount.ServerUrl);
336
                if (MessageBoxResult.Yes !=
337
                    MessageBox.Show(message, "Warning! Account data will be wiped", MessageBoxButton.YesNo,
338
                                    MessageBoxImage.Hand, MessageBoxResult.No))
339
                    return;      
340
                          
341
                await aMonitor.CloudClient.WipeContainer("", new Uri("pithos", UriKind.Relative));
342
                aMonitor.Stop();
343
                await aMonitor.Start();
344
                MessageBox.Show("Account wiped");
345
            }
346
        }
347

    
348

    
349
        public void OpenLogPath()
350
        {
351
            Shell.OpenLogPath();
352
        }
353

    
354
        public void OpenLogConsole()
355
        {
356
            var logView = IoC.Get<LogConsole.LogConsoleViewModel>();
357
            _windowManager.ShowWindow(logView);
358
        }
359

    
360
        public void SaveChanges()
361
        {
362
            DoSave();
363
            TryClose( /*true*/);
364
        }
365

    
366
        public void RejectChanges()
367
        {
368
            Settings.Reload();
369
            TryClose( /*false*/);
370
        }
371

    
372
        public void ApplyChanges()
373
        {
374
            DoSave();
375
        }
376

    
377
        private void DoSave()
378
        {
379
            //SetStartupMode();            
380

    
381
            //Ensure we save the settings changes first
382
            foreach (var account in _accountsToRemove)
383
            {
384
                Settings.Accounts.Remove(account);
385
            }
386

    
387
            foreach (var account in _accountsToAdd)
388
            {
389
                Settings.Accounts.Add(account);
390
            }
391

    
392
            Settings.Save();
393

    
394

    
395
            try
396
            {
397
                foreach (var account in _accountsToRemove)
398
                {
399
                    Shell.RemoveMonitor(account.ServerUrl, account.AccountName);
400
                    Shell.RemoveAccountFromDatabase(account);
401
                }
402

    
403
                foreach (var account in Settings.Accounts)
404
                {
405
                    Shell.MonitorAccount(account);
406
                }
407

    
408
                var poller = IoC.Get<PollAgent>();
409
                poller.SynchNow();
410
            }
411
            finally
412
            {
413
                _accountsToRemove.Clear();
414
                _accountsToAdd.Clear();
415
            }
416

    
417
            NotifyOfPropertyChange(() => Settings);
418

    
419
            if (IgnoreCertificateErrors)
420
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
421
            else
422
            {
423
                ServicePointManager.ServerCertificateValidationCallback = null;
424
            }
425
        }
426

    
427
        /*   public void ChangePithosFolder()
428
        {
429
            var browser = new FolderBrowserDialog();
430
            browser.SelectedPath = Settings.PithosPath;
431
            var result = browser.ShowDialog((IWin32Window)GetView());
432
            if (result == DialogResult.OK)
433
            {
434
                var newPath = browser.SelectedPath;
435
                var accountName = CurrentAccount.AccountName;
436
                var monitor = Shell.Monitors[accountName];
437
                monitor.Stop();
438
                
439
                Shell.Monitors.Remove(accountName);
440

    
441
                Directory.Move(Settings.PithosPath, newPath);
442
                Settings.PithosPath = newPath;
443
                Settings.Save();
444

    
445
                Shell.MonitorAccount(CurrentAccount);
446

    
447
                NotifyOfPropertyChange(() => Settings);                
448
            }
449
        }
450
*/
451

    
452

    
453
        private readonly List<AccountSettings> _accountsToAdd = new List<AccountSettings>();
454

    
455
        public async void AddAccount()
456
        {
457
            var wizard = new AddAccountViewModel();
458
            if (_windowManager.ShowDialog(wizard) == true)
459
            {
460
                try
461
                {
462
                    string selectedPath = wizard.AccountPath;
463
                    var initialRootPath = wizard.ShouldCreateOkeanosFolder
464
                                              ? Path.Combine(selectedPath, "Okeanos")
465
                                              : selectedPath;
466
                    var actualRootPath = initialRootPath;
467
                    if (wizard.ShouldCreateOkeanosFolder)
468
                    {
469
                        int attempt = 1;
470
                        while (Directory.Exists(actualRootPath) || File.Exists(actualRootPath))
471
                        {
472
                            actualRootPath = String.Format("{0} {1}", initialRootPath, attempt++);
473
                        }
474
                        Directory.CreateDirectory(actualRootPath);
475
                    }
476

    
477

    
478

    
479
                    var account =
480
                        Accounts.FirstOrDefault(
481
                            act => act.AccountName == wizard.AccountName && act.ServerUrl == wizard.CurrentServer);
482
                    if (account != null)
483
                    {
484
                        if (
485
                            MessageBox.Show("The account you specified already exists. Do you want to update it?",
486
                                            "The account exists") == MessageBoxResult.Yes)
487
                        {
488
                            account.ApiKey = wizard.Token;
489
                            account.IsExpired = false;
490
                            CurrentAccount = account;
491
                        }
492
                    }
493
                    else
494
                    {
495
                        var newAccount = new AccountSettings
496
                                             {
497
                                                 AccountName = wizard.AccountName,
498
                                                 ServerUrl = wizard.CurrentServer,
499
                                                 ApiKey = wizard.Token,
500
                                                 RootPath = actualRootPath,
501
                                                 IsActive = wizard.IsAccountActive,
502
                                             };
503

    
504

    
505
                        var client = new CloudFilesClient(newAccount.AccountName, newAccount.ApiKey)
506
                                         {
507
                                             AuthenticationUrl = newAccount.ServerUrl,
508
                                             UsePithos = true
509
                                         };
510

    
511
                        await InitializeSelectiveFolders(newAccount, client);
512

    
513

    
514
                        //TODO:Add the "pithos" container as a default selection                   
515

    
516
                        _accountsToAdd.Add(newAccount);
517
                        var accountVm = new AccountViewModel(newAccount);
518
                        (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVm);
519
                        CurrentAccount = accountVm;
520
                    }
521
                    NotifyOfPropertyChange(() => Accounts);
522
                    NotifyOfPropertyChange(() => Settings);
523
                }
524
                catch (WebException exc)
525
                {
526
                    Log.ErrorFormat("[Add Account] Connectivity Error: {0}", exc);
527
                    MessageBox.Show("Unable to connect to Pithos. Please try again later", "Connectivity Error",
528
                                    MessageBoxButton.OK, MessageBoxImage.Exclamation);
529
                }
530
            }
531

    
532

    
533

    
534
        }
535

    
536
        private async Task InitializeSelectiveFolders(AccountSettings newAccount, CloudFilesClient client,
537
                                                      int retries = 3)
538
        {
539
            while (true)
540
            {
541
                try
542
                {
543
                    await client.Authenticate().ConfigureAwait(false);
544

    
545
                    var containers = await client.ListContainers(newAccount.AccountName).ConfigureAwait(false);
546
                    var containerUris = from container in containers
547
                                        select String.Format(@"{0}/v1/{1}/{2}",
548
                                                             newAccount.ServerUrl, newAccount.AccountName,
549
                                                             container.Name);
550

    
551
                    newAccount.SelectiveFolders.AddRange(containerUris.ToArray());
552

    
553
                    var objectInfos = (from container in containers
554
                                       from dir in client.ListObjects(newAccount.AccountName, container.Name)
555
                                       where container.Name.ToString() != "trash"
556
                                       select dir).ToList();
557
                    var tree = objectInfos.ToTree();
558

    
559
                    var selected = (from root in tree
560
                                    from child in root
561
                                    select child.Uri.ToString()).ToArray();
562
                    newAccount.SelectiveFolders.AddRange(selected);
563
                    return;
564
                }
565
                catch (WebException)
566
                {
567
                    if (retries > 0)
568
                        retries--;
569
                    else
570
                        throw;
571
                }
572
            }
573
        }
574

    
575
/*
576
        public void AddPithosAccount()
577
       {
578
            var credentials=PithosAccount.RetrieveCredentials(null);
579
            if (credentials == null)
580
                return;
581
            var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
582
            var accountVM = new AccountViewModel(account);
583
            if (account == null)
584
            {
585
                account=new AccountSettings{
586
                    AccountName=credentials.UserName,
587
                    ApiKey=credentials.Password
588
                };
589
                Settings.Accounts.Add(account);
590
                accountVM = new AccountViewModel(account);
591
                (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVM);
592
            }
593
            else
594
            {
595
                account.ApiKey=credentials.Password;
596
            }
597
            //SelectedAccountIndex= Settings.Accounts.IndexOf(account);
598
            CurrentAccount = accountVM;
599
            NotifyOfPropertyChange(() => Accounts);
600
            NotifyOfPropertyChange(()=>Settings);                       
601
       }
602
*/
603

    
604

    
605
        private readonly List<AccountSettings> _accountsToRemove = new List<AccountSettings>();
606

    
607
        public void RemoveAccount()
608
        {
609
            Accounts.TryRemove(CurrentAccount);
610
            _accountsToRemove.Add(CurrentAccount.Account);
611

    
612
            CurrentAccount = null;
613
            NotifyOfPropertyChange(() => Accounts);
614

    
615

    
616
            //NotifyOfPropertyChange("Settings.Accounts");
617
        }
618

    
619
        public bool CanRemoveAccount
620
        {
621
            get { return (CurrentAccount != null); }
622
        }
623

    
624
        public bool CanClearAccountCache
625
        {
626
            get { return (CurrentAccount != null); }
627
        }
628

    
629
        public void ClearAccountCache()
630
        {
631
            if (MessageBoxResult.Yes ==
632
                MessageBox.Show("You are about to delete all partially downloaded files from the account's cache.\n" +
633
                                " You will have to download all partially downloaded data again\n" +
634
                                "This change can not be undone\n\n" +
635
                                "Do you wish to delete all partially downloaded data?",
636
                                "Warning! Clearing account cache",
637
                                MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No))
638
            {
639

    
640
                var cachePath = Path.Combine(CurrentAccount.RootPath, FolderConstants.CacheFolder);
641
                var dir = new DirectoryInfo(cachePath);
642
                //The file may not exist if we just created the account
643
                if (!dir.Exists)
644
                    return;
645
                dir.EnumerateFiles().Apply(file => file.Delete());
646
                dir.EnumerateDirectories().Apply(folder => folder.Delete(true));
647
            }
648
        }
649

    
650

    
651
        public bool ExtensionsActivated
652
        {
653
            get { return Settings.ExtensionsActivated; }
654
            set
655
            {
656
                if (Settings.ExtensionsActivated == value)
657
                    return;
658

    
659
                Settings.ExtensionsActivated = value;
660

    
661
/*
662
                if (value)
663
                    _extensionController.RegisterExtensions();
664
                else
665
                {
666
                    _extensionController.UnregisterExtensions();
667
                }
668
*/
669
                NotifyOfPropertyChange(() => ExtensionsActivated);
670
            }
671
        }
672

    
673
        public bool DebugLoggingEnabled
674
        {
675
            get { return Settings.DebugLoggingEnabled; }
676
            set
677
            {
678
                Settings.DebugLoggingEnabled = value;
679
                NotifyOfPropertyChange(() => DebugLoggingEnabled);
680
            }
681
        }
682

    
683
        public bool IgnoreCertificateErrors
684
        {
685
            get { return Settings.IgnoreCertificateErrors; }
686
            set
687
            {
688
                Settings.IgnoreCertificateErrors = value;
689
                NotifyOfPropertyChange(() => IgnoreCertificateErrors);
690
            }
691
        }
692

    
693
        #endregion
694

    
695
        /* private int _selectedAccountIndex;
696
        public int SelectedAccountIndex
697
        {
698
            get { return _selectedAccountIndex; }
699
            set
700
            {
701
                //var accountCount=Settings.Accounts.Count;
702
                //if (accountCount == 0)
703
                //    return;
704
                //if (0 <= value && value < accountCount)
705
                //    _selectedAccountIndex = value;
706
                //else
707
                //    _selectedAccountIndex = 0;
708
                _selectedAccountIndex = value;
709
                NotifyOfPropertyChange(() => CurrentAccount);
710
                NotifyOfPropertyChange(() => CanRemoveAccount);
711
                NotifyOfPropertyChange(()=>SelectedAccountIndex);
712
            }
713
        }*/
714

    
715
        private AccountViewModel _currentAccount;
716
        private readonly IWindowManager _windowManager;
717
        private readonly string _shortcutPath;
718

    
719

    
720

    
721
        public AccountViewModel CurrentAccount
722
        {
723
            get { return _currentAccount; }
724
            set
725
            {
726
                _currentAccount = value;
727

    
728
                if (_currentAccount != null)
729
                    _currentAccount.PropertyChanged += (o, e) => NotifyOfPropertyChange(() => CanSelectiveSyncFolders);
730

    
731
                NotifyOfPropertyChange(() => CurrentAccount);
732
                NotifyOfPropertyChange(() => CanRemoveAccount);
733
                NotifyOfPropertyChange(() => CanSelectiveSyncFolders);
734
                NotifyOfPropertyChange(() => CanMoveAccountFolder);
735
                NotifyOfPropertyChange(() => CanClearAccountCache);
736
                NotifyOfPropertyChange(() => CanWipeAccount);
737
            }
738
        }
739

    
740
/*
741
        public AccountSettings CurrentAccount
742
        {
743
            get {
744
                if (0 <= SelectedAccountIndex && SelectedAccountIndex < Settings.Accounts.Count)                    
745
                    return Settings.Accounts[SelectedAccountIndex];
746
                return null;
747
            }
748

    
749
        }
750
*/
751

    
752

    
753
        public bool CanMoveAccountFolder
754
        {
755
            get { return CurrentAccount != null; }
756
        }
757

    
758
        public void MoveAccountFolder()
759
        {
760

    
761
            using (var dlg = new FolderBrowserDialog())
762
            {
763
                var currentFolder = CurrentAccount.RootPath;
764
                dlg.SelectedPath = currentFolder;
765
                //Ask the user to select a folder
766
                //Note: We need a parent window here, which we retrieve with GetView            
767
                var view = (Window) GetView();
768
                if (DialogResult.OK != dlg.ShowDialog(new Wpf32Window(view)))
769
                    return;
770

    
771
                var newPath = dlg.SelectedPath;
772
                //Find the account's monitor and stop it
773
                PithosMonitor monitor;
774
                if (Shell.Monitors.TryGetValue(CurrentAccount.AccountKey, out monitor))
775
                {
776
                    //Problem: Doesn't stop the poll agent
777
                    monitor.Stop();
778

    
779
                    monitor.MoveRootFolder(newPath);
780

    
781
                   
782
                }
783
                //Replace the old rootpath with the new
784
                CurrentAccount.RootPath = newPath;
785
                //TODO: This will save all settings changes. Too coarse grained, need to fix at a later date
786
                Settings.Save();
787
                //And start the monitor on the new RootPath            
788
                if (monitor != null)
789
                {
790
                    monitor.RootPath = newPath;
791
                    if (CurrentAccount.IsActive)
792
                        Shell.StartMonitor(monitor);
793
                        
794
                }
795
                else
796
                    Shell.MonitorAccount(CurrentAccount.Account);
797
                //Finally, notify that the Settings, CurrentAccount have changed
798
                NotifyOfPropertyChange(() => CurrentAccount);
799
                NotifyOfPropertyChange(() => Settings);
800

    
801
            }
802
        }
803

    
804
    }
805
}