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;
51 using System.Threading.Tasks;
53 using System.Windows.Controls.Primitives;
54 using System.Windows.Input;
55 using AppLimit.NetSparkle;
57 using Hardcodet.Wpf.TaskbarNotification;
58 using Pithos.Client.WPF.Configuration;
59 using Pithos.Client.WPF.FileProperties;
60 using Pithos.Client.WPF.Preferences;
61 using Pithos.Client.WPF.SelectiveSynch;
62 using Pithos.Client.WPF.Services;
63 using Pithos.Client.WPF.Shell;
65 using Pithos.Core.Agents;
66 using Pithos.Interfaces;
68 using System.Collections.Generic;
71 using StatusService = Pithos.Client.WPF.Services.StatusService;
73 namespace Pithos.Client.WPF {
74 using System.ComponentModel.Composition;
76 public class ToggleStatusCommand:ICommand
78 private readonly ShellViewModel _model;
79 public ToggleStatusCommand(ShellViewModel model)
83 public void Execute(object parameter)
85 _model.CurrentSyncStatus();
88 public bool CanExecute(object parameter)
93 public event EventHandler CanExecuteChanged;
98 /// The "shell" of the Pithos application displays the taskbar icon, menu and notifications.
99 /// The shell also hosts the status service called by shell extensions to retrieve file info
102 /// It is a strange "shell" as its main visible element is an icon instead of a window
103 /// The shell subscribes to the following events:
104 /// * Notification: Raised by components that want to notify the user. Usually displayed in a balloon
105 /// * 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
106 /// * ShowFilePropertiesEvent: Raised when a shell command requests the display of the file/container properties dialog
108 //TODO: CODE SMELL Why does the shell handle the SelectiveSynchChanges?
109 [Export(typeof(IShell)), Export(typeof(ShellViewModel)),Export(typeof(IStatusNotification))]
110 public class ShellViewModel : Screen, IStatusNotification, IShell,
111 IHandle<Notification>, IHandle<SelectiveSynchChanges>, IHandle<ShowFilePropertiesEvent>
114 private readonly IEventAggregator _events;
116 public PithosSettings Settings { get; private set; }
119 private readonly ConcurrentDictionary<Uri, PithosMonitor> _monitors = new ConcurrentDictionary<Uri, PithosMonitor>();
121 /// Dictionary of account monitors, keyed by account
124 /// One monitor class is created for each account. The Shell needs access to the monitors to execute start/stop/pause commands,
125 /// retrieve account and boject info
127 // TODO: Does the Shell REALLY need access to the monitors? Could we achieve the same results with a better design?
128 // TODO: The monitors should be internal to Pithos.Core, even though exposing them makes coding of the Object and Container windows easier
129 public ConcurrentDictionary<Uri, PithosMonitor> Monitors
131 get { return _monitors; }
136 /// The status service is used by Shell extensions to retrieve file status information
138 //TODO: CODE SMELL! This is the shell! While hosting in the shell makes executing start/stop commands easier, it is still a smell
139 private ServiceHost _statusService;
141 //Logging in the Pithos client is provided by log4net
142 private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
145 private PollAgent _pollAgent;
148 private NetworkAgent _networkAgent;
151 public Selectives Selectives { get; set; }
154 public ToggleStatusCommand ToggleMiniStatusCommand { get; set; }
156 private MiniStatusViewModel _miniStatus;
159 public MiniStatusViewModel MiniStatus
161 get { return _miniStatus; }
165 _miniStatus.Shell = this;
166 _miniStatus.Deactivated += (sender, arg) =>
168 _statusVisible = false;
169 NotifyOfPropertyChange(()=>MiniStatusCaption);
175 /// The Shell depends on MEF to provide implementations for windowManager, events, the status checker service and the settings
178 /// The PithosSettings class encapsulates the app's settings to abstract their storage mechanism (App settings, a database or registry)
180 [ImportingConstructor]
181 public ShellViewModel(IWindowManager windowManager, IEventAggregator events, PithosSettings settings/*,PollAgent pollAgent,NetworkAgent networkAgent*/)
186 _windowManager = windowManager;
187 //CHECK: Caliburn doesn't need explicit command construction
188 //CurrentSyncStatusCommand = new PithosCommand(OpenPithosFolder);
191 _events.Subscribe(this);
194 _pollAgent = pollAgent;
195 _networkAgent = networkAgent;
199 Proxy.SetFromSettings(settings);
201 StatusMessage = Settings.Accounts.Count==0
202 ? "No Accounts added\r\nPlease add an account"
205 _accounts.CollectionChanged += (sender, e) =>
207 NotifyOfPropertyChange(() => OpenFolderCaption);
208 NotifyOfPropertyChange(() => HasAccounts);
213 ToggleMiniStatusCommand=new ToggleStatusCommand(this);
215 catch (Exception exc)
217 Log.Error("Error while starting the ShellViewModel",exc);
223 private void SetVersionMessage()
225 Assembly assembly = Assembly.GetExecutingAssembly();
226 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
227 VersionMessage = String.Format("Pithos+ {0}", fileVersion.FileVersion);
230 public void CurrentSyncStatus()
232 if (Accounts.Count == 0)
234 ShowPreferences("AccountTab");
240 _windowManager.ShowWindow(MiniStatus);
241 _statusVisible = true;
245 if (MiniStatus.IsActive)
246 MiniStatus.TryClose();
247 _statusVisible = false;
250 NotifyOfPropertyChange(() => MiniStatusCaption);
254 protected override void OnActivate()
260 //Must delay opening the upgrade window
261 //to avoid Windows Messages sent by the TaskbarIcon
262 TaskEx.Delay(5000).ContinueWith(_=>
263 Execute.OnUIThread(()=> _sparkle.StartLoop(true,Settings.UpdateForceCheck,Settings.UpdateCheckInterval)));
270 private void OnCheckFinished(object sender, bool updaterequired)
273 Log.InfoFormat("Upgrade check finished. Need Upgrade: {0}", updaterequired);
274 if (_manualUpgradeCheck)
276 _manualUpgradeCheck = false;
278 //Sparkle raises events on a background thread
279 Execute.OnUIThread(()=>
280 ShowBalloonFor(new Notification{Title="Pithos+ is up to date",Message="You have the latest Pithos+ version. No update is required"}));
284 private void OnUpgradeDetected(object sender, UpdateDetectedEventArgs e)
286 Log.InfoFormat("Update detected {0}",e.LatestVersion);
289 public void CheckForUpgrade()
291 ShowBalloonFor(new Notification{Title="Checking for upgrades",Message="Contacting the server to retrieve the latest Pithos+ version."});
293 _sparkle.updateDetected -= OnUpgradeDetected;
294 _sparkle.checkLoopFinished -= OnCheckFinished;
297 _manualUpgradeCheck = true;
299 _sparkle.StartLoop(true,true,Settings.UpdateCheckInterval);
302 private void InitializeSparkle()
304 _sparkle = new Sparkle(Settings.UpdateUrl);
305 _sparkle.updateDetected += OnUpgradeDetected;
306 _sparkle.checkLoopFinished += OnCheckFinished;
307 _sparkle.ShowDiagnosticWindow = Settings.UpdateDiagnostics;
310 private async void StartMonitoring()
314 if (Settings.IgnoreCertificateErrors)
316 ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
319 var accounts = Settings.Accounts.Select(MonitorAccount);
320 await TaskEx.WhenAll(accounts).ConfigureAwait(false);
321 _statusService = StatusService.Start();
324 catch (AggregateException exc)
328 Log.Error("Error while starting monitoring", e);
335 protected override void OnDeactivate(bool close)
337 base.OnDeactivate(close);
340 StatusService.Stop(_statusService);
341 _statusService = null;
345 public Task MonitorAccount(AccountSettings account)
347 return Task.Factory.StartNew(() =>
349 PithosMonitor monitor;
350 var accountName = account.AccountName;
352 MigrateFolders(account);
354 Selectives.SetIsSelectiveEnabled(account.AccountKey, account.SelectiveSyncEnabled);
356 if (Monitors.TryGetValue(account.AccountKey, out monitor))
358 //If the account is active
359 if (account.IsActive)
361 //The Api Key may have changed throuth the Preferences dialog
362 monitor.ApiKey = account.ApiKey;
363 Debug.Assert(monitor.StatusNotification == this,"An existing monitor should already have a StatusNotification service object");
364 monitor.RootPath = account.RootPath;
365 //Start the monitor. It's OK to start an already started monitor,
366 //it will just ignore the call
367 StartMonitor(monitor).Wait();
371 //If the account is inactive
372 //Stop and remove the monitor
373 RemoveMonitor(account.ServerUrl,accountName);
379 //Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
380 monitor = new PithosMonitor
382 UserName = accountName,
383 ApiKey = account.ApiKey,
384 StatusNotification = this,
385 RootPath = account.RootPath
387 //PithosMonitor uses MEF so we need to resolve it
388 IoC.BuildUp(monitor);
390 monitor.AuthenticationUrl = account.ServerUrl;
392 Monitors[account.AccountKey] = monitor;
394 if (account.IsActive)
396 //Don't start a monitor if it doesn't have an account and ApiKey
397 if (String.IsNullOrWhiteSpace(monitor.UserName) ||
398 String.IsNullOrWhiteSpace(monitor.ApiKey))
400 StartMonitor(monitor);
405 private void MigrateFolders(AccountSettings account)
407 var oldOthersFolder=Path.Combine(account.RootPath, FolderConstants.OldOthersFolder);
408 var newOthersFolder = Path.Combine(account.RootPath, FolderConstants.OthersFolder);
409 var oldFolder = new DirectoryInfo(oldOthersFolder);
410 var newFolder = new DirectoryInfo(newOthersFolder);
412 if (oldFolder.Exists && !newFolder.Exists)
414 oldFolder.MoveTo(newOthersFolder);
419 protected override void OnViewLoaded(object view)
422 var window = (Window)view;
423 TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
424 base.OnViewLoaded(view);
428 #region Status Properties
430 private string _statusMessage;
431 public string StatusMessage
433 get { return _statusMessage; }
436 _statusMessage = value;
437 NotifyOfPropertyChange(() => StatusMessage);
438 NotifyOfPropertyChange(() => TooltipMessage);
442 public string VersionMessage { get; set; }
444 public string TooltipMessage
448 return String.Format("{0}\r\n{1}",VersionMessage,StatusMessage);
452 public string TooltipMiniStatus
456 return String.Format("{0}\r\n{1}", "Status Window", "Enable / Disable the status window");
460 /*public string ToggleStatusWindowMessage
464 return String.Format("{0}" + Environment.NewLine + "{1} Toggle Mini Status");
468 private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
469 public ObservableConcurrentCollection<AccountInfo> Accounts
471 get { return _accounts; }
474 public bool HasAccounts
476 get { return _accounts.Count > 0; }
480 public string OpenFolderCaption
484 return (_accounts.Count == 0)
485 ? "No Accounts Defined"
486 : "Open Pithos Folder";
490 private string _pauseSyncCaption="Pause Synching";
491 public string PauseSyncCaption
493 get { return _pauseSyncCaption; }
496 _pauseSyncCaption = value;
497 NotifyOfPropertyChange(() => PauseSyncCaption);
501 private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
502 public ObservableConcurrentCollection<FileEntry> RecentFiles
504 get { return _recentFiles; }
508 private string _statusIcon="../Images/Pithos.ico";
509 public string StatusIcon
511 get { return _statusIcon; }
514 //TODO: Ensure all status icons use the Pithos logo
516 NotifyOfPropertyChange(() => StatusIcon);
524 public void CancelCurrentOperation()
526 _networkAgent.CancelCurrentOperation();
529 public void ShowPreferences()
531 ShowPreferences(null);
534 public void ShowPreferences(string currentTab)
538 var preferences = new PreferencesViewModel(_windowManager, _events, this, Settings,currentTab);
539 _windowManager.ShowDialog(preferences);
543 public void AboutPithos()
545 var about = IoC.Get<AboutViewModel>();
546 about.LatestVersion=_sparkle.LatestVersion;
547 _windowManager.ShowWindow(about);
550 public void SendFeedback()
552 var feedBack = IoC.Get<FeedbackViewModel>();
553 _windowManager.ShowWindow(feedBack);
556 //public PithosCommand OpenPithosFolderCommand { get; private set; }
558 public void OpenPithosFolder()
560 var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
563 Process.Start(account.RootPath);
566 public void OpenPithosFolder(AccountInfo account)
568 Process.Start(account.AccountPath);
573 public void GoToSite()
575 var site = Properties.Settings.Default.ProductionServer;
580 public void GoToSite(AccountInfo account)
582 var uri = account.SiteUri.Replace("http://","https://");
586 private bool _statusVisible;
588 public string MiniStatusCaption
592 return _statusVisible ? "Hide Status Window" : "Show Status Window";
596 public bool HasConflicts
600 public void ShowConflicts()
602 _windowManager.ShowWindow(IoC.Get<ConflictsViewModel>());
606 /// Open an explorer window to the target path's directory
607 /// and select the file
609 /// <param name="entry"></param>
610 public void GoToFile(FileEntry entry)
612 var fullPath = entry.FullPath;
613 if (!File.Exists(fullPath) && !Directory.Exists(fullPath))
615 Process.Start("explorer.exe","/select, " + fullPath);
618 public void OpenLogPath()
620 var pithosDataPath = PithosSettings.PithosDataPath;
622 Process.Start(pithosDataPath);
625 public void ShowFileProperties()
627 var account = Settings.Accounts.First(acc => acc.IsActive);
628 var dir = new DirectoryInfo(account.RootPath + @"\pithos");
629 var files=dir.GetFiles();
631 var idx=r.Next(0, files.Length);
632 ShowFileProperties(files[idx].FullName);
635 public void ShowFileProperties(string filePath)
637 if (String.IsNullOrWhiteSpace(filePath))
638 throw new ArgumentNullException("filePath");
639 if (!File.Exists(filePath) && !Directory.Exists(filePath))
640 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
641 Contract.EndContractBlock();
643 var pair=(from monitor in Monitors
644 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
645 select monitor).FirstOrDefault();
646 var accountMonitor = pair.Value;
648 if (accountMonitor == null)
651 var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
655 var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
656 _windowManager.ShowWindow(fileProperties);
659 public void ShowContainerProperties()
661 var account = Settings.Accounts.First(acc => acc.IsActive);
662 var dir = new DirectoryInfo(account.RootPath);
663 var fullName = (from folder in dir.EnumerateDirectories()
664 where (folder.Attributes & FileAttributes.Hidden) == 0
665 select folder.FullName).First();
666 ShowContainerProperties(fullName);
669 public void ShowContainerProperties(string filePath)
671 if (String.IsNullOrWhiteSpace(filePath))
672 throw new ArgumentNullException("filePath");
673 if (!Directory.Exists(filePath))
674 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
675 Contract.EndContractBlock();
677 var pair=(from monitor in Monitors
678 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
679 select monitor).FirstOrDefault();
680 var accountMonitor = pair.Value;
681 var info = accountMonitor.GetContainerInfo(filePath);
685 var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
686 _windowManager.ShowWindow(containerProperties);
689 public void SynchNow()
691 _pollAgent.SynchNow();
694 public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
696 if (currentInfo==null)
697 throw new ArgumentNullException("currentInfo");
698 Contract.EndContractBlock();
699 var monitor = Monitors[currentInfo.AccountKey];
700 var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
704 public ContainerInfo RefreshContainerInfo(ContainerInfo container)
706 if (container == null)
707 throw new ArgumentNullException("container");
708 Contract.EndContractBlock();
710 var monitor = Monitors[container.AccountKey];
711 var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
715 private bool _isPaused;
718 get { return _isPaused; }
722 PauseSyncCaption = IsPaused ? "Resume syncing" : "Pause syncing";
723 var iconKey = IsPaused ? "TraySyncPaused" : "TrayInSynch";
724 StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
726 NotifyOfPropertyChange(() => IsPaused);
730 public void ToggleSynching()
733 foreach (var monitor in Monitors.Values)
735 monitor.Pause = IsPaused ;
737 _pollAgent.Pause = IsPaused;
738 _networkAgent.Pause = IsPaused;
743 public void ExitPithos()
748 foreach (var monitor in Monitors.Select(pair => pair.Value))
753 var view = GetView() as Window;
757 catch (Exception exc)
759 Log.Info("Exception while exiting", exc);
763 Application.Current.Shutdown();
770 private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
772 new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
773 new StatusInfo(PithosStatus.PollSyncing, "Polling Files", "TraySynching"),
774 new StatusInfo(PithosStatus.LocalSyncing, "Syncing Files", "TraySynching"),
775 new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
776 }.ToDictionary(s => s.Status);
778 readonly IWindowManager _windowManager;
780 //private int _syncCount=0;
783 private PithosStatus _pithosStatus = PithosStatus.Disconnected;
785 public void SetPithosStatus(PithosStatus status)
787 if (_pithosStatus == PithosStatus.LocalSyncing && status == PithosStatus.PollComplete)
789 if (_pithosStatus == PithosStatus.PollSyncing && status == PithosStatus.LocalComplete)
791 if (status == PithosStatus.LocalComplete || status == PithosStatus.PollComplete)
792 _pithosStatus = PithosStatus.InSynch;
794 _pithosStatus = status;
798 public void SetPithosStatus(PithosStatus status,string message)
800 StatusMessage = message;
801 SetPithosStatus(status);
804 /* public Notifier GetNotifier(Notification startNotification, Notification endNotification)
806 return new Notifier(this, startNotification, endNotification);
809 public Notifier GetNotifier(string startMessage, string endMessage, params object[] args)
811 return new Notifier(this,
812 new StatusNotification(String.Format(startMessage,args)),
813 new StatusNotification(String.Format(endMessage,args)));
818 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat
820 public void UpdateStatus()
823 if (_iconNames.ContainsKey(_pithosStatus))
825 var info = _iconNames[_pithosStatus];
826 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
829 if (_pithosStatus == PithosStatus.InSynch)
830 StatusMessage = "All files up to date";
835 private Task StartMonitor(PithosMonitor monitor,int retries=0)
837 return Task.Factory.StartNew(() =>
839 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
843 Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
847 catch (WebException exc)
849 if (AbandonRetry(monitor, retries))
852 HttpStatusCode statusCode =HttpStatusCode.OK;
853 var response = exc.Response as HttpWebResponse;
855 statusCode = response.StatusCode;
859 case HttpStatusCode.Unauthorized:
860 var message = String.Format("API Key Expired for {0}. Starting Renewal",
862 Log.Error(message, exc);
863 var account = Settings.Accounts.Find(acc => acc.AccountKey == new Uri(new Uri(monitor.AuthenticationUrl), monitor.UserName));
864 account.IsExpired = true;
865 Notify(new ExpirationNotification(account));
866 //TryAuthorize(monitor.UserName, retries).Wait();
868 case HttpStatusCode.ProxyAuthenticationRequired:
869 TryAuthenticateProxy(monitor,retries);
872 TryLater(monitor, exc, retries);
876 catch (Exception exc)
878 if (AbandonRetry(monitor, retries))
881 TryLater(monitor,exc,retries);
887 private void TryAuthenticateProxy(PithosMonitor monitor,int retries)
889 Execute.OnUIThread(() =>
891 var proxyAccount = IoC.Get<ProxyAccountViewModel>();
892 proxyAccount.Settings = Settings;
893 if (true != _windowManager.ShowDialog(proxyAccount))
895 StartMonitor(monitor, retries);
896 NotifyOfPropertyChange(() => Accounts);
900 private bool AbandonRetry(PithosMonitor monitor, int retries)
904 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
906 _events.Publish(new Notification
907 {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
914 private void TryLater(PithosMonitor monitor, Exception exc,int retries)
916 var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
917 Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
918 _events.Publish(new Notification
919 {Title = "Error", Message = message, Level = TraceLevel.Error});
920 Log.Error(message, exc);
924 public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
926 StatusMessage = status;
928 _events.Publish(new Notification { Title = "Pithos+", Message = status, Level = level });
931 public void NotifyChangedFile(string filePath)
933 if (RecentFiles.Any(e => e.FullPath == filePath))
936 IProducerConsumerCollection<FileEntry> files=RecentFiles;
938 while (files.Count > 5)
939 files.TryTake(out popped);
940 var entry = new FileEntry { FullPath = filePath };
944 public void NotifyAccount(AccountInfo account)
948 //TODO: What happens to an existing account whose Token has changed?
949 account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
950 account.SiteUri, Uri.EscapeDataString(account.Token),
951 Uri.EscapeDataString(account.UserName));
953 if (!Accounts.Any(item => item.UserName == account.UserName && item.SiteUri == account.SiteUri))
954 Accounts.TryAdd(account);
958 public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
960 if (conflictFiles == null)
962 //Convert to list to avoid multiple iterations
963 var files = conflictFiles.ToList();
968 //TODO: Create a more specific message. For now, just show a warning
969 NotifyForFiles(files,message,TraceLevel.Warning);
973 public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info)
980 StatusMessage = message;
982 _events.Publish(new Notification { Title = "Pithos+", Message = message, Level = level});
985 public void Notify(Notification notification)
987 TaskEx.Run(()=> _events.Publish(notification));
991 public void RemoveMonitor(string serverUrl,string accountName)
993 if (String.IsNullOrWhiteSpace(accountName))
996 var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName && account.StorageUri.ToString().StartsWith(serverUrl));
997 if (accountInfo != null)
999 _accounts.TryRemove(accountInfo);
1000 _pollAgent.RemoveAccount(accountInfo);
1003 var accountKey = new Uri(new Uri(serverUrl),accountName);
1004 PithosMonitor monitor;
1005 if (Monitors.TryRemove(accountKey, out monitor))
1008 //TODO: Also remove any pending actions for this account
1009 //from the network queue
1013 public void RefreshOverlays()
1015 foreach (var pair in Monitors)
1017 var monitor = pair.Value;
1019 var path = monitor.RootPath;
1021 if (String.IsNullOrWhiteSpace(path))
1024 if (!Directory.Exists(path) && !File.Exists(path))
1027 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
1031 NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
1032 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
1033 pathPointer, IntPtr.Zero);
1037 Marshal.FreeHGlobal(pathPointer);
1042 #region Event Handlers
1044 public void Handle(SelectiveSynchChanges message)
1048 PithosMonitor monitor;
1049 if (Monitors.TryGetValue(message.Account.AccountKey, out monitor))
1051 Selectives.SetIsSelectiveEnabled(message.Account.AccountKey, message.Enabled);
1052 monitor.SetSelectivePaths(message.Uris, message.Added, message.Removed);
1055 var account = Accounts.FirstOrDefault(acc => acc.AccountKey == message.Account.AccountKey);
1056 if (account != null)
1058 var added=monitor.UrisToFilePaths(message.Added);
1059 _pollAgent.SynchNow(added);
1066 private bool _pollStarted;
1067 private Sparkle _sparkle;
1068 private bool _manualUpgradeCheck;
1070 //SMELL: Doing so much work for notifications in the shell is wrong
1071 //The notifications should be moved to their own view/viewmodel pair
1072 //and different templates should be used for different message types
1073 //This will also allow the addition of extra functionality, eg. actions
1075 public void Handle(Notification notification)
1079 if (!Settings.ShowDesktopNotifications)
1082 if (notification is PollNotification)
1084 _pollStarted = true;
1087 if (notification is CloudNotification)
1091 _pollStarted= false;
1092 notification.Title = "Pithos+";
1093 notification.Message = "Start Synchronisation";
1096 var deleteNotification = notification as CloudDeleteNotification;
1097 if (deleteNotification != null)
1099 StatusMessage = String.Format("Deleted {0}", deleteNotification.Data.Name);
1103 var progress = notification as ProgressNotification;
1106 if (progress != null)
1108 StatusMessage = String.Format("{0} {1:p2} of {2} - {3}",
1110 (progress.Block + progress.BlockPercentage/100.0)/(double)progress.TotalBlocks,
1111 progress.FileSize.ToByteSize(),
1116 var info = notification as StatusNotification;
1119 StatusMessage = info.Title;
1122 if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
1125 if (notification.Level <= TraceLevel.Warning)
1126 ShowBalloonFor(notification);
1129 private void ShowBalloonFor(Notification notification)
1131 Contract.Requires(notification!=null);
1133 if (!Settings.ShowDesktopNotifications)
1137 switch (notification.Level)
1139 case TraceLevel.Verbose:
1141 case TraceLevel.Info:
1142 icon = BalloonIcon.Info;
1144 case TraceLevel.Error:
1145 icon = BalloonIcon.Error;
1147 case TraceLevel.Warning:
1148 icon = BalloonIcon.Warning;
1154 var tv = (ShellView) GetView();
1155 System.Action clickAction = null;
1156 if (notification is ExpirationNotification)
1158 clickAction = () => ShowPreferences("AccountTab");
1160 var balloon = new PithosBalloon
1162 Title = notification.Title,
1163 Message = notification.Message,
1165 ClickAction = clickAction
1167 tv.TaskbarView.ShowCustomBalloon(balloon, PopupAnimation.Fade, 4000);
1172 public void Handle(ShowFilePropertiesEvent message)
1174 if (message == null)
1175 throw new ArgumentNullException("message");
1176 if (String.IsNullOrWhiteSpace(message.FileName) )
1177 throw new ArgumentException("message");
1178 Contract.EndContractBlock();
1180 var fileName = message.FileName;
1181 //TODO: Display file properties for non-container folders
1182 if (File.Exists(fileName))
1183 //Retrieve the full name with exact casing. Pithos names are case sensitive
1184 ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
1185 else if (Directory.Exists(fileName))
1186 //Retrieve the full name with exact casing. Pithos names are case sensitive
1188 var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
1189 if (IsContainer(path))
1190 ShowContainerProperties(path);
1192 ShowFileProperties(path);
1196 private bool IsContainer(string path)
1198 var matchingFolders = from account in _accounts
1199 from rootFolder in Directory.GetDirectories(account.AccountPath)
1200 where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
1202 return matchingFolders.Any();
1205 public FileStatus GetFileStatus(string localFileName)
1207 if (String.IsNullOrWhiteSpace(localFileName))
1208 throw new ArgumentNullException("localFileName");
1209 Contract.EndContractBlock();
1211 var statusKeeper = IoC.Get<IStatusKeeper>();
1212 var status=statusKeeper.GetFileStatus(localFileName);
1216 public void RemoveAccountFromDatabase(AccountSettings account)
1218 var statusKeeper = IoC.Get<IStatusKeeper>();
1219 statusKeeper.ClearFolderStatus(account.RootPath);