2 /* -----------------------------------------------------------------------
3 * <copyright file="PreferencesViewModel.cs" company="GRNet">
5 * Copyright 2011-2012 GRNET S.A. All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
11 * 1. Redistributions of source code must retain the above
12 * copyright notice, this list of conditions and the following
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.
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.
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.
39 * -----------------------------------------------------------------------
44 using System.Collections.Concurrent;
45 using System.Collections.Generic;
46 using System.ComponentModel.Composition;
47 using System.Diagnostics;
50 using System.Reflection;
51 using System.Threading.Tasks;
53 using System.Windows.Forms;
55 using Pithos.Client.WPF.Configuration;
56 using Pithos.Client.WPF.Properties;
57 using Pithos.Client.WPF.SelectiveSynch;
59 using Pithos.Interfaces;
62 using MessageBox = System.Windows.MessageBox;
63 using Screen = Caliburn.Micro.Screen;
65 namespace Pithos.Client.WPF.Preferences
68 /// The preferences screen displays user and account settings and updates the PithosMonitor
69 /// classes when account settings change.
72 /// The class is a single ViewModel for all Preferences tabs. It can be broken in separate
73 /// ViewModels, one for each tab.
76 public class PreferencesViewModel : Screen
78 private readonly IEventAggregator _events;
80 //Logging in the Pithos client is provided by log4net
81 private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
83 private PithosSettings _settings;
84 public PithosSettings Settings
86 get { return _settings; }
90 NotifyOfPropertyChange(()=>Settings);
94 private ObservableConcurrentCollection<AccountViewModel> _accounts;
95 public ObservableConcurrentCollection<AccountViewModel> Accounts
97 get { return _accounts; }
101 NotifyOfPropertyChange(()=>Accounts);
105 public bool StartOnSystemStartup { get; set; }
107 public ShellViewModel Shell { get; set; }
108 //ShellExtensionController _extensionController=new ShellExtensionController();
110 public PreferencesViewModel(IWindowManager windowManager, IEventAggregator events, ShellViewModel shell, PithosSettings settings, string currentTab)
112 // ReSharper disable DoNotCallOverridableMethodsInConstructor
113 //Caliburn.Micro uses DisplayName for the view's title
114 DisplayName = "Pithos+ Preferences";
115 // ReSharper restore DoNotCallOverridableMethodsInConstructor
117 _windowManager = windowManager;
123 Accounts = new ObservableConcurrentCollection<AccountViewModel>();
124 if (settings.Accounts == null)
126 settings.Accounts=new AccountsCollection();
129 var accountVMs = from account in settings.Accounts
130 select new AccountViewModel(account);
132 Accounts.AddFromEnumerable(accountVMs);
134 var startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
135 _shortcutPath = Path.Combine(startupPath, "Pithos.lnk");
138 StartOnSystemStartup = File.Exists(_shortcutPath);
140 SelectedTab = currentTab;
143 private string _selectedTab="General";
144 public string SelectedTab
146 get { return _selectedTab; }
149 _selectedTab = value??"General";
150 NotifyOfPropertyChange(()=>SelectedTab);
151 NotifyOfPropertyChange(() => AccountTabSelected);
156 public bool AccountTabSelected
158 get { return _selectedTab == "AccountTab"; }
160 #region Preferences Properties
162 private bool _noProxy;
165 get { return _noProxy; }
169 NotifyOfPropertyChange(()=>NoProxy);
174 private bool _defaultProxy;
176 public bool DefaultProxy
178 get { return _defaultProxy; }
181 _defaultProxy = value;
182 NotifyOfPropertyChange(() => DefaultProxy);
187 private bool _manualProxy;
189 public bool ManualProxy
191 get { return _manualProxy; }
194 _manualProxy = value;
195 NotifyOfPropertyChange(() => ManualProxy);
201 public int StartupDelay
203 get { return (int) Settings.StartupDelay.TotalMinutes; }
207 throw new ArgumentOutOfRangeException("value",Resources.PreferencesViewModel_StartupDelay_Greater_or_equal_to_0);
208 Settings.StartupDelay = TimeSpan.FromMinutes(value);
209 NotifyOfPropertyChange(()=>StartupDelay);
215 public bool CanSelectiveSyncFolders
217 get { return CurrentAccount != null; }
220 public void SelectiveSyncFolders()
222 var monitor = Shell.Monitors[CurrentAccount.AccountName];
225 var model = new SelectiveSynchViewModel(monitor,_events,CurrentAccount.Account);
226 if (_windowManager.ShowDialog(model) == true)
232 public void RefreshApiKey()
234 //_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 });
235 if (CurrentAccount == null)
240 var name = CurrentAccount.AccountName;
242 var loginUri = new Uri(new Uri(CurrentAccount.ServerUrl), "login");
243 var credentials = PithosAccount.RetrieveCredentials(loginUri.ToString(),name);
244 if (credentials==null)
246 //The server will return credentials for a different account, not just the current account
247 //We need to find the correct account first
248 var account = Accounts.First(act => act.AccountName == credentials.UserName && act.ServerUrl == CurrentAccount.ServerUrl);
249 account.ApiKey = credentials.Password;
250 account.IsExpired = false;
252 TaskEx.Delay(10000).ContinueWith(_ =>Shell.MonitorAccount(account.Account));
253 NotifyOfPropertyChange(() => Accounts);
255 catch (AggregateException exc)
257 string message = String.Format("API Key retrieval failed");
258 Log.Error(message, exc.InnerException);
259 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
261 catch (Exception exc)
263 string message = String.Format("API Key retrieval failed");
264 Log.Error(message, exc);
265 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
271 public void OpenLogPath()
276 public void OpenLogConsole()
278 var logView=IoC.Get<LogConsole.LogConsoleViewModel>();
279 _windowManager.ShowWindow(logView);
282 public void SaveChanges()
288 public void RejectChanges()
294 public void ApplyChanges()
299 private void DoSave()
303 //Ensure we save the settings changes first
304 foreach (var account in _accountsToRemove)
306 Settings.Accounts.Remove(account);
309 foreach (var account in _accountsToAdd)
311 Settings.Accounts.Add(account);
319 foreach (var account in _accountsToRemove)
321 Shell.RemoveMonitor(account.AccountName);
322 Shell.RemoveAccountFromDatabase(account);
325 foreach (var account in Settings.Accounts)
327 Shell.MonitorAccount(account);
332 _accountsToRemove.Clear();
333 _accountsToAdd.Clear();
336 NotifyOfPropertyChange(()=>Settings);
338 if (IgnoreCertificateErrors)
339 ServicePointManager.ServerCertificateValidationCallback= (sender,certificate,chain,errors)=> true;
342 ServicePointManager.ServerCertificateValidationCallback = null;
346 /* public void ChangePithosFolder()
348 var browser = new FolderBrowserDialog();
349 browser.SelectedPath = Settings.PithosPath;
350 var result = browser.ShowDialog((IWin32Window)GetView());
351 if (result == DialogResult.OK)
353 var newPath = browser.SelectedPath;
354 var accountName = CurrentAccount.AccountName;
355 var monitor = Shell.Monitors[accountName];
358 Shell.Monitors.Remove(accountName);
360 Directory.Move(Settings.PithosPath, newPath);
361 Settings.PithosPath = newPath;
364 Shell.MonitorAccount(CurrentAccount);
366 NotifyOfPropertyChange(() => Settings);
372 readonly List<AccountSettings> _accountsToAdd=new List<AccountSettings>();
373 public void AddAccount()
375 var wizard = new AddAccountViewModel();
376 if (_windowManager.ShowDialog(wizard) == true)
378 string selectedPath = wizard.AccountPath;
379 var initialRootPath = wizard.ShouldCreateOkeanosFolder?
380 Path.Combine(selectedPath, "Okeanos")
382 var actualRootPath= initialRootPath;
383 if (wizard.ShouldCreateOkeanosFolder)
386 while (Directory.Exists(actualRootPath) || File.Exists(actualRootPath))
388 actualRootPath = String.Format("{0} {1}", initialRootPath, attempt++);
394 var account = Accounts.FirstOrDefault(act => act.AccountName == wizard.AccountName && act.ServerUrl == wizard.CurrentServer);
397 if (MessageBox.Show("The account you specified already exists. Do you want to update it?","The account exists") == MessageBoxResult.Yes)
399 account.ApiKey = wizard.Token;
400 account.IsExpired = false;
401 CurrentAccount = account;
406 var newAccount = new AccountSettings
408 AccountName = wizard.AccountName,
409 ServerUrl = wizard.CurrentServer,
410 ApiKey = wizard.Token,
411 RootPath = actualRootPath,
412 IsActive = wizard.IsAccountActive
414 _accountsToAdd.Add(newAccount);
415 var accountVm = new AccountViewModel(newAccount);
416 (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVm);
417 CurrentAccount = accountVm;
419 NotifyOfPropertyChange(() => Accounts);
420 NotifyOfPropertyChange(() => Settings);
428 public void AddPithosAccount()
430 var credentials=PithosAccount.RetrieveCredentials(null);
431 if (credentials == null)
433 var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
434 var accountVM = new AccountViewModel(account);
437 account=new AccountSettings{
438 AccountName=credentials.UserName,
439 ApiKey=credentials.Password
441 Settings.Accounts.Add(account);
442 accountVM = new AccountViewModel(account);
443 (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVM);
447 account.ApiKey=credentials.Password;
449 //SelectedAccountIndex= Settings.Accounts.IndexOf(account);
450 CurrentAccount = accountVM;
451 NotifyOfPropertyChange(() => Accounts);
452 NotifyOfPropertyChange(()=>Settings);
457 readonly List<AccountSettings> _accountsToRemove = new List<AccountSettings>();
458 public void RemoveAccount()
460 Accounts.TryRemove(CurrentAccount);
461 _accountsToRemove.Add(CurrentAccount.Account);
463 CurrentAccount = null;
464 NotifyOfPropertyChange(() => Accounts);
467 //NotifyOfPropertyChange("Settings.Accounts");
470 public bool CanRemoveAccount
472 get { return (CurrentAccount != null); }
477 public bool ExtensionsActivated
479 get { return Settings.ExtensionsActivated; }
482 if (Settings.ExtensionsActivated == value)
485 Settings.ExtensionsActivated = value;
489 _extensionController.RegisterExtensions();
492 _extensionController.UnregisterExtensions();
495 NotifyOfPropertyChange(() => ExtensionsActivated);
499 public bool DebugLoggingEnabled
501 get { return Settings.DebugLoggingEnabled; }
503 Settings.DebugLoggingEnabled = value;
504 NotifyOfPropertyChange(()=>DebugLoggingEnabled);
508 public bool IgnoreCertificateErrors
510 get { return Settings.IgnoreCertificateErrors; }
512 Settings.IgnoreCertificateErrors = value;
513 NotifyOfPropertyChange(() => IgnoreCertificateErrors);
519 /* private int _selectedAccountIndex;
520 public int SelectedAccountIndex
522 get { return _selectedAccountIndex; }
525 //var accountCount=Settings.Accounts.Count;
526 //if (accountCount == 0)
528 //if (0 <= value && value < accountCount)
529 // _selectedAccountIndex = value;
531 // _selectedAccountIndex = 0;
532 _selectedAccountIndex = value;
533 NotifyOfPropertyChange(() => CurrentAccount);
534 NotifyOfPropertyChange(() => CanRemoveAccount);
535 NotifyOfPropertyChange(()=>SelectedAccountIndex);
539 private AccountViewModel _currentAccount;
540 private readonly IWindowManager _windowManager;
541 private readonly string _shortcutPath;
545 public AccountViewModel CurrentAccount
547 get { return _currentAccount; }
550 _currentAccount = value;
551 NotifyOfPropertyChange(()=>CurrentAccount);
552 NotifyOfPropertyChange(() => CanRemoveAccount);
553 NotifyOfPropertyChange(() => CanSelectiveSyncFolders);
554 NotifyOfPropertyChange(() => CanMoveAccountFolder);
559 public AccountSettings CurrentAccount
562 if (0 <= SelectedAccountIndex && SelectedAccountIndex < Settings.Accounts.Count)
563 return Settings.Accounts[SelectedAccountIndex];
571 public bool CanMoveAccountFolder
573 get { return CurrentAccount != null; }
576 public void MoveAccountFolder()
579 using (var dlg = new FolderBrowserDialog())
581 var currentFolder = CurrentAccount.RootPath;
582 dlg.SelectedPath = currentFolder;
583 //Ask the user to select a folder
584 //Note: We need a parent window here, which we retrieve with GetView
585 var view = (Window)GetView();
586 if (DialogResult.OK != dlg.ShowDialog(new Wpf32Window(view)))
589 var newPath= dlg.SelectedPath;
590 //Find the account's monitor and stop it
591 PithosMonitor monitor;
592 if (Shell.Monitors.TryGetValue(CurrentAccount.AccountName, out monitor))
597 var oldPath = monitor.RootPath;
598 //The old directory may not exist eg. if we create an account for the first time
599 if (Directory.Exists(oldPath))
601 //If it does, do the move
603 //Now Create all of the directories
604 foreach (string dirPath in Directory.EnumerateDirectories(oldPath, "*",
605 SearchOption.AllDirectories))
606 Directory.CreateDirectory(dirPath.Replace(oldPath, newPath));
609 foreach (string newFilePath in Directory.EnumerateFiles(oldPath, "*.*",
610 SearchOption.AllDirectories))
611 File.Copy(newFilePath, newFilePath.Replace(oldPath, newPath));
613 Log.InfoFormat("Deleting account folder {0}",oldPath);
614 Directory.Delete(oldPath, true);
616 //We also need to change the path of the existing file states
617 monitor.MoveFileStates(oldPath, newPath);
620 //Replace the old rootpath with the new
621 CurrentAccount.RootPath = newPath;
622 //TODO: This will save all settings changes. Too coarse grained, need to fix at a later date
624 //And start the monitor on the new RootPath
627 monitor.RootPath = newPath;
628 if (CurrentAccount.IsActive)
632 Shell.MonitorAccount(CurrentAccount.Account);
633 //Finally, notify that the Settings, CurrentAccount have changed
634 NotifyOfPropertyChange(() => CurrentAccount);
635 NotifyOfPropertyChange(() => Settings);