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