Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / Preferences / PreferencesViewModel.cs @ fe62b7f4

History | View | Annotate | Download (19.3 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
        public void SaveChanges()
268
        {
269
            DoSave();
270
            TryClose(true);
271
        }
272

    
273
        public void RejectChanges()
274
        {
275
            Settings.Reload();
276
            TryClose(false);
277
        }
278

    
279
        public void ApplyChanges()
280
        {
281
            DoSave();
282
        }
283

    
284
        private void DoSave()
285
        {
286
            //SetStartupMode();            
287

    
288
            //Ensure we save the settings changes first
289
            foreach (var account in _accountsToRemove)
290
            {
291
                Settings.Accounts.Remove(account);
292
            }
293

    
294
            foreach (var account in _accountsToAdd)
295
            {
296
                Settings.Accounts.Add(account);    
297
            }
298
            
299
            Settings.Save();
300

    
301

    
302
            foreach (var account in _accountsToRemove)
303
            {
304
                Shell.RemoveMonitor(account.AccountName);
305
                Shell.RemoveAccountFromDatabase(account);
306
            }
307

    
308
            foreach (var account in Settings.Accounts)
309
            {                                
310
                Shell.MonitorAccount(account);
311
            }
312

    
313
            NotifyOfPropertyChange(()=>Settings);
314
        }
315

    
316
     /*   public void ChangePithosFolder()
317
        {
318
            var browser = new FolderBrowserDialog();
319
            browser.SelectedPath = Settings.PithosPath;
320
            var result = browser.ShowDialog((IWin32Window)GetView());
321
            if (result == DialogResult.OK)
322
            {
323
                var newPath = browser.SelectedPath;
324
                var accountName = CurrentAccount.AccountName;
325
                var monitor = Shell.Monitors[accountName];
326
                monitor.Stop();
327
                
328
                Shell.Monitors.Remove(accountName);
329

    
330
                Directory.Move(Settings.PithosPath, newPath);
331
                Settings.PithosPath = newPath;
332
                Settings.Save();
333

    
334
                Shell.MonitorAccount(CurrentAccount);
335

    
336
                NotifyOfPropertyChange(() => Settings);                
337
            }
338
        }
339
*/
340

    
341

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

    
362
               var newAccount = new AccountSettings
363
                                    {
364
                                        AccountName = wizard.AccountName,
365
                                        ServerUrl=wizard.CurrentServer,
366
                                        ApiKey=wizard.Token,
367
                                        RootPath = actualRootPath,
368
                                        IsActive=wizard.IsAccountActive
369
                                    };
370
               _accountsToAdd.Add(newAccount);
371
               var accountVm = new AccountViewModel(newAccount);
372
               (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVm);
373
               CurrentAccount = accountVm;
374
               NotifyOfPropertyChange(() => Accounts);
375
               NotifyOfPropertyChange(() => Settings);   
376
           }
377

    
378

    
379
            
380
       }
381

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

    
407

    
408
        readonly List<AccountSettings> _accountsToRemove = new List<AccountSettings>();
409
        public void RemoveAccount()
410
        {
411
            Accounts.TryRemove(CurrentAccount);
412
            _accountsToRemove.Add(CurrentAccount.Account);
413

    
414
            CurrentAccount = null;
415
            NotifyOfPropertyChange(() => Accounts);
416

    
417
            
418
            //NotifyOfPropertyChange("Settings.Accounts");
419
        }
420

    
421
        public bool CanRemoveAccount
422
        {
423
            get { return (CurrentAccount != null); }
424
        }
425

    
426

    
427

    
428
        public bool ExtensionsActivated
429
        {
430
            get { return Settings.ExtensionsActivated; }
431
            set
432
            {
433
                if (Settings.ExtensionsActivated == value)
434
                    return;
435

    
436
                Settings.ExtensionsActivated = value;
437

    
438
/*
439
                if (value)
440
                    _extensionController.RegisterExtensions();
441
                else
442
                {
443
                    _extensionController.UnregisterExtensions();
444
                }
445
*/
446
                NotifyOfPropertyChange(() => ExtensionsActivated);
447
            }
448
        }
449

    
450
       
451
        #endregion
