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 / Disable the status 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)
507 var preferences = new PreferencesViewModel(_windowManager, _events, this, Settings,currentTab);
508 _windowManager.ShowDialog(preferences);
512 public void AboutPithos()
514 var about = IoC.Get<AboutViewModel>();
515 about.LatestVersion=_sparkle.LatestVersion;
516 _windowManager.ShowWindow(about);
519 public void SendFeedback()
521 var feedBack = IoC.Get<FeedbackViewModel>();
522 _windowManager.ShowWindow(feedBack);
525 //public PithosCommand OpenPithosFolderCommand { get; private set; }
527 public void OpenPithosFolder()
529 var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
532 Process.Start(account.RootPath);
535 public void OpenPithosFolder(AccountInfo account)
537 Process.Start(account.AccountPath);
542 public void GoToSite()
544 var site = Properties.Settings.Default.ProductionServer;
549 public void GoToSite(AccountInfo account)
551 var uri = account.SiteUri.Replace("http://","https://");
555 private bool _statusVisible;
557 public string MiniStatusCaption
561 return _statusVisible ? "Hide Status Window" : "Show Status Window";
565 public bool HasConflicts
569 public void ShowConflicts()
571 _windowManager.ShowWindow(IoC.Get<ConflictsViewModel>());
575 /// Open an explorer window to the target path's directory
576 /// and select the file
578 /// <param name="entry"></param>
579 public void GoToFile(FileEntry entry)
581 var fullPath = entry.FullPath;
582 if (!File.Exists(fullPath) && !Directory.Exists(fullPath))
584 Process.Start("explorer.exe","/select, " + fullPath);
587 public void OpenLogPath()
589 var pithosDataPath = PithosSettings.PithosDataPath;
591 Process.Start(pithosDataPath);
594 public void ShowFileProperties()
596 var account = Settings.Accounts.First(acc => acc.IsActive);
597 var dir = new DirectoryInfo(account.RootPath + @"\pithos");
598 var files=dir.GetFiles();
600 var idx=r.Next(0, files.Length);
601 ShowFileProperties(files[idx].FullName);
604 public void ShowFileProperties(string filePath)
606 if (String.IsNullOrWhiteSpace(filePath))
607 throw new ArgumentNullException("filePath");
608 if (!File.Exists(filePath) && !Directory.Exists(filePath))
609 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
610 Contract.EndContractBlock();
612 var pair=(from monitor in Monitors
613 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
614 select monitor).FirstOrDefault();
615 var accountMonitor = pair.Value;
617 if (accountMonitor == null)
620 var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
624 var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
625 _windowManager.ShowWindow(fileProperties);
628 public void ShowContainerProperties()
630 var account = Settings.Accounts.First(acc => acc.IsActive);
631 var dir = new DirectoryInfo(account.RootPath);
632 var fullName = (from folder in dir.EnumerateDirectories()
633 where (folder.Attributes & FileAttributes.Hidden) == 0
634 select folder.FullName).First();
635 ShowContainerProperties(fullName);
638 public void ShowContainerProperties(string filePath)
640 if (String.IsNullOrWhiteSpace(filePath))
641 throw new ArgumentNullException("filePath");
642 if (!Directory.Exists(filePath))
643 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
644 Contract.EndContractBlock();
646 var pair=(from monitor in Monitors
647 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
648 select monitor).FirstOrDefault();
649 var accountMonitor = pair.Value;
650 var info = accountMonitor.GetContainerInfo(filePath);
654 var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
655 _windowManager.ShowWindow(containerProperties);
658 public void SynchNow()
660 _pollAgent.SynchNow();
663 public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
665 if (currentInfo==null)
666 throw new ArgumentNullException("currentInfo");
667 Contract.EndContractBlock();
668 var monitor = Monitors[currentInfo.AccountKey];
669 var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
673 public ContainerInfo RefreshContainerInfo(ContainerInfo container)
675 if (container == null)
676 throw new ArgumentNullException("container");
677 Contract.EndContractBlock();
679 var monitor = Monitors[container.AccountKey];
680 var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
684 private bool _isPaused;
687 get { return _isPaused; }
691 PauseSyncCaption = IsPaused ? "Resume syncing" : "Pause syncing";
692 var iconKey = IsPaused ? "TraySyncPaused" : "TrayInSynch";
693 StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
695 NotifyOfPropertyChange(() => IsPaused);
699 public void ToggleSynching()
702 foreach (var monitor in Monitors.Values)
704 monitor.Pause = IsPaused ;
706 _pollAgent.Pause = IsPaused;
707 _networkAgent.Pause = IsPaused;
712 public void ExitPithos()
717 foreach (var monitor in Monitors.Select(pair => pair.Value))
722 var view = GetView() as Window;
726 catch (Exception exc)
728 Log.Info("Exception while exiting", exc);
732 Application.Current.Shutdown();
739 private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
741 new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
742 new StatusInfo(PithosStatus.PollSyncing, "Polling Files", "TraySynching"),
743 new StatusInfo(PithosStatus.LocalSyncing, "Syncing Files", "TraySynching"),
744 new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
745 }.ToDictionary(s => s.Status);
747 readonly IWindowManager _windowManager;
749 //private int _syncCount=0;
752 private PithosStatus _pithosStatus = PithosStatus.Disconnected;
754 public void SetPithosStatus(PithosStatus status)
756 if (_pithosStatus == PithosStatus.LocalSyncing && status == PithosStatus.PollComplete)
758 if (_pithosStatus == PithosStatus.PollSyncing && status == PithosStatus.LocalComplete)
760 if (status == PithosStatus.LocalComplete || status == PithosStatus.PollComplete)
761 _pithosStatus = PithosStatus.InSynch;
763 _pithosStatus = status;
767 public void SetPithosStatus(PithosStatus status,string message)
769 StatusMessage = message;
770 SetPithosStatus(status);
773 /* public Notifier GetNotifier(Notification startNotification, Notification endNotification)
775 return new Notifier(this, startNotification, endNotification);
778 public Notifier GetNotifier(string startMessage, string endMessage, params object[] args)
780 return new Notifier(this,
781 new StatusNotification(String.Format(startMessage,args)),
782 new StatusNotification(String.Format(endMessage,args)));
787 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat
789 public void UpdateStatus()
792 if (_iconNames.ContainsKey(_pithosStatus))
794 var info = _iconNames[_pithosStatus];
795 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
798 if (_pithosStatus == PithosStatus.InSynch)
799 StatusMessage = "All files up to date";
804 private Task StartMonitor(PithosMonitor monitor,int retries=0)
806 return Task.Factory.StartNew(() =>
808 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
812 Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
816 catch (WebException exc)
818 if (AbandonRetry(monitor, retries))
821 HttpStatusCode statusCode =HttpStatusCode.OK;
822 var response = exc.Response as HttpWebResponse;
824 statusCode = response.StatusCode;
828 case HttpStatusCode.Unauthorized:
829 var message = String.Format("API Key Expired for {0}. Starting Renewal",
831 Log.Error(message, exc);
832 var account = Settings.Accounts.Find(acc => acc.AccountKey == new Uri(new Uri(monitor.AuthenticationUrl), monitor.UserName));
833 account.IsExpired = true;
834 Notify(new ExpirationNotification(account));
835 //TryAuthorize(monitor.UserName, retries).Wait();
837 case HttpStatusCode.ProxyAuthenticationRequired:
838 TryAuthenticateProxy(monitor,retries);
841 TryLater(monitor, exc, retries);
845 catch (Exception exc)
847 if (AbandonRetry(monitor, retries))
850 TryLater(monitor,exc,retries);
856 private void TryAuthenticateProxy(PithosMonitor monitor,int retries)
858 Execute.OnUIThread(() =>
860 var proxyAccount = IoC.Get<ProxyAccountViewModel>();
861 proxyAccount.Settings = Settings;
862 if (true != _windowManager.ShowDialog(proxyAccount))
864 StartMonitor(monitor, retries);
865 NotifyOfPropertyChange(() => Accounts);
869 private bool AbandonRetry(PithosMonitor monitor, int retries)
873 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
875 _events.Publish(new Notification
876 {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
883 private void TryLater(PithosMonitor monitor, Exception exc,int retries)
885 var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
886 Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
887 _events.Publish(new Notification
888 {Title = "Error", Message = message, Level = TraceLevel.Error});
889 Log.Error(message, exc);
893 public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
895 StatusMessage = status;
897 _events.Publish(new Notification { Title = "Pithos+", Message = status, Level = level });
900 public void NotifyChangedFile(string filePath)
902 if (RecentFiles.Any(e => e.FullPath == filePath))
905 IProducerConsumerCollection<FileEntry> files=RecentFiles;
907 while (files.Count > 5)
908 files.TryTake(out popped);
909 var entry = new FileEntry { FullPath = filePath };
913 public void NotifyAccount(AccountInfo account)
917 //TODO: What happens to an existing account whose Token has changed?
918 account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
919 account.SiteUri, Uri.EscapeDataString(account.Token),
920 Uri.EscapeDataString(account.UserName));
922 if (!Accounts.Any(item => item.UserName == account.UserName && item.SiteUri == account.SiteUri))
923 Accounts.TryAdd(account);
927 public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
929 if (conflictFiles == null)
931 //Convert to list to avoid multiple iterations
932 var files = conflictFiles.ToList();
937 //TODO: Create a more specific message. For now, just show a warning
938 NotifyForFiles(files,message,TraceLevel.Warning);
942 public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info)
949 StatusMessage = message;
951 _events.Publish(new Notification { Title = "Pithos+", Message = message, Level = level});
954 public void Notify(Notification notification)
956 _events.Publish(notification);
960 public void RemoveMonitor(string serverUrl,string accountName)
962 if (String.IsNullOrWhiteSpace(accountName))
965 var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName && account.StorageUri.ToString().StartsWith(serverUrl));
966 if (accountInfo != null)
968 _accounts.TryRemove(accountInfo);
969 _pollAgent.RemoveAccount(accountInfo);
972 var accountKey = new Uri(new Uri(serverUrl),accountName);
973 PithosMonitor monitor;
974 if (Monitors.TryRemove(accountKey, out monitor))
977 //TODO: Also remove any pending actions for this account
978 //from the network queue
982 public void RefreshOverlays()
984 foreach (var pair in Monitors)
986 var monitor = pair.Value;
988 var path = monitor.RootPath;
990 if (String.IsNullOrWhiteSpace(path))
993 if (!Directory.Exists(path) && !File.Exists(path))
996 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
1000 NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
1001 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
1002 pathPointer, IntPtr.Zero);
1006 Marshal.FreeHGlobal(pathPointer);
1011 #region Event Handlers
1013 public void Handle(SelectiveSynchChanges message)
1017 PithosMonitor monitor;
1018 if (Monitors.TryGetValue(message.Account.AccountKey, out monitor))
1020 Selectives.SetIsSelectiveEnabled(message.Account.AccountKey, message.Enabled);
1021 monitor.SetSelectivePaths(message.Uris, message.Added, message.Removed);
1024 var account = Accounts.FirstOrDefault(acc => acc.AccountKey == message.Account.AccountKey);
1025 if (account != null)
1027 _pollAgent.SetSelectivePaths(account, message.Added, message.Removed);
1028 var added=monitor.UrisToFilePaths(message.Added);
1029 _pollAgent.SynchNow(added);
1036 private bool _pollStarted;
1037 private Sparkle _sparkle;
1038 private bool _manualUpgradeCheck;
1040 //SMELL: Doing so much work for notifications in the shell is wrong
1041 //The notifications should be moved to their own view/viewmodel pair
1042 //and different templates should be used for different message types
1043 //This will also allow the addition of extra functionality, eg. actions
1045 public void Handle(Notification notification)
1049 if (!Settings.ShowDesktopNotifications)
1052 if (notification is PollNotification)
1054 _pollStarted = true;
1057 if (notification is CloudNotification)
1061 _pollStarted= false;
1062 notification.Title = "Pithos+";
1063 notification.Message = "Start Synchronisation";
1066 var deleteNotification = notification as CloudDeleteNotification;
1067 if (deleteNotification != null)
1069 StatusMessage = String.Format("Deleted {0}", deleteNotification.Data.Name);
1073 var progress = notification as ProgressNotification;
1076 if (progress != null)
1078 StatusMessage = String.Format("{0} {1:p2} of {2} - {3}",
1080 progress.Block/(double)progress.TotalBlocks,
1081 progress.FileSize.ToByteSize(),
1086 var info = notification as StatusNotification;
1089 StatusMessage = info.Title;
1092 if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
1095 if (notification.Level <= TraceLevel.Warning)
1096 ShowBalloonFor(notification);
1099 private void ShowBalloonFor(Notification notification)
1101 Contract.Requires(notification!=null);
1103 if (!Settings.ShowDesktopNotifications)
1107 switch (notification.Level)
1109 case TraceLevel.Verbose:
1111 case TraceLevel.Info:
1112 icon = BalloonIcon.Info;
1114 case TraceLevel.Error:
1115 icon = BalloonIcon.Error;
1117 case TraceLevel.Warning:
1118 icon = BalloonIcon.Warning;
1124 var tv = (ShellView) GetView();
1125 System.Action clickAction = null;
1126 if (notification is ExpirationNotification)
1128 clickAction = () => ShowPreferences("AccountTab");
1130 var balloon = new PithosBalloon
1132 Title = notification.Title,
1133 Message = notification.Message,
1135 ClickAction = clickAction
1137 tv.TaskbarView.ShowCustomBalloon(balloon, PopupAnimation.Fade, 4000);
1142 public void Handle(ShowFilePropertiesEvent message)
1144 if (message == null)
1145 throw new ArgumentNullException("message");
1146 if (String.IsNullOrWhiteSpace(message.FileName) )
1147 throw new ArgumentException("message");
1148 Contract.EndContractBlock();
1150 var fileName = message.FileName;
1151 //TODO: Display file properties for non-container folders
1152 if (File.Exists(fileName))
1153 //Retrieve the full name with exact casing. Pithos names are case sensitive
1154 ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
1155 else if (Directory.Exists(fileName))
1156 //Retrieve the full name with exact casing. Pithos names are case sensitive
1158 var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
1159 if (IsContainer(path))
1160 ShowContainerProperties(path);
1162 ShowFileProperties(path);
1166 private bool IsContainer(string path)
1168 var matchingFolders = from account in _accounts
1169 from rootFolder in Directory.GetDirectories(account.AccountPath)
1170 where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
1172 return matchingFolders.Any();
1175 public FileStatus GetFileStatus(string localFileName)
1177 if (String.IsNullOrWhiteSpace(localFileName))
1178 throw new ArgumentNullException("localFileName");
1179 Contract.EndContractBlock();
1181 var statusKeeper = IoC.Get<IStatusKeeper>();
1182 var status=statusKeeper.GetFileStatus(localFileName);
1186 public void RemoveAccountFromDatabase(AccountSettings account)
1188 var statusKeeper = IoC.Get<IStatusKeeper>();
1189 statusKeeper.ClearFolderStatus(account.RootPath);