Fixed Mini Status Window
[pithos-ms-client] / trunk / Pithos.Client.WPF / Shell / ShellViewModel.cs
1 #region
2 /* -----------------------------------------------------------------------
3  * <copyright file="ShellViewModel.cs" company="GRNet">
4  * 
5  * Copyright 2011-2012 GRNET S.A. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or
8  * without modification, are permitted provided that the following
9  * conditions are met:
10  *
11  *   1. Redistributions of source code must retain the above
12  *      copyright notice, this list of conditions and the following
13  *      disclaimer.
14  *
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.
19  *
20  *
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.
33  *
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.
38  * </copyright>
39  * -----------------------------------------------------------------------
40  */
41 #endregion
42 using System.Collections.Concurrent;
43 using System.Diagnostics;
44 using System.Diagnostics.Contracts;
45 using System.IO;
46 using System.Net;
47 using System.Reflection;
48 using System.Runtime.InteropServices;
49 using System.ServiceModel;
50 using System.Threading.Tasks;
51 using System.Windows;
52 using System.Windows.Controls.Primitives;
53 using AppLimit.NetSparkle;
54 using Caliburn.Micro;
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;
62 using Pithos.Core;
63 using Pithos.Core.Agents;
64 using Pithos.Interfaces;
65 using System;
66 using System.Collections.Generic;
67 using System.Linq;
68 using Pithos.Network;
69 using StatusService = Pithos.Client.WPF.Services.StatusService;
70
71 namespace Pithos.Client.WPF {
72         using System.ComponentModel.Composition;
73
74         
75         ///<summary>
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
78         ///</summary>
79         ///<remarks>
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
85         ///</remarks>           
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>
90         {
91
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;
96
97                 public PithosSettings Settings { get; private set; }
98
99
100                 private readonly ConcurrentDictionary<Uri, PithosMonitor> _monitors = new ConcurrentDictionary<Uri, PithosMonitor>();
101                 ///<summary>
102                 /// Dictionary of account monitors, keyed by account
103                 ///</summary>
104                 ///<remarks>
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            
107                 ///</remarks>
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
111                 {
112                         get { return _monitors; }
113                 }
114
115
116                 ///<summary>
117                 /// The status service is used by Shell extensions to retrieve file status information
118                 ///</summary>
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;
121
122                 //Logging in the Pithos client is provided by log4net
123         private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
124
125             private readonly PollAgent _pollAgent;
126
127
128             private MiniStatusViewModel _miniStatus;
129
130             [Import]
131         public MiniStatusViewModel MiniStatus
132             {
133                 get { return _miniStatus; }
134                 set
135                 {
136                     _miniStatus = value;
137                     _miniStatus.Shell = this;
138                     _miniStatus.Deactivated += (sender, arg) =>
139                                                    {
140                                                        _statusVisible = false;
141                                                    NotifyOfPropertyChange(()=>MiniStatusCaption);
142                                                    };
143                 }
144             }
145
146             ///<summary>
147                 /// The Shell depends on MEF to provide implementations for windowManager, events, the status checker service and the settings
148                 ///</summary>
149                 ///<remarks>
150                 /// The PithosSettings class encapsulates the app's settings to abstract their storage mechanism (App settings, a database or registry)
151                 ///</remarks>
152                 [ImportingConstructor]          
153                 public ShellViewModel(IWindowManager windowManager, IEventAggregator events, IStatusChecker statusChecker, PithosSettings settings,PollAgent pollAgent)
154                 {
155                         try
156                         {
157
158                                 _windowManager = windowManager;
159                                 //CHECK: Caliburn doesn't need explicit command construction
160                                 //OpenPithosFolderCommand = new PithosCommand(OpenPithosFolder);
161                                 _statusChecker = statusChecker;
162                                 //The event subst
163                                 _events = events;
164                                 _events.Subscribe(this);
165
166                             _pollAgent = pollAgent;
167                                 Settings = settings;
168
169                                 Proxy.SetFromSettings(settings);
170
171                 StatusMessage = Settings.Accounts.Count==0 
172                     ? "No Accounts added\r\nPlease add an account" 
173                     : "Starting";
174
175                                 _accounts.CollectionChanged += (sender, e) =>
176                                                                                                    {
177                                                                                                            NotifyOfPropertyChange(() => OpenFolderCaption);
178                                                                                                            NotifyOfPropertyChange(() => HasAccounts);
179                                                                                                    };
180
181                 SetVersionMessage();
182                         }
183                         catch (Exception exc)
184                         {
185                                 Log.Error("Error while starting the ShellViewModel",exc);
186                                 throw;
187                         }
188
189                 }
190
191             private void SetVersionMessage()
192             {
193                 Assembly assembly = Assembly.GetExecutingAssembly();
194                 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
195                 VersionMessage = String.Format("Pithos+ {0}", fileVersion.FileVersion);
196             }
197
198         public void CurrentSyncStatus()
199         {
200             if (Accounts.Count == 0)
201             {
202                 ShowPreferences("AccountTab");
203             }
204             else
205             {
206                 if (!_statusVisible)
207                     _windowManager.ShowWindow(MiniStatus);
208                 else
209                 {
210                     if (MiniStatus.IsActive)
211                         MiniStatus.TryClose();
212                 }
213                 _statusVisible = !_statusVisible;
214
215                 NotifyOfPropertyChange(() => MiniStatusCaption);
216             }
217         }
218
219             protected override void OnActivate()
220                 {
221                         base.OnActivate();
222
223             InitializeSparkle();
224
225                 //Must delay opening the upgrade window
226             //to avoid Windows Messages sent by the TaskbarIcon
227             TaskEx.Delay(5000).ContinueWith(_=>
228                 Execute.OnUIThread(()=> _sparkle.StartLoop(true,Settings.UpdateForceCheck,Settings.UpdateCheckInterval)));
229
230
231                         StartMonitoring();                    
232                 }
233
234
235             private void OnCheckFinished(object sender, bool updaterequired)
236             {
237             
238             Log.InfoFormat("Upgrade check finished. Need Upgrade: {0}", updaterequired);
239             if (_manualUpgradeCheck)
240             {
241                 _manualUpgradeCheck = false;
242                 if (!updaterequired)
243                     //Sparkle raises events on a background thread
244                     Execute.OnUIThread(()=>
245                         ShowBalloonFor(new Notification{Title="Pithos+ is up to date",Message="You have the latest Pithos+ version. No update is required"}));
246             }
247             }
248
249             private void OnUpgradeDetected(object sender, UpdateDetectedEventArgs e)
250             {            
251                 Log.InfoFormat("Update detected {0}",e.LatestVersion);
252             }
253
254         public void CheckForUpgrade()
255         {
256             ShowBalloonFor(new Notification{Title="Checking for upgrades",Message="Contacting the server to retrieve the latest Pithos+ version."});
257             _sparkle.StopLoop();
258             _sparkle.updateDetected -= OnUpgradeDetected;
259             _sparkle.checkLoopFinished -= OnCheckFinished;
260             _sparkle.Dispose();
261
262             _manualUpgradeCheck = true;
263             InitializeSparkle();
264             _sparkle.StartLoop(true,true,Settings.UpdateCheckInterval);
265         }
266
267         private void InitializeSparkle()
268         {
269             _sparkle = new Sparkle(Settings.UpdateUrl);
270             _sparkle.updateDetected += OnUpgradeDetected;
271             _sparkle.checkLoopFinished += OnCheckFinished;
272             _sparkle.ShowDiagnosticWindow = Settings.UpdateDiagnostics;
273         }
274
275             private async void StartMonitoring()
276                 {
277                         try
278                         {
279                 if (Settings.IgnoreCertificateErrors)
280                 {
281                     ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
282                 }
283                     
284                                 var accounts = Settings.Accounts.Select(MonitorAccount);
285                                 await TaskEx.WhenAll(accounts);
286                                 _statusService = StatusService.Start();
287
288                         }
289                         catch (AggregateException exc)
290                         {
291                                 exc.Handle(e =>
292                                 {
293                                         Log.Error("Error while starting monitoring", e);
294                                         return true;
295                                 });
296                                 throw;
297                         }
298                 }
299
300                 protected override void OnDeactivate(bool close)
301                 {
302                         base.OnDeactivate(close);
303                         if (close)
304                         {
305                                 StatusService.Stop(_statusService);
306                                 _statusService = null;
307                         }
308                 }
309
310                 public Task MonitorAccount(AccountSettings account)
311                 {
312                         return Task.Factory.StartNew(() =>
313                         {                                                
314                                 PithosMonitor monitor;
315                                 var accountName = account.AccountName;
316
317                                 if (Monitors.TryGetValue(account.AccountKey, out monitor))
318                                 {
319                                         //If the account is active
320                     if (account.IsActive)
321                     {
322                         //The Api Key may have changed throuth the Preferences dialog
323                         monitor.ApiKey = account.ApiKey;
324                                                 Debug.Assert(monitor.StatusNotification == this,"An existing monitor should already have a StatusNotification service object");
325                         monitor.RootPath = account.RootPath;
326                         //Start the monitor. It's OK to start an already started monitor,
327                         //it will just ignore the call                        
328                         StartMonitor(monitor).Wait();
329                     }
330                     else
331                     {
332                         //If the account is inactive
333                         //Stop and remove the monitor
334                         RemoveMonitor(account.ServerUrl,accountName);
335                     }
336                                         return;
337                                 }
338
339                                 
340                                 //Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
341                                 monitor = new PithosMonitor
342                                                           {
343                                                                   UserName = accountName,
344                                                                   ApiKey = account.ApiKey,                                  
345                                                                   StatusNotification = this,
346                                                                   RootPath = account.RootPath
347                                                           };
348                                 //PithosMonitor uses MEF so we need to resolve it
349                                 IoC.BuildUp(monitor);
350
351                                 monitor.AuthenticationUrl = account.ServerUrl;
352
353                                 Monitors[account.AccountKey] = monitor;
354
355                                 if (account.IsActive)
356                                 {
357                                         //Don't start a monitor if it doesn't have an account and ApiKey
358                                         if (String.IsNullOrWhiteSpace(monitor.UserName) ||
359                                                 String.IsNullOrWhiteSpace(monitor.ApiKey))
360                                                 return;
361                                         StartMonitor(monitor);
362                                 }
363                         });
364                 }
365
366
367                 protected override void OnViewLoaded(object view)
368                 {
369                         UpdateStatus();
370                         var window = (Window)view;            
371                         TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
372                         base.OnViewLoaded(view);
373                 }
374
375
376                 #region Status Properties
377
378                 private string _statusMessage;
379                 public string StatusMessage
380                 {
381                         get { return _statusMessage; }
382                         set
383                         {
384                                 _statusMessage = value;
385                                 NotifyOfPropertyChange(() => StatusMessage);
386                 NotifyOfPropertyChange(() => TooltipMessage);
387                         }
388                 }
389
390         public string VersionMessage { get; set; }
391
392             public string TooltipMessage
393             {
394                 get
395                 {
396                     return String.Format("{0}\r\n{1}",VersionMessage,StatusMessage);
397                 }
398             }
399
400         public string ToggleStatusWindowMessage
401         {
402             get
403             {
404                 return String.Format("{0}" + Environment.NewLine + "{1} Toggle Mini Status");
405             }
406         }
407
408             private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
409                 public ObservableConcurrentCollection<AccountInfo> Accounts
410                 {
411                         get { return _accounts; }
412                 }
413
414                 public bool HasAccounts
415                 {
416                         get { return _accounts.Count > 0; }
417                 }
418
419
420                 public string OpenFolderCaption
421                 {
422                         get
423                         {
424                                 return (_accounts.Count == 0)
425                                                 ? "No Accounts Defined"
426                                                 : "Open Pithos Folder";
427                         }
428                 }
429
430                 private string _pauseSyncCaption="Pause Synching";
431                 public string PauseSyncCaption
432                 {
433                         get { return _pauseSyncCaption; }
434                         set
435                         {
436                                 _pauseSyncCaption = value;
437                                 NotifyOfPropertyChange(() => PauseSyncCaption);
438                         }
439                 }
440
441                 private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
442                 public ObservableConcurrentCollection<FileEntry> RecentFiles
443                 {
444                         get { return _recentFiles; }
445                 }
446
447
448                 private string _statusIcon="../Images/Pithos.ico";
449                 public string StatusIcon
450                 {
451                         get { return _statusIcon; }
452                         set
453                         {
454                                 //TODO: Ensure all status icons use the Pithos logo
455                                 _statusIcon = value;
456                                 NotifyOfPropertyChange(() => StatusIcon);
457                         }
458                 }
459
460                 #endregion
461
462                 #region Commands
463
464         public void ShowPreferences()
465         {
466             ShowPreferences(null);
467         }
468
469                 public void ShowPreferences(string currentTab)
470                 {
471                         //Settings.Reload();
472                     var preferences = new PreferencesViewModel(_windowManager, _events, this, Settings,currentTab);
473                     _windowManager.ShowDialog(preferences);
474                         
475                 }
476
477                 public void AboutPithos()
478                 {
479                         var about = IoC.Get<AboutViewModel>();
480                     about.LatestVersion=_sparkle.LatestVersion;
481                         _windowManager.ShowWindow(about);
482                 }
483
484                 public void SendFeedback()
485                 {
486                         var feedBack =  IoC.Get<FeedbackViewModel>();
487                         _windowManager.ShowWindow(feedBack);
488                 }
489
490                 //public PithosCommand OpenPithosFolderCommand { get; private set; }
491
492                 public void OpenPithosFolder()
493                 {
494                         var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
495                         if (account == null)
496                                 return;
497                         Process.Start(account.RootPath);
498                 }
499
500                 public void OpenPithosFolder(AccountInfo account)
501                 {
502                         Process.Start(account.AccountPath);
503                 }
504
505                 
506
507                 public void GoToSite()
508                 {            
509                         var site = Properties.Settings.Default.ProductionServer;
510                         Process.Start(site);            
511                 }
512
513
514                 public void GoToSite(AccountInfo account)
515                 {
516                     var uri = account.SiteUri.Replace("http://","https://");            
517                     Process.Start(uri);
518                 }
519
520             private bool _statusVisible;
521
522             public string MiniStatusCaption
523             {
524                 get
525                 {
526                     return  _statusVisible ? "Hide Status Window" : "Show Status Window";
527                 }
528             }
529
530             public bool HasConflicts
531             {
532             get { return true; }
533             }
534         public void ShowConflicts()
535         {
536             _windowManager.ShowWindow(IoC.Get<ConflictsViewModel>());            
537         }
538
539             /// <summary>
540         /// Open an explorer window to the target path's directory
541         /// and select the file
542         /// </summary>
543         /// <param name="entry"></param>
544         public void GoToFile(FileEntry entry)
545         {
546             var fullPath = entry.FullPath;
547             if (!File.Exists(fullPath) && !Directory.Exists(fullPath))
548                 return;
549             Process.Start("explorer.exe","/select, " + fullPath);
550         }
551
552         public void OpenLogPath()
553         {
554             var pithosDataPath = PithosSettings.PithosDataPath;
555
556             Process.Start(pithosDataPath);
557         }
558         
559         public void ShowFileProperties()
560                 {
561                         var account = Settings.Accounts.First(acc => acc.IsActive);            
562                         var dir = new DirectoryInfo(account.RootPath + @"\pithos");
563                         var files=dir.GetFiles();
564                         var r=new Random();
565                         var idx=r.Next(0, files.Length);
566                         ShowFileProperties(files[idx].FullName);            
567                 }
568
569                 public void ShowFileProperties(string filePath)
570                 {
571                         if (String.IsNullOrWhiteSpace(filePath))
572                                 throw new ArgumentNullException("filePath");
573                         if (!File.Exists(filePath) && !Directory.Exists(filePath))
574                                 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
575                         Contract.EndContractBlock();
576
577                         var pair=(from monitor in  Monitors
578                                                            where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
579                                                                    select monitor).FirstOrDefault();
580                         var accountMonitor = pair.Value;
581
582                         if (accountMonitor == null)
583                                 return;
584
585                         var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
586
587                         
588
589                         var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
590                         _windowManager.ShowWindow(fileProperties);
591                 } 
592                 
593                 public void ShowContainerProperties()
594                 {
595                         var account = Settings.Accounts.First(acc => acc.IsActive);            
596                         var dir = new DirectoryInfo(account.RootPath);
597                         var fullName = (from folder in dir.EnumerateDirectories()
598                                                         where (folder.Attributes & FileAttributes.Hidden) == 0
599                                                         select folder.FullName).First();
600                         ShowContainerProperties(fullName);            
601                 }
602
603                 public void ShowContainerProperties(string filePath)
604                 {
605                         if (String.IsNullOrWhiteSpace(filePath))
606                                 throw new ArgumentNullException("filePath");
607                         if (!Directory.Exists(filePath))
608                                 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
609                         Contract.EndContractBlock();
610
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;            
615                         var info = accountMonitor.GetContainerInfo(filePath);
616
617                         
618
619                         var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
620                         _windowManager.ShowWindow(containerProperties);
621                 }
622
623                 public void SynchNow()
624                 {
625                         _pollAgent.SynchNow();
626                 }
627
628                 public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
629                 {
630                         if (currentInfo==null)
631                                 throw new ArgumentNullException("currentInfo");
632                         Contract.EndContractBlock();                
633             var monitor = Monitors[currentInfo.AccountKey];
634                         var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
635                         return newInfo;
636                 }
637
638                 public ContainerInfo RefreshContainerInfo(ContainerInfo container)
639                 {
640                         if (container == null)
641                                 throw new ArgumentNullException("container");
642                         Contract.EndContractBlock();
643
644                         var monitor = Monitors[container.AccountKey];
645                         var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
646                         return newInfo;
647                 }
648
649
650                 public void ToggleSynching()
651                 {
652                         bool isPaused=false;
653                         foreach (var pair in Monitors)
654                         {
655                                 var monitor = pair.Value;
656                                 monitor.Pause = !monitor.Pause;
657                                 isPaused = monitor.Pause;
658                         }
659                         
660
661                         PauseSyncCaption = isPaused ? "Resume syncing" : "Pause syncing";
662                         var iconKey = isPaused? "TraySyncPaused" : "TrayInSynch";
663                         StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
664                 }
665
666         public void ExitPithos()
667         {
668             try
669             {
670
671                 foreach (var monitor in Monitors.Select(pair => pair.Value))
672                 {
673                     monitor.Stop();
674                 }
675
676                 var view = GetView() as Window;
677                 if (view != null)
678                     view.Close();
679             }
680             catch (Exception exc)
681             {
682                 Log.Info("Exception while exiting", exc);                
683             }
684             finally
685             {
686                 Application.Current.Shutdown();
687             }
688         }
689
690             #endregion
691
692
693                 private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
694                         {
695                                 new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
696                                 new StatusInfo(PithosStatus.PollSyncing, "Polling Files", "TraySynching"),
697                 new StatusInfo(PithosStatus.LocalSyncing, "Syncing Files", "TraySynching"),
698                                 new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
699                         }.ToDictionary(s => s.Status);
700
701                 readonly IWindowManager _windowManager;
702                 
703         //private int _syncCount=0;
704
705
706         private PithosStatus _pithosStatus = PithosStatus.Disconnected;
707
708         public void SetPithosStatus(PithosStatus status)
709         {
710             if (_pithosStatus == PithosStatus.LocalSyncing && status == PithosStatus.PollComplete)
711                 return;
712             if (_pithosStatus == PithosStatus.PollSyncing && status == PithosStatus.LocalComplete)
713                 return;
714             if (status == PithosStatus.LocalComplete || status == PithosStatus.PollComplete)
715                 _pithosStatus = PithosStatus.InSynch;
716             else
717                 _pithosStatus = status;
718             UpdateStatus();
719         }
720
721         public void SetPithosStatus(PithosStatus status,string message)
722         {
723             StatusMessage = message;
724             SetPithosStatus(status);
725         }
726
727           /*  public Notifier GetNotifier(Notification startNotification, Notification endNotification)
728             {
729                 return new Notifier(this, startNotification, endNotification);
730             }*/
731
732             public Notifier GetNotifier(string startMessage, string endMessage, params object[] args)
733             {
734                 return new Notifier(this, 
735                 new StatusNotification(String.Format(startMessage,args)), 
736                 new StatusNotification(String.Format(endMessage,args)));
737             }
738
739
740             ///<summary>
741                 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat                
742                 ///</summary>
743                 public void UpdateStatus()
744                 {
745
746                         if (_iconNames.ContainsKey(_pithosStatus))
747                         {
748                                 var info = _iconNames[_pithosStatus];
749                                 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
750                         }
751
752             if (_pithosStatus == PithosStatus.InSynch)
753                 StatusMessage = "All files up to date";
754                 }
755
756
757            
758                 private Task StartMonitor(PithosMonitor monitor,int retries=0)
759                 {
760                         return Task.Factory.StartNew(() =>
761                         {
762                                 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
763                                 {
764                                         try
765                                         {
766                                                 Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
767
768                                                 monitor.Start();
769                                         }
770                                         catch (WebException exc)
771                                         {
772                                                 if (AbandonRetry(monitor, retries))
773                                                         return;
774
775                                                 HttpStatusCode statusCode =HttpStatusCode.OK;
776                                                 var response = exc.Response as HttpWebResponse;
777                                                 if(response!=null)
778                                                         statusCode = response.StatusCode;
779
780                                                 switch (statusCode)
781                                                 {
782                                                         case HttpStatusCode.Unauthorized:
783                                                                 var message = String.Format("API Key Expired for {0}. Starting Renewal",
784                                                                                                                         monitor.UserName);
785                                                                 Log.Error(message, exc);
786                                 var account = Settings.Accounts.Find(acc => acc.AccountKey == new Uri(new Uri(monitor.AuthenticationUrl), monitor.UserName));                                
787                                                         account.IsExpired = true;
788                                 Notify(new ExpirationNotification(account));
789                                                                 //TryAuthorize(monitor.UserName, retries).Wait();
790                                                                 break;
791                                                         case HttpStatusCode.ProxyAuthenticationRequired:
792                                                                 TryAuthenticateProxy(monitor,retries);
793                                                                 break;
794                                                         default:
795                                                                 TryLater(monitor, exc, retries);
796                                                                 break;
797                                                 }
798                                         }
799                                         catch (Exception exc)
800                                         {
801                                                 if (AbandonRetry(monitor, retries)) 
802                                                         return;
803
804                                                 TryLater(monitor,exc,retries);
805                                         }
806                                 }
807                         });
808                 }
809
810                 private void TryAuthenticateProxy(PithosMonitor monitor,int retries)
811                 {
812                         Execute.OnUIThread(() =>
813                                                                    {                                       
814                                                                            var proxyAccount = IoC.Get<ProxyAccountViewModel>();
815                                                                                 proxyAccount.Settings = Settings;
816                                                                            if (true != _windowManager.ShowDialog(proxyAccount)) 
817                                                                                    return;
818                                                                            StartMonitor(monitor, retries);
819                                                                            NotifyOfPropertyChange(() => Accounts);
820                                                                    });
821                 }
822
823                 private bool AbandonRetry(PithosMonitor monitor, int retries)
824                 {
825                         if (retries > 1)
826                         {
827                                 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
828                                                                                         monitor.UserName);
829                                 _events.Publish(new Notification
830                                                                         {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
831                                 return true;
832                         }
833                         return false;
834                 }
835
836
837             private void TryLater(PithosMonitor monitor, Exception exc,int retries)
838                 {
839                         var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
840                         Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
841                         _events.Publish(new Notification
842                                                                 {Title = "Error", Message = message, Level = TraceLevel.Error});
843                         Log.Error(message, exc);
844                 }
845
846
847                 public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
848                 {
849                         StatusMessage = status;
850                         
851                         _events.Publish(new Notification { Title = "Pithos+", Message = status, Level = level });
852                 }
853
854                 public void NotifyChangedFile(string filePath)
855                 {
856             if (RecentFiles.Any(e => e.FullPath == filePath))
857                 return;
858             
859                         IProducerConsumerCollection<FileEntry> files=RecentFiles;
860                         FileEntry popped;
861                         while (files.Count > 5)
862                                 files.TryTake(out popped);
863             var entry = new FileEntry { FullPath = filePath };
864                         files.TryAdd(entry);
865                 }
866
867                 public void NotifyAccount(AccountInfo account)
868                 {
869                         if (account== null)
870                                 return;
871                         //TODO: What happens to an existing account whose Token has changed?
872                         account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
873                                 account.SiteUri, Uri.EscapeDataString(account.Token),
874                                 Uri.EscapeDataString(account.UserName));
875
876                         if (!Accounts.Any(item => item.UserName == account.UserName && item.SiteUri == account.SiteUri))
877                                 Accounts.TryAdd(account);
878
879                 }
880
881                 public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
882                 {
883                         if (conflictFiles == null)
884                                 return;
885                     //Convert to list to avoid multiple iterations
886             var files = conflictFiles.ToList();
887                         if (files.Count==0)
888                                 return;
889
890                         UpdateStatus();
891                         //TODO: Create a more specific message. For now, just show a warning
892                         NotifyForFiles(files,message,TraceLevel.Warning);
893
894                 }
895
896                 public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info)
897                 {
898                         if (files == null)
899                                 return;
900                         if (!files.Any())
901                                 return;
902
903                         StatusMessage = message;
904
905                         _events.Publish(new Notification { Title = "Pithos+", Message = message, Level = level});
906                 }
907
908                 public void Notify(Notification notification)
909                 {
910                         _events.Publish(notification);
911                 }
912
913
914                 public void RemoveMonitor(string serverUrl,string accountName)
915                 {
916                         if (String.IsNullOrWhiteSpace(accountName))
917                                 return;
918
919                         var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName && account.StorageUri.ToString().StartsWith(serverUrl));
920             if (accountInfo != null)
921             {
922                 _accounts.TryRemove(accountInfo);
923                 _pollAgent.RemoveAccount(accountInfo);
924             }
925
926             var accountKey = new Uri(new Uri(serverUrl),accountName);
927                     PithosMonitor monitor;
928                         if (Monitors.TryRemove(accountKey, out monitor))
929                         {
930                                 monitor.Stop();
931                 //TODO: Also remove any pending actions for this account
932                 //from the network queue                
933                         }
934                 }
935
936                 public void RefreshOverlays()
937                 {
938                         foreach (var pair in Monitors)
939                         {
940                                 var monitor = pair.Value;
941
942                                 var path = monitor.RootPath;
943
944                                 if (String.IsNullOrWhiteSpace(path))
945                                         continue;
946
947                                 if (!Directory.Exists(path) && !File.Exists(path))
948                                         continue;
949
950                                 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
951
952                                 try
953                                 {
954                                         NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
955                                                                                                  HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
956                                                                                                  pathPointer, IntPtr.Zero);
957                                 }
958                                 finally
959                                 {
960                                         Marshal.FreeHGlobal(pathPointer);
961                                 }
962                         }
963                 }
964
965                 #region Event Handlers
966                 
967                 public void Handle(SelectiveSynchChanges message)
968         {
969             PithosMonitor monitor;
970             if (Monitors.TryGetValue(message.Account.AccountKey, out monitor))
971             {
972                 monitor.SetSelectivePaths(message.Uris, message.Added, message.Removed);
973
974             }
975
976             var account = Accounts.FirstOrDefault(acc => acc.AccountKey == message.Account.AccountKey);
977             if (account!=null)
978             {
979                 this._pollAgent.SetSelectivePaths(account, message.Added, message.Removed);
980             }
981
982
983         }
984
985
986                 private bool _pollStarted;
987             private Sparkle _sparkle;
988             private bool _manualUpgradeCheck;
989
990             //SMELL: Doing so much work for notifications in the shell is wrong
991                 //The notifications should be moved to their own view/viewmodel pair
992                 //and different templates should be used for different message types
993                 //This will also allow the addition of extra functionality, eg. actions
994                 //
995                 public void Handle(Notification notification)
996                 {
997                         UpdateStatus();
998
999                         if (!Settings.ShowDesktopNotifications)
1000                                 return;
1001
1002                         if (notification is PollNotification)
1003                         {
1004                                 _pollStarted = true;
1005                                 return;
1006                         }
1007                         if (notification is CloudNotification)
1008                         {
1009                                 if (!_pollStarted) 
1010                                         return;
1011                                 _pollStarted= false;
1012                                 notification.Title = "Pithos+";
1013                                 notification.Message = "Start Synchronisation";
1014                         }
1015
1016                     var deleteNotification = notification as CloudDeleteNotification;
1017             if (deleteNotification != null)
1018             {
1019                 StatusMessage = String.Format("Deleted {0}", deleteNotification.Data.Name);
1020                 return;
1021             }
1022
1023                     var progress = notification as ProgressNotification;
1024                     
1025                     
1026             if (progress != null)
1027                     {
1028                         StatusMessage = String.Format("{0} {1:p2} of {2} - {3}",                                                      
1029                                               progress.Action,
1030                                                       progress.Block/(double)progress.TotalBlocks,
1031                                                       progress.FileSize.ToByteSize(),
1032                                                       progress.FileName);
1033                         return;
1034                     }
1035
1036                     var info = notification as StatusNotification;
1037             if (info != null)
1038             {
1039                 StatusMessage = info.Title;
1040                 return;
1041             }
1042                         if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
1043                                 return;
1044
1045             if (notification.Level <= TraceLevel.Warning)
1046                             ShowBalloonFor(notification);
1047                 }
1048
1049             private void ShowBalloonFor(Notification notification)
1050             {
1051             Contract.Requires(notification!=null);
1052             
1053             if (!Settings.ShowDesktopNotifications) 
1054                 return;
1055             
1056             BalloonIcon icon;
1057                 switch (notification.Level)
1058                 {
1059                 case TraceLevel.Verbose:
1060                         return;
1061                     case TraceLevel.Info:                   
1062                         icon = BalloonIcon.Info;
1063                         break;
1064                 case TraceLevel.Error:
1065                     icon = BalloonIcon.Error;
1066                     break;
1067                 case TraceLevel.Warning:
1068                         icon = BalloonIcon.Warning;
1069                         break;
1070                     default:
1071                         return;
1072                 }
1073
1074                 var tv = (ShellView) GetView();
1075                 System.Action clickAction = null;
1076                 if (notification is ExpirationNotification)
1077                 {
1078                     clickAction = () => ShowPreferences("AccountTab");
1079                 }
1080                 var balloon = new PithosBalloon
1081                                   {
1082                                       Title = notification.Title,
1083                                       Message = notification.Message,
1084                                       Icon = icon,
1085                                       ClickAction = clickAction
1086                                   };
1087                 tv.TaskbarView.ShowCustomBalloon(balloon, PopupAnimation.Fade, 4000);
1088             }
1089
1090             #endregion
1091
1092                 public void Handle(ShowFilePropertiesEvent message)
1093                 {
1094                         if (message == null)
1095                                 throw new ArgumentNullException("message");
1096                         if (String.IsNullOrWhiteSpace(message.FileName) )
1097                                 throw new ArgumentException("message");
1098                         Contract.EndContractBlock();
1099
1100                         var fileName = message.FileName;
1101                         //TODO: Display file properties for non-container folders
1102                         if (File.Exists(fileName))
1103                                 //Retrieve the full name with exact casing. Pithos names are case sensitive                             
1104                                 ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
1105                         else if (Directory.Exists(fileName))
1106                                 //Retrieve the full name with exact casing. Pithos names are case sensitive
1107                         {
1108                                 var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
1109                                 if (IsContainer(path))
1110                                         ShowContainerProperties(path);
1111                                 else
1112                                         ShowFileProperties(path);
1113                         }
1114                 }
1115
1116                 private bool IsContainer(string path)
1117                 {
1118                         var matchingFolders = from account in _accounts
1119                                                                   from rootFolder in Directory.GetDirectories(account.AccountPath)
1120                                                                   where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
1121                                                                   select rootFolder;
1122                         return matchingFolders.Any();
1123                 }
1124
1125                 public FileStatus GetFileStatus(string localFileName)
1126                 {
1127                         if (String.IsNullOrWhiteSpace(localFileName))
1128                                 throw new ArgumentNullException("localFileName");
1129                         Contract.EndContractBlock();
1130                         
1131                         var statusKeeper = IoC.Get<IStatusKeeper>();
1132                         var status=statusKeeper.GetFileStatus(localFileName);
1133                         return status;
1134                 }
1135
1136             public void RemoveAccountFromDatabase(AccountSettings account)
1137             {
1138             var statusKeeper = IoC.Get<IStatusKeeper>();
1139             statusKeeper.ClearFolderStatus(account.RootPath);           
1140             }
1141         }
1142 }