452

    
453
       /* private int _selectedAccountIndex;
454
        public int SelectedAccountIndex
455
        {
456
            get { return _selectedAccountIndex; }
457
            set
458
            {
459
                //var accountCount=Settings.Accounts.Count;
460
                //if (accountCount == 0)
461
                //    return;
462
                //if (0 <= value && value < accountCount)
463
                //    _selectedAccountIndex = value;
464
                //else
465
                //    _selectedAccountIndex = 0;
466
                _selectedAccountIndex = value;
467
                NotifyOfPropertyChange(() => CurrentAccount);
468
                NotifyOfPropertyChange(() => CanRemoveAccount);
469
                NotifyOfPropertyChange(()=>SelectedAccountIndex);
470
            }
471
        }*/
472

    
473
        private AccountViewModel _currentAccount;
474
        private readonly IWindowManager _windowManager;
475
        private readonly string _shortcutPath;
476

    
477

    
478
        
479
        public AccountViewModel CurrentAccount
480
        {
481
            get { return _currentAccount; }
482
            set
483
            {
484
                _currentAccount = value;
485
                NotifyOfPropertyChange(()=>CurrentAccount);
486
                NotifyOfPropertyChange(() => CanRemoveAccount);
487
                NotifyOfPropertyChange(() => CanSelectiveSyncFolders);
488
                NotifyOfPropertyChange(() => CanMoveAccountFolder);
489
            }
490
        }
491

    
492
/*
493
        public AccountSettings CurrentAccount
494
        {
495
            get {
496
                if (0 <= SelectedAccountIndex && SelectedAccountIndex < Settings.Accounts.Count)                    
497
                    return Settings.Accounts[SelectedAccountIndex];
498
                return null;
499
            }
500

    
501
        }
502
*/
503

    
504

    
505
        public bool CanMoveAccountFolder
506
        {
507
            get { return CurrentAccount != null; }
508
        }
509

    
510
    public void MoveAccountFolder()
511
    {
512

    
513
        using (var dlg = new FolderBrowserDialog())
514
        {
515
            var currentFolder = CurrentAccount.RootPath;
516
            dlg.SelectedPath = currentFolder;
517
            //Ask the user to select a folder
518
            //Note: We need a parent window here, which we retrieve with GetView            
519
            var view = (Window)GetView();            
520
            if (DialogResult.OK != dlg.ShowDialog(new Wpf32Window(view)))
521
                return;            
522

    
523
            var newPath= dlg.SelectedPath;                
524
            //Find the account's monitor and stop it
525
            PithosMonitor monitor;
526
            if (Shell.Monitors.TryGetValue(CurrentAccount.AccountName, out monitor))
527
            {
528
                monitor.Stop();
529

    
530

    
531
                var oldPath = monitor.RootPath;
532
                //The old directory may not exist eg. if we create an account for the first time
533
                if (Directory.Exists(oldPath))
534
                {
535
                    //If it does, do the move
536

    
537
                    //Now Create all of the directories
538
                    foreach (string dirPath in Directory.EnumerateDirectories(oldPath, "*",
539
                                                           SearchOption.AllDirectories))
540
                        Directory.CreateDirectory(dirPath.Replace(oldPath, newPath));
541

    
542
                    //Copy all the files
543
                    foreach (string newFilePath in Directory.EnumerateFiles(oldPath, "*.*",
544
                                                                            SearchOption.AllDirectories))
545
                        File.Copy(newFilePath, newFilePath.Replace(oldPath, newPath));
546

    
547
                    Directory.Delete(oldPath, true);
548

    
549
                    //We also need to change the path of the existing file states
550
                    monitor.MoveFileStates(oldPath, newPath);
551
                }
552
            }
553
            //Replace the old rootpath with the new
554
            CurrentAccount.RootPath = newPath;
555
            //TODO: This will save all settings changes. Too coarse grained, need to fix at a later date
556
            Settings.Save();            
557
            //And start the monitor on the new RootPath            
558
            if (monitor != null)
559
            {
560
                monitor.RootPath = newPath;
561
                if (CurrentAccount.IsActive)
562
                    monitor.Start();
563
            }
564
            else
565
                Shell.MonitorAccount(CurrentAccount.Account);
566
            //Finally, notify that the Settings, CurrentAccount have changed
567
            NotifyOfPropertyChange(() => CurrentAccount);
568
            NotifyOfPropertyChange(() => Settings);
569

    
570
        }
571
    }
572
    }
573
}