2 /* -----------------------------------------------------------------------
3 * <copyright file="ShellViewModel.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 * -----------------------------------------------------------------------
42 using System.Collections.Concurrent;
43 using System.Diagnostics;
44 using System.Diagnostics.Contracts;
47 using System.Reflection;
48 using System.Runtime.InteropServices;
49 using System.ServiceModel;
50 using System.Threading.Tasks;
52 using System.Windows.Controls.Primitives;
53 using AppLimit.NetSparkle;
55 using Hardcodet.Wpf.TaskbarNotification;
56 using Pithos.Client.WPF.Configuration;
57 using Pithos.Client.WPF.FileProperties;
58 using Pithos.Client.WPF.Preferences;
59 using Pithos.Client.WPF.SelectiveSynch;
60 using Pithos.Client.WPF.Services;
61 using Pithos.Client.WPF.Shell;
63 using Pithos.Core.Agents;
64 using Pithos.Interfaces;
66 using System.Collections.Generic;
69 using StatusService = Pithos.Client.WPF.Services.StatusService;
71 namespace Pithos.Client.WPF {
72 using System.ComponentModel.Composition;
76 /// The "shell" of the Pithos application displays the taskbar icon, menu and notifications.
77 /// The shell also hosts the status service called by shell extensions to retrieve file info
80 /// It is a strange "shell" as its main visible element is an icon instead of a window
81 /// The shell subscribes to the following events:
82 /// * Notification: Raised by components that want to notify the user. Usually displayed in a balloon
83 /// * SelectiveSynchChanges: Notifies that the user made changes to the selective synch folders for an account. Raised by the Selective Synch dialog. Located here because the monitors are here
84 /// * ShowFilePropertiesEvent: Raised when a shell command requests the display of the file/container properties dialog
86 //TODO: CODE SMELL Why does the shell handle the SelectiveSynchChanges?
87 [Export(typeof(IShell)), Export(typeof(ShellViewModel))]
88 public class ShellViewModel : Screen, IStatusNotification, IShell,
89 IHandle<Notification>, IHandle<SelectiveSynchChanges>, IHandle<ShowFilePropertiesEvent>
92 //The Status Checker provides the current synch state
93 //TODO: Could we remove the status checker and use events in its place?
94 private readonly IStatusChecker _statusChecker;
95 private readonly IEventAggregator _events;
97 public PithosSettings Settings { get; private set; }
100 private readonly ConcurrentDictionary<Uri, PithosMonitor> _monitors = new ConcurrentDictionary<Uri, PithosMonitor>();
102 /// Dictionary of account monitors, keyed by account
105 /// One monitor class is created for each account. The Shell needs access to the monitors to execute start/stop/pause commands,
106 /// retrieve account and boject info
108 // TODO: Does the Shell REALLY need access to the monitors? Could we achieve the same results with a better design?
109 // TODO: The monitors should be internal to Pithos.Core, even though exposing them makes coding of the Object and Container windows easier
110 public ConcurrentDictionary<Uri, PithosMonitor> Monitors
112 get { return _monitors; }
117 /// The status service is used by Shell extensions to retrieve file status information
119 //TODO: CODE SMELL! This is the shell! While hosting in the shell makes executing start/stop commands easier, it is still a smell
120 private ServiceHost _statusService;
122 //Logging in the Pithos client is provided by log4net
123 private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
125 private readonly PollAgent _pollAgent;
126 private readonly NetworkAgent _networkAgent;
129 public Selectives Selectives { get; set; }
131 private MiniStatusViewModel _miniStatus;
134 public MiniStatusViewModel MiniStatus
136 get { return _miniStatus; }
140 _miniStatus.Shell = this;
141 _miniStatus.Deactivated += (sender, arg) =>
143 _statusVisible = false;
144 NotifyOfPropertyChange(()=>MiniStatusCaption);
150 /// The Shell depends on MEF to provide implementations for windowManager, events, the status checker service and the settings
153 /// The PithosSettings class encapsulates the app's settings to abstract their storage mechanism (App settings, a database or registry)
155 [ImportingConstructor]
156 public ShellViewModel(IWindowManager windowManager, IEventAggregator events, IStatusChecker statusChecker, PithosSettings settings,PollAgent pollAgent,NetworkAgent networkAgent)
161 _windowManager = windowManager;
162 //CHECK: Caliburn doesn't need explicit command construction
163 //OpenPithosFolderCommand = new PithosCommand(OpenPithosFolder);
164 _statusChecker = statusChecker;
167 _events.Subscribe(this);
169 _pollAgent = pollAgent;
170 _networkAgent = networkAgent;
173 Proxy.SetFromSettings(settings);
175 StatusMessage = Settings.Accounts.Count==0
176 ? "No Accounts added\r\nPlease add an account"
179 _accounts.CollectionChanged += (sender, e) =>
181 NotifyOfPropertyChange(() => OpenFolderCaption);
182 NotifyOfPropertyChange(() => HasAccounts);
187 catch (Exception exc)
189 Log.Error("Error while starting the ShellViewModel",exc);
195 private void SetVersionMessage()
197 Assembly assembly = Assembly.GetExecutingAssembly();
198 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
199 VersionMessage = String.Format("Pithos+ {0}", fileVersion.FileVersion);
202 public void CurrentSyncStatus()
204 if (Accounts.Count == 0)
206 ShowPreferences("AccountTab");
211 _windowManager.ShowWindow(MiniStatus);
214 if (MiniStatus.IsActive)
215 MiniStatus.TryClose();
217 _statusVisible = !_statusVisible;
219 NotifyOfPropertyChange(() => MiniStatusCaption);
223 protected override void OnActivate()
229 //Must delay opening the upgrade window
230 //to avoid Windows Messages sent by the TaskbarIcon
231 TaskEx.Delay(5000).ContinueWith(_=>
232 Execute.OnUIThread(()=> _sparkle.StartLoop(true,Settings.UpdateForceCheck,Settings.UpdateCheckInterval)));
239 private void OnCheckFinished(object sender, bool updaterequired)
242 Log.InfoFormat("Upgrade check finished. Need Upgrade: {0}", updaterequired);
243 if (_manualUpgradeCheck)
245 _manualUpgradeCheck = false;
247 //Sparkle raises events on a background thread
248 Execute.OnUIThread(()=>
249 ShowBalloonFor(new Notification{Title="Pithos+ is up to date",Message="You have the latest Pithos+ version. No update is required"}));
253 private void OnUpgradeDetected(object sender, UpdateDetectedEventArgs e)
255 Log.InfoFormat("Update detected {0}",e.LatestVersion);
258 public void CheckForUpgrade()
260 ShowBalloonFor(new Notification{Title="Checking for upgrades",Message="Contacting the server to retrieve the latest Pithos+ version."});
262 _sparkle.updateDetected -= OnUpgradeDetected;
263 _sparkle.checkLoopFinished -= OnCheckFinished;
266 _manualUpgradeCheck = true;
268 _sparkle.StartLoop(true,true,Settings.UpdateCheckInterval);
271 private void InitializeSparkle()
273 _sparkle = new Sparkle(Settings.UpdateUrl);
274 _sparkle.updateDetected += OnUpgradeDetected;
275 _sparkle.checkLoopFinished += OnCheckFinished;
276 _sparkle.ShowDiagnosticWindow = Settings.UpdateDiagnostics;
279 private async void StartMonitoring()
283 if (Settings.IgnoreCertificateErrors)
285 ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
288 var accounts = Settings.Accounts.Select(MonitorAccount);
289 await TaskEx.WhenAll(accounts);
290 _statusService = StatusService.Start();
293 catch (AggregateException exc)
297 Log.Error("Error while starting monitoring", e);
304 protected override void OnDeactivate(bool close)
306 base.OnDeactivate(close);
309 StatusService.Stop(_statusService);
310 _statusService = null;
314 public Task MonitorAccount(AccountSettings account)
316 return Task.Factory.StartNew(() =>
318 PithosMonitor monitor;
319 var accountName = account.AccountName;
321 MigrateFolders(account);
323 Selectives.SetIsSelectiveEnabled(account.AccountKey, account.SelectiveSyncEnabled);
325 if (Monitors.TryGetValue(account.AccountKey, out monitor))
327 //If the account is active
328 if (account.IsActive)
330 //The Api Key may have changed throuth the Preferences dialog
331 monitor.ApiKey = account.ApiKey;
332 Debug.Assert(monitor.StatusNotification == this,"An existing monitor should already have a StatusNotification service object");
333 monitor.RootPath = account.RootPath;
334 //Start the monitor. It's OK to start an already started monitor,
335 //it will just ignore the call
336 StartMonitor(monitor).Wait();
340 //If the account is inactive
341 //Stop and remove the monitor
342 RemoveMonitor(account.ServerUrl,accountName);
348 //Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
349 monitor = new PithosMonitor
351 UserName = accountName,
352 ApiKey = account.ApiKey,
353 StatusNotification = this,
354 RootPath = account.RootPath
356 //PithosMonitor uses MEF so we need to resolve it
357 IoC.BuildUp(monitor);
359 monitor.AuthenticationUrl = account.ServerUrl;
361 Monitors[account.AccountKey] = monitor;
363 if (account.IsActive)
365 //Don't start a monitor if it doesn't have an account and ApiKey
366 if (String.IsNullOrWhiteSpace(monitor.UserName) ||
367 String.IsNullOrWhiteSpace(monitor.ApiKey))
369 StartMonitor(monitor);
374 private void MigrateFolders(AccountSettings account)
376 var oldOthersFolder=Path.Combine(account.RootPath, FolderConstants.OldOthersFolder);
377 var newOthersFolder = Path.Combine(account.RootPath, FolderConstants.OthersFolder);
378 var oldFolder = new DirectoryInfo(oldOthersFolder);
379 var newFolder = new DirectoryInfo(newOthersFolder);
381 if (oldFolder.Exists && !newFolder.Exists)
383 oldFolder.MoveTo(newOthersFolder);
388 protected override void OnViewLoaded(object view)
391 var window = (Window)view;
392 TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
393 base.OnViewLoaded(view);
397 #region Status Properties
399 private string _statusMessage;
400 public string StatusMessage
402 get { return _statusMessage; }
405 _statusMessage = value;
406 NotifyOfPropertyChange(() => StatusMessage);
407 NotifyOfPropertyChange(() => TooltipMessage);
411 public string VersionMessage { get; set; }
413 public string TooltipMessage
417 return String.Format("{0}\r\n{1}",VersionMessage,StatusMessage);
421 public string TooltipMiniStatus
425 return String.Format("{0}\r\n{1}", "Status Window", "Enable / Dissable the stuatus window");
429 public string ToggleStatusWindowMessage
433 return String.Format("{0}" + Environment.NewLine + "{1} Toggle Mini Status");
437 private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
438 public ObservableConcurrentCollection<AccountInfo> Accounts
440 get { return _accounts; }
443 public bool HasAccounts
445 get { return _accounts.Count > 0; }
449 public string OpenFolderCaption
453 return (_accounts.Count == 0)
454 ? "No Accounts Defined"
455 : "Open Pithos Folder";
459 private string _pauseSyncCaption="Pause Synching";
460 public string PauseSyncCaption
462 get { return _pauseSyncCaption; }
465 _pauseSyncCaption = value;
466 NotifyOfPropertyChange(() => PauseSyncCaption);
470 private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
471 public ObservableConcurrentCollection<FileEntry> RecentFiles
473 get { return _recentFiles; }
477 private string _statusIcon="../Images/Pithos.ico";
478 public string StatusIcon
480 get { return _statusIcon; }
483 //TODO: Ensure all status icons use the Pithos logo
485 NotifyOfPropertyChange(() => StatusIcon);
493 public void CancelCurrentOperation()
495 _networkAgent.CancelCurrentOperation();
498 public void ShowPreferences()
500 ShowPreferences(null);
503 public void ShowPreferences(string currentTab)
506 var preferences = new PreferencesViewModel(_windowManager, _events, this, Settings,currentTab);
507 _windowManager.ShowDialog(preferences);
511 public void AboutPithos()
513 var about = IoC.Get<AboutViewModel>();
514 about.LatestVersion=_sparkle.LatestVersion;
515 _windowManager.ShowWindow(about);
518 public void SendFeedback()
520 var feedBack = IoC.Get<FeedbackViewModel>();
521 _windowManager.ShowWindow(feedBack);
524 //public PithosCommand OpenPithosFolderCommand { get; private set; }
526 public void OpenPithosFolder()
528 var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
531 Process.Start(account.RootPath);
534 public void OpenPithosFolder(AccountInfo account)
536 Process.Start(account.AccountPath);
541 public void GoToSite()
543 var site = Properties.Settings.Default.ProductionServer;
548 public void GoToSite(AccountInfo account)
550 var uri = account.SiteUri.Replace("http://","https://");
554 private bool _statusVisible;
556 public string MiniStatusCaption
560 return _statusVisible ? "Hide Status Window" : "Show Status Window";
564 public bool HasConflicts
568 public void ShowConflicts()
570 _windowManager.ShowWindow(IoC.Get<ConflictsViewModel>());
574 /// Open an explorer window to the target path's directory
575 /// and select the file
577 /// <param name="entry"></param>
578 public void GoToFile(FileEntry entry)
580 var fullPath = entry.FullPath;
581 if (!File.Exists(fullPath) && !Directory.Exists(fullPath))
583 Process.Start("explorer.exe","/select, " + fullPath);
586 public void OpenLogPath()
588 var pithosDataPath = PithosSettings.PithosDataPath;
590 Process.Start(pithosDataPath);
593 public void ShowFileProperties()
595 var account = Settings.Accounts.First(acc => acc.IsActive);
596 var dir = new DirectoryInfo(account.RootPath + @"\pithos");
597 var files=dir.GetFiles();
599 var idx=r.Next(0, files.Length);
600 ShowFileProperties(files[idx].FullName);
603 public void ShowFileProperties(string filePath)
605 if (String.IsNullOrWhiteSpace(filePath))
606 throw new ArgumentNullException("filePath");
607 if (!File.Exists(filePath) && !Directory.Exists(filePath))
608 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
609 Contract.EndContractBlock();
611 var pair=(from monitor in Monitors
612 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
613 select monitor).FirstOrDefault();
614 var accountMonitor = pair.Value;
616 if (accountMonitor == null)
619 var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
623 var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
624 _windowManager.ShowWindow(fileProperties);
627 public void ShowContainerProperties()
629 var account = Settings.Accounts.First(acc => acc.IsActive);
630 var dir = new DirectoryInfo(account.RootPath);
631 var fullName = (from folder in dir.EnumerateDirectories()
632 where (folder.Attributes & FileAttributes.Hidden) == 0
633 select folder.FullName).First();
634 ShowContainerProperties(fullName);
637 public void ShowContainerProperties(string filePath)
639 if (String.IsNullOrWhiteSpace(filePath))
640 throw new ArgumentNullException("filePath");
641 if (!Directory.Exists(filePath))
642 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
643 Contract.EndContractBlock();
645 var pair=(from monitor in Monitors
646 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
647 select monitor).FirstOrDefault();
648 var accountMonitor = pair.Value;
649 var info = accountMonitor.GetContainerInfo(filePath);
653 var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
654 _windowManager.ShowWindow(containerProperties);
657 public void SynchNow()
659 _pollAgent.SynchNow();
662 public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
664 if (currentInfo==null)
665 throw new ArgumentNullException("currentInfo");
666 Contract.EndContractBlock();
667 var monitor = Monitors[currentInfo.AccountKey];
668 var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
672 public ContainerInfo RefreshContainerInfo(ContainerInfo container)
674 if (container == null)
675 throw new ArgumentNullException("container");
676 Contract.EndContractBlock();
678 var monitor = Monitors[container.AccountKey];
679 var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
683 private bool _isPaused;
686 get { return _isPaused; }
690 PauseSyncCaption = IsPaused ? "Resume syncing" : "Pause syncing";
691 var iconKey = IsPaused ? "TraySyncPaused" : "TrayInSynch";
692 StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
694 NotifyOfPropertyChange(() => IsPaused);
698 public void ToggleSynching()
701 foreach (var monitor in Monitors.Values)
703 monitor.Pause = IsPaused ;
705 _pollAgent.Pause = IsPaused;
706 _networkAgent.Pause = IsPaused;
711 public void ExitPithos()
716 foreach (var monitor in Monitors.Select(pair => pair.Value))
721 var view = GetView() as Window;
725 catch (Exception exc)
727 Log.Info("Exception while exiting", exc);
731 Application.Current.Shutdown();
738 private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
740 new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
741 new StatusInfo(PithosStatus.PollSyncing, "Polling Files", "TraySynching"),
742 new StatusInfo(PithosStatus.LocalSyncing, "Syncing Files", "TraySynching"),
743 new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
744 }.ToDictionary(s => s.Status);
746 readonly IWindowManager _windowManager;
748 //private int _syncCount=0;
751 private PithosStatus _pithosStatus = PithosStatus.Disconnected;
753 public void SetPithosStatus(PithosStatus status)
755 if (_pithosStatus == PithosStatus.LocalSyncing && status == PithosStatus.PollComplete)
757 if (_pithosStatus == PithosStatus.PollSyncing && status == PithosStatus.LocalComplete)
759 if (status == PithosStatus.LocalComplete || status == PithosStatus.PollComplete)
760 _pithosStatus = PithosStatus.InSynch;
762 _pithosStatus = status;
766 public void SetPithosStatus(PithosStatus status,string message)
768 StatusMessage = message;
769 SetPithosStatus(status);
772 /* public Notifier GetNotifier(Notification startNotification, Notification endNotification)
774 return new Notifier(this, startNotification, endNotification);
777 public Notifier GetNotifier(string startMessage, string endMessage, params object[] args)
779 return new Notifier(this,
780 new StatusNotification(String.Format(startMessage,args)),
781 new StatusNotification(String.Format(endMessage,args)));
786 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat
788 public void UpdateStatus()
791 if (_iconNames.ContainsKey(_pithosStatus))
793 var info = _iconNames[_pithosStatus];
794 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
797 if (_pithosStatus == PithosStatus.InSynch)
798 StatusMessage = "All files up to date";
803 private Task StartMonitor(PithosMonitor monitor,int retries=0)
805 return Task.Factory.StartNew(() =>
807 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
811 Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
815 catch (WebException exc)
817 if (AbandonRetry(monitor, retries))
820 HttpStatusCode statusCode =HttpStatusCode.OK;
821 var response = exc.Response as HttpWebResponse;
823 statusCode = response.StatusCode;
827 case HttpStatusCode.Unauthorized:
828 var message = String.Format("API Key Expired for {0}. Starting Renewal",
830 Log.Error(message, exc);
831 var account = Settings.Accounts.Find(acc => acc.AccountKey == new Uri(new Uri(monitor.AuthenticationUrl), monitor.UserName));
832 account.IsExpired = true;
833 Notify(new ExpirationNotification(account));
834 //TryAuthorize(monitor.UserName, retries).Wait();
836 case HttpStatusCode.ProxyAuthenticationRequired:
837 TryAuthenticateProxy(monitor,retries);
840 TryLater(monitor, exc, retries);
844 catch (Exception exc)
846 if (AbandonRetry(monitor, retries))
849 TryLater(monitor,exc,retries);
855 private void TryAuthenticateProxy(PithosMonitor monitor,int retries)
857 Execute.OnUIThread(() =>
859 var proxyAccount = IoC.Get<ProxyAccountViewModel>();
860 proxyAccount.Settings = Settings;
861 if (true != _windowManager.ShowDialog(proxyAccount))
863 StartMonitor(monitor, retries);
864 NotifyOfPropertyChange(() => Accounts);
868 private bool AbandonRetry(PithosMonitor monitor, int retries)
872 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
874 _events.Publish(new Notification
875 {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
882 private void TryLater(PithosMonitor monitor, Exception exc,int retries)
884 var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
885 Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
886 _events.Publish(new Notification
887 {Title = "Error", Message = message, Level = TraceLevel.Error});
888 Log.Error(message, exc);
892 public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
894 StatusMessage = status;
896 _events.Publish(new Notification { Title = "Pithos+", Message = status, Level = level });
899 public void NotifyChangedFile(string filePath)
901 if (RecentFiles.Any(e => e.FullPath == filePath))
904 IProducerConsumerCollection<FileEntry> files=RecentFiles;
906 while (files.Count > 5)
907 files.TryTake(out popped);
908 var entry = new FileEntry { FullPath = filePath };
912 public void NotifyAccount(AccountInfo account)
916 //TODO: What happens to an existing account whose Token has changed?
917 account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
918 account.SiteUri, Uri.EscapeDataString(account.Token),
919 Uri.EscapeDataString(account.UserName));
921 if (!Accounts.Any(item => item.UserName == account.UserName && item.SiteUri == account.SiteUri))
922 Accounts.TryAdd(account);
926 public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
928 if (conflictFiles == null)
930 //Convert to list to avoid multiple iterations
931 var files = conflictFiles.ToList();
936 //TODO: Create a more specific message. For now, just show a warning
937 NotifyForFiles(files,message,TraceLevel.Warning);
941 public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info)
948 StatusMessage = message;
950 _events.Publish(new Notification { Title = "Pithos+", Message = message, Level = level});
953 public void Notify(Notification notification)
955 _events.Publish(notification);
959 public void RemoveMonitor(string serverUrl,string accountName)
961 if (String.IsNullOrWhiteSpace(accountName))
964 var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName && account.StorageUri.ToString().StartsWith(serverUrl));
965 if (accountInfo != null)
967 _accounts.TryRemove(accountInfo);
968 _pollAgent.RemoveAccount(accountInfo);
971 var accountKey = new Uri(new Uri(serverUrl),accountName);
972 PithosMonitor monitor;
973 if (Monitors.TryRemove(accountKey, out monitor))
976 //TODO: Also remove any pending actions for this account
977 //from the network queue
981 public void RefreshOverlays()
983 foreach (var pair in Monitors)
985 var monitor = pair.Value;
987 var path = monitor.RootPath;
989 if (String.IsNullOrWhiteSpace(path))
992 if (!Directory.Exists(path) && !File.Exists(path))
995 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
999 NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
1000 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
1001 pathPointer, IntPtr.Zero);
1005 Marshal.FreeHGlobal(pathPointer);
1010 #region Event Handlers
1012 public void Handle(SelectiveSynchChanges message)
1016 PithosMonitor monitor;
1017 if (Monitors.TryGetValue(message.Account.AccountKey, out monitor))
1019 Selectives.SetIsSelectiveEnabled(message.Account.AccountKey, message.Enabled);
1020 monitor.SetSelectivePaths(message.Uris, message.Added, message.Removed);
1023 var account = Accounts.FirstOrDefault(acc => acc.AccountKey == message.Account.AccountKey);
1024 if (account != null)
1026 this._pollAgent.SetSelectivePaths(account, message.Added, message.Removed);
1033 private bool _pollStarted;
1034 private Sparkle _sparkle;
1035 private bool _manualUpgradeCheck;
1037 //SMELL: Doing so much work for notifications in the shell is wrong
1038 //The notifications should be moved to their own view/viewmodel pair
1039 //and different templates should be used for different message types
1040 //This will also allow the addition of extra functionality, eg. actions
1042 public void Handle(Notification notification)
1046 if (!Settings.ShowDesktopNotifications)
1049 if (notification is PollNotification)
1051 _pollStarted = true;
1054 if (notification is CloudNotification)
1058 _pollStarted= false;
1059 notification.Title = "Pithos+";
1060 notification.Message = "Start Synchronisation";
1063 var deleteNotification = notification as CloudDeleteNotification;
1064 if (deleteNotification != null)
1066 StatusMessage = String.Format("Deleted {0}", deleteNotification.Data.Name);
1070 var progress = notification as ProgressNotification;
1073 if (progress != null)
1075 StatusMessage = String.Format("{0} {1:p2} of {2} - {3}",
1077 progress.Block/(double)progress.TotalBlocks,
1078 progress.FileSize.ToByteSize(),
1083 var info = notification as StatusNotification;
1086 StatusMessage = info.Title;
1089 if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
1092 if (notification.Level <= TraceLevel.Warning)
1093 ShowBalloonFor(notification);
1096 private void ShowBalloonFor(Notification notification)
1098 Contract.Requires(notification!=null);
1100 if (!Settings.ShowDesktopNotifications)
1104 switch (notification.Level)
1106 case TraceLevel.Verbose:
1108 case TraceLevel.Info:
1109 icon = BalloonIcon.Info;
1111 case TraceLevel.Error:
1112 icon = BalloonIcon.Error;
1114 case TraceLevel.Warning:
1115 icon = BalloonIcon.Warning;
1121 var tv = (ShellView) GetView();
1122 System.Action clickAction = null;
1123 if (notification is ExpirationNotification)
1125 clickAction = () => ShowPreferences("AccountTab");
1127 var balloon = new PithosBalloon
1129 Title = notification.Title,
1130 Message = notification.Message,
1132 ClickAction = clickAction
1134 tv.TaskbarView.ShowCustomBalloon(balloon, PopupAnimation.Fade, 4000);
1139 public void Handle(ShowFilePropertiesEvent message)
1141 if (message == null)
1142 throw new ArgumentNullException("message");
1143 if (String.IsNullOrWhiteSpace(message.FileName) )
1144 throw new ArgumentException("message");
1145 Contract.EndContractBlock();
1147 var fileName = message.FileName;
1148 //TODO: Display file properties for non-container folders
1149 if (File.Exists(fileName))
1150 //Retrieve the full name with exact casing. Pithos names are case sensitive
1151 ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
1152 else if (Directory.Exists(fileName))
1153 //Retrieve the full name with exact casing. Pithos names are case sensitive
1155 var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
1156 if (IsContainer(path))
1157 ShowContainerProperties(path);
1159 ShowFileProperties(path);
1163 private bool IsContainer(string path)
1165 var matchingFolders = from account in _accounts
1166 from rootFolder in Directory.GetDirectories(account.AccountPath)
1167 where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
1169 return matchingFolders.Any();
1172 public FileStatus GetFileStatus(string localFileName)
1174 if (String.IsNullOrWhiteSpace(localFileName))
1175 throw new ArgumentNullException("localFileName");
1176 Contract.EndContractBlock();
1178 var statusKeeper = IoC.Get<IStatusKeeper>();
1179 var status=statusKeeper.GetFileStatus(localFileName);
1183 public void RemoveAccountFromDatabase(AccountSettings account)
1185 var statusKeeper = IoC.Get<IStatusKeeper>();
1186 statusKeeper.ClearFolderStatus(account.RootPath);