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 private MiniStatusViewModel _miniStatus;
132 public MiniStatusViewModel MiniStatus
134 get { return _miniStatus; }
138 _miniStatus.Shell = this;
139 _miniStatus.Deactivated += (sender, arg) =>
141 _statusVisible = false;
142 NotifyOfPropertyChange(()=>MiniStatusCaption);
148 /// The Shell depends on MEF to provide implementations for windowManager, events, the status checker service and the settings
151 /// The PithosSettings class encapsulates the app's settings to abstract their storage mechanism (App settings, a database or registry)
153 [ImportingConstructor]
154 public ShellViewModel(IWindowManager windowManager, IEventAggregator events, IStatusChecker statusChecker, PithosSettings settings,PollAgent pollAgent,NetworkAgent networkAgent)
159 _windowManager = windowManager;
160 //CHECK: Caliburn doesn't need explicit command construction
161 //OpenPithosFolderCommand = new PithosCommand(OpenPithosFolder);
162 _statusChecker = statusChecker;
165 _events.Subscribe(this);
167 _pollAgent = pollAgent;
168 _networkAgent = networkAgent;
171 Proxy.SetFromSettings(settings);
173 StatusMessage = Settings.Accounts.Count==0
174 ? "No Accounts added\r\nPlease add an account"
177 _accounts.CollectionChanged += (sender, e) =>
179 NotifyOfPropertyChange(() => OpenFolderCaption);
180 NotifyOfPropertyChange(() => HasAccounts);
185 catch (Exception exc)
187 Log.Error("Error while starting the ShellViewModel",exc);
193 private void SetVersionMessage()
195 Assembly assembly = Assembly.GetExecutingAssembly();
196 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
197 VersionMessage = String.Format("Pithos+ {0}", fileVersion.FileVersion);
200 public void CurrentSyncStatus()
202 if (Accounts.Count == 0)
204 ShowPreferences("AccountTab");
209 _windowManager.ShowWindow(MiniStatus);
212 if (MiniStatus.IsActive)
213 MiniStatus.TryClose();
215 _statusVisible = !_statusVisible;
217 NotifyOfPropertyChange(() => MiniStatusCaption);
221 protected override void OnActivate()
227 //Must delay opening the upgrade window
228 //to avoid Windows Messages sent by the TaskbarIcon
229 TaskEx.Delay(5000).ContinueWith(_=>
230 Execute.OnUIThread(()=> _sparkle.StartLoop(true,Settings.UpdateForceCheck,Settings.UpdateCheckInterval)));
237 private void OnCheckFinished(object sender, bool updaterequired)
240 Log.InfoFormat("Upgrade check finished. Need Upgrade: {0}", updaterequired);
241 if (_manualUpgradeCheck)
243 _manualUpgradeCheck = false;
245 //Sparkle raises events on a background thread
246 Execute.OnUIThread(()=>
247 ShowBalloonFor(new Notification{Title="Pithos+ is up to date",Message="You have the latest Pithos+ version. No update is required"}));
251 private void OnUpgradeDetected(object sender, UpdateDetectedEventArgs e)
253 Log.InfoFormat("Update detected {0}",e.LatestVersion);
256 public void CheckForUpgrade()
258 ShowBalloonFor(new Notification{Title="Checking for upgrades",Message="Contacting the server to retrieve the latest Pithos+ version."});
260 _sparkle.updateDetected -= OnUpgradeDetected;
261 _sparkle.checkLoopFinished -= OnCheckFinished;
264 _manualUpgradeCheck = true;
266 _sparkle.StartLoop(true,true,Settings.UpdateCheckInterval);
269 private void InitializeSparkle()
271 _sparkle = new Sparkle(Settings.UpdateUrl);
272 _sparkle.updateDetected += OnUpgradeDetected;
273 _sparkle.checkLoopFinished += OnCheckFinished;
274 _sparkle.ShowDiagnosticWindow = Settings.UpdateDiagnostics;
277 private async void StartMonitoring()
281 if (Settings.IgnoreCertificateErrors)
283 ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
286 var accounts = Settings.Accounts.Select(MonitorAccount);
287 await TaskEx.WhenAll(accounts);
288 _statusService = StatusService.Start();
291 catch (AggregateException exc)
295 Log.Error("Error while starting monitoring", e);
302 protected override void OnDeactivate(bool close)
304 base.OnDeactivate(close);
307 StatusService.Stop(_statusService);
308 _statusService = null;
312 public Task MonitorAccount(AccountSettings account)
314 return Task.Factory.StartNew(() =>
316 PithosMonitor monitor;
317 var accountName = account.AccountName;
319 if (Monitors.TryGetValue(account.AccountKey, out monitor))
321 //If the account is active
322 if (account.IsActive)
324 //The Api Key may have changed throuth the Preferences dialog
325 monitor.ApiKey = account.ApiKey;
326 Debug.Assert(monitor.StatusNotification == this,"An existing monitor should already have a StatusNotification service object");
327 monitor.RootPath = account.RootPath;
328 //Start the monitor. It's OK to start an already started monitor,
329 //it will just ignore the call
330 StartMonitor(monitor).Wait();
334 //If the account is inactive
335 //Stop and remove the monitor
336 RemoveMonitor(account.ServerUrl,accountName);
342 //Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
343 monitor = new PithosMonitor
345 UserName = accountName,
346 ApiKey = account.ApiKey,
347 StatusNotification = this,
348 RootPath = account.RootPath
350 //PithosMonitor uses MEF so we need to resolve it
351 IoC.BuildUp(monitor);
353 monitor.AuthenticationUrl = account.ServerUrl;
355 Monitors[account.AccountKey] = monitor;
357 if (account.IsActive)
359 //Don't start a monitor if it doesn't have an account and ApiKey
360 if (String.IsNullOrWhiteSpace(monitor.UserName) ||
361 String.IsNullOrWhiteSpace(monitor.ApiKey))
363 StartMonitor(monitor);
369 protected override void OnViewLoaded(object view)
372 var window = (Window)view;
373 TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
374 base.OnViewLoaded(view);
378 #region Status Properties
380 private string _statusMessage;
381 public string StatusMessage
383 get { return _statusMessage; }
386 _statusMessage = value;
387 NotifyOfPropertyChange(() => StatusMessage);
388 NotifyOfPropertyChange(() => TooltipMessage);
392 public string VersionMessage { get; set; }
394 public string TooltipMessage
398 return String.Format("{0}\r\n{1}",VersionMessage,StatusMessage);
402 public string TooltipMiniStatus
406 return String.Format("{0}\r\n{1}", "Status Window", "Enable / Dissable the stuatus window");
410 public string ToggleStatusWindowMessage
414 return String.Format("{0}" + Environment.NewLine + "{1} Toggle Mini Status");
418 private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
419 public ObservableConcurrentCollection<AccountInfo> Accounts
421 get { return _accounts; }
424 public bool HasAccounts
426 get { return _accounts.Count > 0; }
430 public string OpenFolderCaption
434 return (_accounts.Count == 0)
435 ? "No Accounts Defined"
436 : "Open Pithos Folder";
440 private string _pauseSyncCaption="Pause Synching";
441 public string PauseSyncCaption
443 get { return _pauseSyncCaption; }
446 _pauseSyncCaption = value;
447 NotifyOfPropertyChange(() => PauseSyncCaption);
451 private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
452 public ObservableConcurrentCollection<FileEntry> RecentFiles
454 get { return _recentFiles; }
458 private string _statusIcon="../Images/Pithos.ico";
459 public string StatusIcon
461 get { return _statusIcon; }
464 //TODO: Ensure all status icons use the Pithos logo
466 NotifyOfPropertyChange(() => StatusIcon);
474 public void CancelCurrentOperation()
476 _networkAgent.CancelCurrentOperation();
479 public void ShowPreferences()
481 ShowPreferences(null);
484 public void ShowPreferences(string currentTab)
487 var preferences = new PreferencesViewModel(_windowManager, _events, this, Settings,currentTab);
488 _windowManager.ShowDialog(preferences);
492 public void AboutPithos()
494 var about = IoC.Get<AboutViewModel>();
495 about.LatestVersion=_sparkle.LatestVersion;
496 _windowManager.ShowWindow(about);
499 public void SendFeedback()
501 var feedBack = IoC.Get<FeedbackViewModel>();
502 _windowManager.ShowWindow(feedBack);
505 //public PithosCommand OpenPithosFolderCommand { get; private set; }
507 public void OpenPithosFolder()
509 var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
512 Process.Start(account.RootPath);
515 public void OpenPithosFolder(AccountInfo account)
517 Process.Start(account.AccountPath);
522 public void GoToSite()
524 var site = Properties.Settings.Default.ProductionServer;
529 public void GoToSite(AccountInfo account)
531 var uri = account.SiteUri.Replace("http://","https://");
535 private bool _statusVisible;
537 public string MiniStatusCaption
541 return _statusVisible ? "Hide Status Window" : "Show Status Window";
545 public bool HasConflicts
549 public void ShowConflicts()
551 _windowManager.ShowWindow(IoC.Get<ConflictsViewModel>());
555 /// Open an explorer window to the target path's directory
556 /// and select the file
558 /// <param name="entry"></param>
559 public void GoToFile(FileEntry entry)
561 var fullPath = entry.FullPath;
562 if (!File.Exists(fullPath) && !Directory.Exists(fullPath))
564 Process.Start("explorer.exe","/select, " + fullPath);
567 public void OpenLogPath()
569 var pithosDataPath = PithosSettings.PithosDataPath;
571 Process.Start(pithosDataPath);
574 public void ShowFileProperties()
576 var account = Settings.Accounts.First(acc => acc.IsActive);
577 var dir = new DirectoryInfo(account.RootPath + @"\pithos");
578 var files=dir.GetFiles();
580 var idx=r.Next(0, files.Length);
581 ShowFileProperties(files[idx].FullName);
584 public void ShowFileProperties(string filePath)
586 if (String.IsNullOrWhiteSpace(filePath))
587 throw new ArgumentNullException("filePath");
588 if (!File.Exists(filePath) && !Directory.Exists(filePath))
589 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
590 Contract.EndContractBlock();
592 var pair=(from monitor in Monitors
593 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
594 select monitor).FirstOrDefault();
595 var accountMonitor = pair.Value;
597 if (accountMonitor == null)
600 var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
604 var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
605 _windowManager.ShowWindow(fileProperties);
608 public void ShowContainerProperties()
610 var account = Settings.Accounts.First(acc => acc.IsActive);
611 var dir = new DirectoryInfo(account.RootPath);
612 var fullName = (from folder in dir.EnumerateDirectories()
613 where (folder.Attributes & FileAttributes.Hidden) == 0
614 select folder.FullName).First();
615 ShowContainerProperties(fullName);
618 public void ShowContainerProperties(string filePath)
620 if (String.IsNullOrWhiteSpace(filePath))
621 throw new ArgumentNullException("filePath");
622 if (!Directory.Exists(filePath))
623 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
624 Contract.EndContractBlock();
626 var pair=(from monitor in Monitors
627 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
628 select monitor).FirstOrDefault();
629 var accountMonitor = pair.Value;
630 var info = accountMonitor.GetContainerInfo(filePath);
634 var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
635 _windowManager.ShowWindow(containerProperties);
638 public void SynchNow()
640 _pollAgent.SynchNow();
643 public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
645 if (currentInfo==null)
646 throw new ArgumentNullException("currentInfo");
647 Contract.EndContractBlock();
648 var monitor = Monitors[currentInfo.AccountKey];
649 var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
653 public ContainerInfo RefreshContainerInfo(ContainerInfo container)
655 if (container == null)
656 throw new ArgumentNullException("container");
657 Contract.EndContractBlock();
659 var monitor = Monitors[container.AccountKey];
660 var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
664 private bool _isPaused;
667 get { return _isPaused; }
671 PauseSyncCaption = IsPaused ? "Resume syncing" : "Pause syncing";
672 var iconKey = IsPaused ? "TraySyncPaused" : "TrayInSynch";
673 StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
675 NotifyOfPropertyChange(() => IsPaused);
679 public void ToggleSynching()
682 foreach (var monitor in Monitors.Values)
684 monitor.Pause = IsPaused ;
686 _pollAgent.Pause = IsPaused;
687 _networkAgent.Pause = IsPaused;
692 public void ExitPithos()
697 foreach (var monitor in Monitors.Select(pair => pair.Value))
702 var view = GetView() as Window;
706 catch (Exception exc)
708 Log.Info("Exception while exiting", exc);
712 Application.Current.Shutdown();
719 private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
721 new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
722 new StatusInfo(PithosStatus.PollSyncing, "Polling Files", "TraySynching"),
723 new StatusInfo(PithosStatus.LocalSyncing, "Syncing Files", "TraySynching"),
724 new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
725 }.ToDictionary(s => s.Status);
727 readonly IWindowManager _windowManager;
729 //private int _syncCount=0;
732 private PithosStatus _pithosStatus = PithosStatus.Disconnected;
734 public void SetPithosStatus(PithosStatus status)
736 if (_pithosStatus == PithosStatus.LocalSyncing && status == PithosStatus.PollComplete)
738 if (_pithosStatus == PithosStatus.PollSyncing && status == PithosStatus.LocalComplete)
740 if (status == PithosStatus.LocalComplete || status == PithosStatus.PollComplete)
741 _pithosStatus = PithosStatus.InSynch;
743 _pithosStatus = status;
747 public void SetPithosStatus(PithosStatus status,string message)
749 StatusMessage = message;
750 SetPithosStatus(status);
753 /* public Notifier GetNotifier(Notification startNotification, Notification endNotification)
755 return new Notifier(this, startNotification, endNotification);
758 public Notifier GetNotifier(string startMessage, string endMessage, params object[] args)
760 return new Notifier(this,
761 new StatusNotification(String.Format(startMessage,args)),
762 new StatusNotification(String.Format(endMessage,args)));
767 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat
769 public void UpdateStatus()
772 if (_iconNames.ContainsKey(_pithosStatus))
774 var info = _iconNames[_pithosStatus];
775 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
778 if (_pithosStatus == PithosStatus.InSynch)
779 StatusMessage = "All files up to date";
784 private Task StartMonitor(PithosMonitor monitor,int retries=0)
786 return Task.Factory.StartNew(() =>
788 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
792 Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
796 catch (WebException exc)
798 if (AbandonRetry(monitor, retries))
801 HttpStatusCode statusCode =HttpStatusCode.OK;
802 var response = exc.Response as HttpWebResponse;
804 statusCode = response.StatusCode;
808 case HttpStatusCode.Unauthorized:
809 var message = String.Format("API Key Expired for {0}. Starting Renewal",
811 Log.Error(message, exc);
812 var account = Settings.Accounts.Find(acc => acc.AccountKey == new Uri(new Uri(monitor.AuthenticationUrl), monitor.UserName));
813 account.IsExpired = true;
814 Notify(new ExpirationNotification(account));
815 //TryAuthorize(monitor.UserName, retries).Wait();
817 case HttpStatusCode.ProxyAuthenticationRequired:
818 TryAuthenticateProxy(monitor,retries);
821 TryLater(monitor, exc, retries);
825 catch (Exception exc)
827 if (AbandonRetry(monitor, retries))
830 TryLater(monitor,exc,retries);
836 private void TryAuthenticateProxy(PithosMonitor monitor,int retries)
838 Execute.OnUIThread(() =>
840 var proxyAccount = IoC.Get<ProxyAccountViewModel>();
841 proxyAccount.Settings = Settings;
842 if (true != _windowManager.ShowDialog(proxyAccount))
844 StartMonitor(monitor, retries);
845 NotifyOfPropertyChange(() => Accounts);
849 private bool AbandonRetry(PithosMonitor monitor, int retries)
853 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
855 _events.Publish(new Notification
856 {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
863 private void TryLater(PithosMonitor monitor, Exception exc,int retries)
865 var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
866 Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
867 _events.Publish(new Notification
868 {Title = "Error", Message = message, Level = TraceLevel.Error});
869 Log.Error(message, exc);
873 public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
875 StatusMessage = status;
877 _events.Publish(new Notification { Title = "Pithos+", Message = status, Level = level });
880 public void NotifyChangedFile(string filePath)
882 if (RecentFiles.Any(e => e.FullPath == filePath))
885 IProducerConsumerCollection<FileEntry> files=RecentFiles;
887 while (files.Count > 5)
888 files.TryTake(out popped);
889 var entry = new FileEntry { FullPath = filePath };
893 public void NotifyAccount(AccountInfo account)
897 //TODO: What happens to an existing account whose Token has changed?
898 account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
899 account.SiteUri, Uri.EscapeDataString(account.Token),
900 Uri.EscapeDataString(account.UserName));
902 if (!Accounts.Any(item => item.UserName == account.UserName && item.SiteUri == account.SiteUri))
903 Accounts.TryAdd(account);
907 public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
909 if (conflictFiles == null)
911 //Convert to list to avoid multiple iterations
912 var files = conflictFiles.ToList();
917 //TODO: Create a more specific message. For now, just show a warning
918 NotifyForFiles(files,message,TraceLevel.Warning);
922 public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info)
929 StatusMessage = message;
931 _events.Publish(new Notification { Title = "Pithos+", Message = message, Level = level});
934 public void Notify(Notification notification)
936 _events.Publish(notification);
940 public void RemoveMonitor(string serverUrl,string accountName)
942 if (String.IsNullOrWhiteSpace(accountName))
945 var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName && account.StorageUri.ToString().StartsWith(serverUrl));
946 if (accountInfo != null)
948 _accounts.TryRemove(accountInfo);
949 _pollAgent.RemoveAccount(accountInfo);
952 var accountKey = new Uri(new Uri(serverUrl),accountName);
953 PithosMonitor monitor;
954 if (Monitors.TryRemove(accountKey, out monitor))
957 //TODO: Also remove any pending actions for this account
958 //from the network queue
962 public void RefreshOverlays()
964 foreach (var pair in Monitors)
966 var monitor = pair.Value;
968 var path = monitor.RootPath;
970 if (String.IsNullOrWhiteSpace(path))
973 if (!Directory.Exists(path) && !File.Exists(path))
976 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
980 NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
981 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
982 pathPointer, IntPtr.Zero);
986 Marshal.FreeHGlobal(pathPointer);
991 #region Event Handlers
993 public void Handle(SelectiveSynchChanges message)
997 PithosMonitor monitor;
998 if (Monitors.TryGetValue(message.Account.AccountKey, out monitor))
1000 monitor.SetSelectivePaths(message.Uris, message.Added, message.Removed);
1003 var account = Accounts.FirstOrDefault(acc => acc.AccountKey == message.Account.AccountKey);
1004 if (account != null)
1006 this._pollAgent.SetSelectivePaths(account, message.Added, message.Removed);
1013 private bool _pollStarted;
1014 private Sparkle _sparkle;
1015 private bool _manualUpgradeCheck;
1017 //SMELL: Doing so much work for notifications in the shell is wrong
1018 //The notifications should be moved to their own view/viewmodel pair
1019 //and different templates should be used for different message types
1020 //This will also allow the addition of extra functionality, eg. actions
1022 public void Handle(Notification notification)
1026 if (!Settings.ShowDesktopNotifications)
1029 if (notification is PollNotification)
1031 _pollStarted = true;
1034 if (notification is CloudNotification)
1038 _pollStarted= false;
1039 notification.Title = "Pithos+";
1040 notification.Message = "Start Synchronisation";
1043 var deleteNotification = notification as CloudDeleteNotification;
1044 if (deleteNotification != null)
1046 StatusMessage = String.Format("Deleted {0}", deleteNotification.Data.Name);
1050 var progress = notification as ProgressNotification;
1053 if (progress != null)
1055 StatusMessage = String.Format("{0} {1:p2} of {2} - {3}",
1057 progress.Block/(double)progress.TotalBlocks,
1058 progress.FileSize.ToByteSize(),
1063 var info = notification as StatusNotification;
1066 StatusMessage = info.Title;
1069 if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
1072 if (notification.Level <= TraceLevel.Warning)
1073 ShowBalloonFor(notification);
1076 private void ShowBalloonFor(Notification notification)
1078 Contract.Requires(notification!=null);
1080 if (!Settings.ShowDesktopNotifications)
1084 switch (notification.Level)
1086 case TraceLevel.Verbose:
1088 case TraceLevel.Info:
1089 icon = BalloonIcon.Info;
1091 case TraceLevel.Error:
1092 icon = BalloonIcon.Error;
1094 case TraceLevel.Warning:
1095 icon = BalloonIcon.Warning;
1101 var tv = (ShellView) GetView();
1102 System.Action clickAction = null;
1103 if (notification is ExpirationNotification)
1105 clickAction = () => ShowPreferences("AccountTab");
1107 var balloon = new PithosBalloon
1109 Title = notification.Title,
1110 Message = notification.Message,
1112 ClickAction = clickAction
1114 tv.TaskbarView.ShowCustomBalloon(balloon, PopupAnimation.Fade, 4000);
1119 public void Handle(ShowFilePropertiesEvent message)
1121 if (message == null)
1122 throw new ArgumentNullException("message");
1123 if (String.IsNullOrWhiteSpace(message.FileName) )
1124 throw new ArgumentException("message");
1125 Contract.EndContractBlock();
1127 var fileName = message.FileName;
1128 //TODO: Display file properties for non-container folders
1129 if (File.Exists(fileName))
1130 //Retrieve the full name with exact casing. Pithos names are case sensitive
1131 ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
1132 else if (Directory.Exists(fileName))
1133 //Retrieve the full name with exact casing. Pithos names are case sensitive
1135 var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
1136 if (IsContainer(path))
1137 ShowContainerProperties(path);
1139 ShowFileProperties(path);
1143 private bool IsContainer(string path)
1145 var matchingFolders = from account in _accounts
1146 from rootFolder in Directory.GetDirectories(account.AccountPath)
1147 where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
1149 return matchingFolders.Any();
1152 public FileStatus GetFileStatus(string localFileName)
1154 if (String.IsNullOrWhiteSpace(localFileName))
1155 throw new ArgumentNullException("localFileName");
1156 Contract.EndContractBlock();
1158 var statusKeeper = IoC.Get<IStatusKeeper>();
1159 var status=statusKeeper.GetFileStatus(localFileName);
1163 public void RemoveAccountFromDatabase(AccountSettings account)
1165 var statusKeeper = IoC.Get<IStatusKeeper>();
1166 statusKeeper.ClearFolderStatus(account.RootPath);