Statistics
| Branch: | Revision:

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

History | View | Annotate | Download (19.9 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
            try
310
            {
311
                foreach (var account in _accountsToRemove)
312
                {
313
                    Shell.RemoveMonitor(account.AccountName);
314
                    Shell.RemoveAccountFromDatabase(account);
315
                }
316

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

    
328
            NotifyOfPropertyChange(()=>Settings);
329
        }
330

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

    
345
                Directory.Move(Settings.PithosPath, newPath);
346
                Settings.PithosPath = newPath;
347
                Settings.Save();
348

    
349
                Shell.MonitorAccount(CurrentAccount);
350

    
351
                NotifyOfPropertyChange(() => Settings);                
352
            }
353
        }
354
*/
355

    
356

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

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

    
393

    
394
            
395
       }
396

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

    
422

    
423
        readonly List<AccountSettings> _accountsToRemove = new List<AccountSettings>();
424
        public void RemoveAccount()
425
        {
426
            Accounts.TryRemove(CurrentAccount);
427
            _accountsToRemove.Add(CurrentAccount.Account);
428

    
429
            CurrentAccount = null;
430
            NotifyOfPropertyChange(() => Accounts);
431

    
432
            
433
            //NotifyOfPropertyChange("Settings.Accounts");
434
        }
435

    
436
        public bool CanRemoveAccount
437
        {
438
            get { return (CurrentAccount != null); }
439
        }
440

    
441

    
442

    
443
        public bool ExtensionsActivated
444
        {
445
            get { return Settings.ExtensionsActivated; }
446
            set
447
            {
448
                if (Settings.ExtensionsActivated == value)
449
                    return;
450

    
451
                Settings.ExtensionsActivated = value;
452

    
453
/*
454
                if (value)
455
                    _extensionController.RegisterExtensions();
456
                else
457
                {
458
                    _extensionController.UnregisterExtensions();
459
                }
460
*/
461
                NotifyOfPropertyChange(() => ExtensionsActivated);
462
            }
463
        }
464

    
465
        public bool DebugLoggingEnabled
466
        {
467
            get { return Settings.DebugLoggingEnabled; }
468
            set { 
469
                Settings.DebugLoggingEnabled = value;
470
                NotifyOfPropertyChange(()=>DebugLoggingEnabled);
471
            }
472
        }
473
       
474
        #endregion
475

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

    
496
        private AccountViewModel _currentAccount;
497
        private readonly IWindowManager _windowManager;
498
        private readonly string _shortcutPath;
499

    
500

    
501
        
502
        public AccountViewModel CurrentAccount
503
        {
504
            get { return _currentAccount; }
505
            set
506
            {
507
                _currentAccount = value;
508
                NotifyOfPropertyChange(()=>CurrentAccount);
509
                NotifyOfPropertyChange(() => CanRemoveAccount);
510
                NotifyOfPropertyChange(() => CanSelectiveSyncFolders);
511
                NotifyOfPropertyChange(() => CanMoveAccountFolder);
512
            }
513
        }
514

    
515
/*
516
        public AccountSettings CurrentAccount
517
        {
518
            get {
519
                if (0 <= SelectedAccountIndex && SelectedAccountIndex < Settings.Accounts.Count)                    
520
                    return Settings.Accounts[SelectedAccountIndex];
521
                return null;
522
            }
523

    
524
        }
525
*/
526

    
527

    
528
        public bool CanMoveAccountFolder
529
        {
530
            get { return CurrentAccount != null; }
531
        }
532

    
533
    public void MoveAccountFolder()
534
    {
535

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

    
546
            var newPath= dlg.SelectedPath;                
547
            //Find the account's monitor and stop it
548
            PithosMonitor monitor;
549
            if (Shell.Monitors.TryGetValue(CurrentAccount.AccountName, out monitor))
550
            {
551
                monitor.Stop();
552

    
553

    
554
                var oldPath = monitor.RootPath;
555
                //The old directory may not exist eg. if we create an account for the first time
556
                if (Directory.Exists(oldPath))
557
                {
558
                    //If it does, do the move
559

    
560
                    //Now Create all of the directories
561
                    foreach (string dirPath in Directory.EnumerateDirectories(oldPath, "*",
562
                                                           SearchOption.AllDirectories))
563
                        Directory.CreateDirectory(dirPath.Replace(oldPath, newPath));
564

    
565
                    //Copy all the files
566
                    foreach (string newFilePath in Directory.EnumerateFiles(oldPath, "*.*",
567
                                                                            SearchOption.AllDirectories))
568
                        File.Copy(newFilePath, newFilePath.Replace(oldPath, newPath));
569

    
570
                    Directory.Delete(oldPath, true);
571

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

    
593
        }
594
    }
595
    }
596
}