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