Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / Shell / ShellViewModel.cs @ 2341c603

History | View | Annotate | Download (35.5 kB)

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
				if (Monitors.TryGetValue(account.AccountKey, out monitor))
320
				{
321
					//If the account is active
322
                    if (account.IsActive)
323
                    {
324
                        //The Api Key may have changed throuth the Preferences dialog
325
                        monitor.ApiKey = account.ApiKey;
326
						Debug.Assert(monitor.StatusNotification == this,"An existing monitor should already have a StatusNotification service object");
327
                        monitor.RootPath = account.RootPath;
328
                        //Start the monitor. It's OK to start an already started monitor,
329
                        //it will just ignore the call                        
330
                        StartMonitor(monitor).Wait();
331
                    }
332
                    else
333
                    {
334
                        //If the account is inactive
335
                        //Stop and remove the monitor
336
                        RemoveMonitor(account.ServerUrl,accountName);
337
                    }
338
					return;
339
				}
340

    
341
				
342
				//Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
343
				monitor = new PithosMonitor
344
							  {
345
								  UserName = accountName,
346
								  ApiKey = account.ApiKey,                                  
347
								  StatusNotification = this,
348
								  RootPath = account.RootPath
349
							  };
350
				//PithosMonitor uses MEF so we need to resolve it
351
				IoC.BuildUp(monitor);
352

    
353
				monitor.AuthenticationUrl = account.ServerUrl;
354

    
355
				Monitors[account.AccountKey] = monitor;
356

    
357
				if (account.IsActive)
358
				{
359
					//Don't start a monitor if it doesn't have an account and ApiKey
360
					if (String.IsNullOrWhiteSpace(monitor.UserName) ||
361
						String.IsNullOrWhiteSpace(monitor.ApiKey))
362
						return;
363
					StartMonitor(monitor);
364
				}
365
			});
366
		}
367

    
368

    
369
		protected override void OnViewLoaded(object view)
370
		{
371
			UpdateStatus();
372
			var window = (Window)view;            
373
			TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
374
			base.OnViewLoaded(view);
375
		}
376

    
377

    
378
		#region Status Properties
379

    
380
		private string _statusMessage;
381
		public string StatusMessage
382
		{
383
			get { return _statusMessage; }
384
			set
385
			{
386
				_statusMessage = value;
387
				NotifyOfPropertyChange(() => StatusMessage);
388
                NotifyOfPropertyChange(() => TooltipMessage);
389
			}
390
		}
391

    
392
        public string VersionMessage { get; set; }
393

    
394
	    public string TooltipMessage
395
	    {
396
	        get
397
	        {
398
	            return String.Format("{0}\r\n{1}",VersionMessage,StatusMessage);
399
	        }
400
	    }
401

    
402
        public string ToggleStatusWindowMessage
403
        {
404
            get
405
            {
406
                return String.Format("{0}" + Environment.NewLine + "{1} Toggle Mini Status");
407
            }
408
        }
409

    
410
	    private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
411
		public ObservableConcurrentCollection<AccountInfo> Accounts
412
		{
413
			get { return _accounts; }
414
		}
415

    
416
		public bool HasAccounts
417
		{
418
			get { return _accounts.Count > 0; }
419
		}
420

    
421

    
422
		public string OpenFolderCaption
423
		{
424
			get
425
			{
426
				return (_accounts.Count == 0)
427
						? "No Accounts Defined"
428
						: "Open Pithos Folder";
429
			}
430
		}
431

    
432
		private string _pauseSyncCaption="Pause Synching";
433
		public string PauseSyncCaption
434
		{
435
			get { return _pauseSyncCaption; }
436
			set
437
			{
438
				_pauseSyncCaption = value;
439
				NotifyOfPropertyChange(() => PauseSyncCaption);
440
			}
441
		}
442

    
443
		private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
444
		public ObservableConcurrentCollection<FileEntry> RecentFiles
445
		{
446
			get { return _recentFiles; }
447
		}
448

    
449

    
450
		private string _statusIcon="../Images/Pithos.ico";
451
		public string StatusIcon
452
		{
453
			get { return _statusIcon; }
454
			set
455
			{
456
				//TODO: Ensure all status icons use the Pithos logo
457
				_statusIcon = value;
458
				NotifyOfPropertyChange(() => StatusIcon);
459
			}
460
		}
461

    
462
		#endregion
463

    
464
		#region Commands
465

    
466
        public void CancelCurrentOperation()
467
        {
468
            _networkAgent.CancelCurrentOperation();
469
        }
470

    
471
        public void ShowPreferences()
472
        {
473
            ShowPreferences(null);
474
        }
475

    
476
		public void ShowPreferences(string currentTab)
477
		{
478
			//Settings.Reload();
479
		    var preferences = new PreferencesViewModel(_windowManager, _events, this, Settings,currentTab);
480
		    _windowManager.ShowDialog(preferences);
481
			
482
		}
483

    
484
		public void AboutPithos()
485
		{
486
			var about = IoC.Get<AboutViewModel>();
487
		    about.LatestVersion=_sparkle.LatestVersion;
488
			_windowManager.ShowWindow(about);
489
		}
490

    
491
		public void SendFeedback()
492
		{
493
			var feedBack =  IoC.Get<FeedbackViewModel>();
494
			_windowManager.ShowWindow(feedBack);
495
		}
496

    
497
		//public PithosCommand OpenPithosFolderCommand { get; private set; }
498

    
499
		public void OpenPithosFolder()
500
		{
501
			var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
502
			if (account == null)
503
				return;
504
			Process.Start(account.RootPath);
505
		}
506

    
507
		public void OpenPithosFolder(AccountInfo account)
508
		{
509
			Process.Start(account.AccountPath);
510
		}
511

    
512
		
513

    
514
		public void GoToSite()
515
		{            
516
			var site = Properties.Settings.Default.ProductionServer;
517
			Process.Start(site);            
518
		}
519

    
520

    
521
		public void GoToSite(AccountInfo account)
522
		{
523
		    var uri = account.SiteUri.Replace("http://","https://");            
524
		    Process.Start(uri);
525
		}
526

    
527
	    private bool _statusVisible;
528

    
529
	    public string MiniStatusCaption
530
	    {
531
	        get
532
	        {
533
	            return  _statusVisible ? "Hide Status Window" : "Show Status Window";
534
	        }
535
	    }
536

    
537
	    public bool HasConflicts
538
	    {
539
            get { return true; }
540
	    }
541
        public void ShowConflicts()
542
        {
543
            _windowManager.ShowWindow(IoC.Get<ConflictsViewModel>());            
544
        }
545

    
546
	    /// <summary>
547
        /// Open an explorer window to the target path's directory
548
        /// and select the file
549
        /// </summary>
550
        /// <param name="entry"></param>
551
        public void GoToFile(FileEntry entry)
552
        {
553
            var fullPath = entry.FullPath;
554
            if (!File.Exists(fullPath) && !Directory.Exists(fullPath))
555
                return;
556
            Process.Start("explorer.exe","/select, " + fullPath);
557
        }
558

    
559
        public void OpenLogPath()
560
        {
561
            var pithosDataPath = PithosSettings.PithosDataPath;
562

    
563
            Process.Start(pithosDataPath);
564
        }
565
        
566
        public void ShowFileProperties()
567
		{
568
			var account = Settings.Accounts.First(acc => acc.IsActive);            
569
			var dir = new DirectoryInfo(account.RootPath + @"\pithos");
570
			var files=dir.GetFiles();
571
			var r=new Random();
572
			var idx=r.Next(0, files.Length);
573
			ShowFileProperties(files[idx].FullName);            
574
		}
575

    
576
		public void ShowFileProperties(string filePath)
577
		{
578
			if (String.IsNullOrWhiteSpace(filePath))
579
				throw new ArgumentNullException("filePath");
580
			if (!File.Exists(filePath) && !Directory.Exists(filePath))
581
				throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
582
			Contract.EndContractBlock();
583

    
584
			var pair=(from monitor in  Monitors
585
							   where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
586
								   select monitor).FirstOrDefault();
587
			var accountMonitor = pair.Value;
588

    
589
			if (accountMonitor == null)
590
				return;
591

    
592
			var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
593

    
594
			
595

    
596
			var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
597
			_windowManager.ShowWindow(fileProperties);
598
		} 
599
		
600
		public void ShowContainerProperties()
601
		{
602
			var account = Settings.Accounts.First(acc => acc.IsActive);            
603
			var dir = new DirectoryInfo(account.RootPath);
604
			var fullName = (from folder in dir.EnumerateDirectories()
605
							where (folder.Attributes & FileAttributes.Hidden) == 0
606
							select folder.FullName).First();
607
			ShowContainerProperties(fullName);            
608
		}
609

    
610
		public void ShowContainerProperties(string filePath)
611
		{
612
			if (String.IsNullOrWhiteSpace(filePath))
613
				throw new ArgumentNullException("filePath");
614
			if (!Directory.Exists(filePath))
615
				throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
616
			Contract.EndContractBlock();
617

    
618
			var pair=(from monitor in  Monitors
619
							   where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
620
								   select monitor).FirstOrDefault();
621
			var accountMonitor = pair.Value;            
622
			var info = accountMonitor.GetContainerInfo(filePath);
623

    
624
			
625

    
626
			var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
627
			_windowManager.ShowWindow(containerProperties);
628
		}
629

    
630
		public void SynchNow()
631
		{
632
			_pollAgent.SynchNow();
633
		}
634

    
635
		public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
636
		{
637
			if (currentInfo==null)
638
				throw new ArgumentNullException("currentInfo");
639
			Contract.EndContractBlock();		    
640
            var monitor = Monitors[currentInfo.AccountKey];
641
			var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
642
			return newInfo;
643
		}
644

    
645
		public ContainerInfo RefreshContainerInfo(ContainerInfo container)
646
		{
647
			if (container == null)
648
				throw new ArgumentNullException("container");
649
			Contract.EndContractBlock();
650

    
651
			var monitor = Monitors[container.AccountKey];
652
			var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
653
			return newInfo;
654
		}
655

    
656
	    private bool _isPaused;
657
	    public bool IsPaused
658
	    {
659
	        get { return _isPaused; }
660
	        set
661
	        {
662
	            _isPaused = value;
663
                PauseSyncCaption = IsPaused ? "Resume syncing" : "Pause syncing";
664
                var iconKey = IsPaused ? "TraySyncPaused" : "TrayInSynch";
665
                StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
666

    
667
                NotifyOfPropertyChange(() => IsPaused);
668
	        }
669
	    }
670

    
671
	    public void ToggleSynching()
672
		{
673
			IsPaused=!IsPaused;
674
			foreach (var monitor in Monitors.Values)
675
			{
676
			    monitor.Pause = IsPaused ;
677
			}
678
            _pollAgent.Pause = IsPaused;
679
            _networkAgent.Pause = IsPaused;
680

    
681

    
682
		}
683

    
684
        public void ExitPithos()
685
        {
686
            try
687
            {
688

    
689
                foreach (var monitor in Monitors.Select(pair => pair.Value))
690
                {
691
                    monitor.Stop();
692
                }
693

    
694
                var view = GetView() as Window;
695
                if (view != null)
696
                    view.Close();
697
            }
698
            catch (Exception exc)
699
            {
700
                Log.Info("Exception while exiting", exc);                
701
            }
702
            finally
703
            {
704
                Application.Current.Shutdown();
705
            }
706
        }
707

    
708
	    #endregion
709

    
710

    
711
		private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
712
			{
713
				new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
714
				new StatusInfo(PithosStatus.PollSyncing, "Polling Files", "TraySynching"),
715
                new StatusInfo(PithosStatus.LocalSyncing, "Syncing Files", "TraySynching"),
716
				new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
717
			}.ToDictionary(s => s.Status);
718

    
719
		readonly IWindowManager _windowManager;
720
		
721
        //private int _syncCount=0;
722

    
723

    
724
        private PithosStatus _pithosStatus = PithosStatus.Disconnected;
725

    
726
        public void SetPithosStatus(PithosStatus status)
727
        {
728
            if (_pithosStatus == PithosStatus.LocalSyncing && status == PithosStatus.PollComplete)
729
                return;
730
            if (_pithosStatus == PithosStatus.PollSyncing && status == PithosStatus.LocalComplete)
731
                return;
732
            if (status == PithosStatus.LocalComplete || status == PithosStatus.PollComplete)
733
                _pithosStatus = PithosStatus.InSynch;
734
            else
735
                _pithosStatus = status;
736
            UpdateStatus();
737
        }
738

    
739
        public void SetPithosStatus(PithosStatus status,string message)
740
        {
741
            StatusMessage = message;
742
            SetPithosStatus(status);
743
        }
744

    
745
	  /*  public Notifier GetNotifier(Notification startNotification, Notification endNotification)
746
	    {
747
	        return new Notifier(this, startNotification, endNotification);
748
	    }*/
749

    
750
	    public Notifier GetNotifier(string startMessage, string endMessage, params object[] args)
751
	    {
752
	        return new Notifier(this, 
753
                new StatusNotification(String.Format(startMessage,args)), 
754
                new StatusNotification(String.Format(endMessage,args)));
755
	    }
756

    
757

    
758
	    ///<summary>
759
		/// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat		
760
		///</summary>
761
		public void UpdateStatus()
762
		{
763

    
764
			if (_iconNames.ContainsKey(_pithosStatus))
765
			{
766
				var info = _iconNames[_pithosStatus];
767
				StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
768
			}
769

    
770
            if (_pithosStatus == PithosStatus.InSynch)
771
                StatusMessage = "All files up to date";
772
		}
773

    
774

    
775
	   
776
		private Task StartMonitor(PithosMonitor monitor,int retries=0)
777
		{
778
			return Task.Factory.StartNew(() =>
779
			{
780
				using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
781
				{
782
					try
783
					{
784
						Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
785

    
786
						monitor.Start();
787
					}
788
					catch (WebException exc)
789
					{
790
						if (AbandonRetry(monitor, retries))
791
							return;
792

    
793
						HttpStatusCode statusCode =HttpStatusCode.OK;
794
						var response = exc.Response as HttpWebResponse;
795
						if(response!=null)
796
							statusCode = response.StatusCode;
797

    
798
						switch (statusCode)
799
						{
800
							case HttpStatusCode.Unauthorized:
801
								var message = String.Format("API Key Expired for {0}. Starting Renewal",
802
															monitor.UserName);
803
								Log.Error(message, exc);
804
                                var account = Settings.Accounts.Find(acc => acc.AccountKey == new Uri(new Uri(monitor.AuthenticationUrl), monitor.UserName));                                
805
						        account.IsExpired = true;
806
                                Notify(new ExpirationNotification(account));
807
								//TryAuthorize(monitor.UserName, retries).Wait();
808
								break;
809
							case HttpStatusCode.ProxyAuthenticationRequired:
810
								TryAuthenticateProxy(monitor,retries);
811
								break;
812
							default:
813
								TryLater(monitor, exc, retries);
814
								break;
815
						}
816
					}
817
					catch (Exception exc)
818
					{
819
						if (AbandonRetry(monitor, retries)) 
820
							return;
821

    
822
						TryLater(monitor,exc,retries);
823
					}
824
				}
825
			});
826
		}
827

    
828
		private void TryAuthenticateProxy(PithosMonitor monitor,int retries)
829
		{
830
			Execute.OnUIThread(() =>
831
								   {                                       
832
									   var proxyAccount = IoC.Get<ProxyAccountViewModel>();
833
										proxyAccount.Settings = Settings;
834
									   if (true != _windowManager.ShowDialog(proxyAccount)) 
835
										   return;
836
									   StartMonitor(monitor, retries);
837
									   NotifyOfPropertyChange(() => Accounts);
838
								   });
839
		}
840

    
841
		private bool AbandonRetry(PithosMonitor monitor, int retries)
842
		{
843
			if (retries > 1)
844
			{
845
				var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
846
											monitor.UserName);
847
				_events.Publish(new Notification
848
									{Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
849
				return true;
850
			}
851
			return false;
852
		}
853

    
854

    
855
	    private void TryLater(PithosMonitor monitor, Exception exc,int retries)
856
		{
857
			var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
858
			Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
859
			_events.Publish(new Notification
860
								{Title = "Error", Message = message, Level = TraceLevel.Error});
861
			Log.Error(message, exc);
862
		}
863

    
864

    
865
		public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
866
		{
867
			StatusMessage = status;
868
			
869
			_events.Publish(new Notification { Title = "Pithos+", Message = status, Level = level });
870
		}
871

    
872
		public void NotifyChangedFile(string filePath)
873
		{
874
            if (RecentFiles.Any(e => e.FullPath == filePath))
875
                return;
876
            
877
			IProducerConsumerCollection<FileEntry> files=RecentFiles;
878
			FileEntry popped;
879
			while (files.Count > 5)
880
				files.TryTake(out popped);
881
            var entry = new FileEntry { FullPath = filePath };
882
			files.TryAdd(entry);
883
		}
884

    
885
		public void NotifyAccount(AccountInfo account)
886
		{
887
			if (account== null)
888
				return;
889
			//TODO: What happens to an existing account whose Token has changed?
890
			account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
891
				account.SiteUri, Uri.EscapeDataString(account.Token),
892
				Uri.EscapeDataString(account.UserName));
893

    
894
			if (!Accounts.Any(item => item.UserName == account.UserName && item.SiteUri == account.SiteUri))
895
				Accounts.TryAdd(account);
896

    
897
		}
898

    
899
		public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
900
		{
901
			if (conflictFiles == null)
902
				return;
903
		    //Convert to list to avoid multiple iterations
904
            var files = conflictFiles.ToList();
905
			if (files.Count==0)
906
				return;
907

    
908
			UpdateStatus();
909
			//TODO: Create a more specific message. For now, just show a warning
910
			NotifyForFiles(files,message,TraceLevel.Warning);
911

    
912
		}
913

    
914
		public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info)
915
		{
916
			if (files == null)
917
				return;
918
			if (!files.Any())
919
				return;
920

    
921
			StatusMessage = message;
922

    
923
			_events.Publish(new Notification { Title = "Pithos+", Message = message, Level = level});
924
		}
925

    
926
		public void Notify(Notification notification)
927
		{
928
			_events.Publish(notification);
929
		}
930

    
931

    
932
		public void RemoveMonitor(string serverUrl,string accountName)
933
		{
934
			if (String.IsNullOrWhiteSpace(accountName))
935
				return;
936

    
937
			var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName && account.StorageUri.ToString().StartsWith(serverUrl));
938
            if (accountInfo != null)
939
            {
940
                _accounts.TryRemove(accountInfo);
941
                _pollAgent.RemoveAccount(accountInfo);
942
            }
943

    
944
            var accountKey = new Uri(new Uri(serverUrl),accountName);
945
		    PithosMonitor monitor;
946
			if (Monitors.TryRemove(accountKey, out monitor))
947
			{
948
				monitor.Stop();
949
                //TODO: Also remove any pending actions for this account
950
                //from the network queue                
951
			}
952
		}
953

    
954
		public void RefreshOverlays()
955
		{
956
			foreach (var pair in Monitors)
957
			{
958
				var monitor = pair.Value;
959

    
960
				var path = monitor.RootPath;
961

    
962
				if (String.IsNullOrWhiteSpace(path))
963
					continue;
964

    
965
				if (!Directory.Exists(path) && !File.Exists(path))
966
					continue;
967

    
968
				IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
969

    
970
				try
971
				{
972
					NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
973
												 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
974
												 pathPointer, IntPtr.Zero);
975
				}
976
				finally
977
				{
978
					Marshal.FreeHGlobal(pathPointer);
979
				}
980
			}
981
		}
982

    
983
		#region Event Handlers
984
		
985
		public void Handle(SelectiveSynchChanges message)
986
        {
987
            PithosMonitor monitor;
988
            if (Monitors.TryGetValue(message.Account.AccountKey, out monitor))
989
            {
990
                monitor.SetSelectivePaths(message.Uris, message.Added, message.Removed);
991

    
992
            }
993

    
994
            var account = Accounts.FirstOrDefault(acc => acc.AccountKey == message.Account.AccountKey);
995
            if (account!=null)
996
            {
997
                this._pollAgent.SetSelectivePaths(account, message.Added, message.Removed);
998
            }
999

    
1000

    
1001
        }
1002

    
1003

    
1004
		private bool _pollStarted;
1005
	    private Sparkle _sparkle;
1006
	    private bool _manualUpgradeCheck;
1007

    
1008
	    //SMELL: Doing so much work for notifications in the shell is wrong
1009
		//The notifications should be moved to their own view/viewmodel pair
1010
		//and different templates should be used for different message types
1011
		//This will also allow the addition of extra functionality, eg. actions
1012
		//
1013
		public void Handle(Notification notification)
1014
		{
1015
			UpdateStatus();
1016

    
1017
			if (!Settings.ShowDesktopNotifications)
1018
				return;
1019

    
1020
			if (notification is PollNotification)
1021
			{
1022
				_pollStarted = true;
1023
				return;
1024
			}
1025
			if (notification is CloudNotification)
1026
			{
1027
				if (!_pollStarted) 
1028
					return;
1029
				_pollStarted= false;
1030
				notification.Title = "Pithos+";
1031
				notification.Message = "Start Synchronisation";
1032
			}
1033

    
1034
		    var deleteNotification = notification as CloudDeleteNotification;
1035
            if (deleteNotification != null)
1036
            {
1037
                StatusMessage = String.Format("Deleted {0}", deleteNotification.Data.Name);
1038
                return;
1039
            }
1040

    
1041
		    var progress = notification as ProgressNotification;
1042
		    
1043
		    
1044
            if (progress != null)
1045
		    {
1046
		        StatusMessage = String.Format("{0} {1:p2} of {2} - {3}",		                                      
1047
                                              progress.Action,
1048
		                                      progress.Block/(double)progress.TotalBlocks,
1049
		                                      progress.FileSize.ToByteSize(),
1050
		                                      progress.FileName);
1051
		        return;
1052
		    }
1053

    
1054
		    var info = notification as StatusNotification;
1055
            if (info != null)
1056
            {
1057
                StatusMessage = info.Title;
1058
                return;
1059
            }
1060
			if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
1061
				return;
1062

    
1063
            if (notification.Level <= TraceLevel.Warning)
1064
			    ShowBalloonFor(notification);
1065
		}
1066

    
1067
	    private void ShowBalloonFor(Notification notification)
1068
	    {
1069
            Contract.Requires(notification!=null);
1070
            
1071
            if (!Settings.ShowDesktopNotifications) 
1072
                return;
1073
            
1074
            BalloonIcon icon;
1075
	        switch (notification.Level)
1076
	        {
1077
                case TraceLevel.Verbose:
1078
	                return;
1079
	            case TraceLevel.Info:	            
1080
	                icon = BalloonIcon.Info;
1081
	                break;
1082
                case TraceLevel.Error:
1083
                    icon = BalloonIcon.Error;
1084
                    break;
1085
                case TraceLevel.Warning:
1086
	                icon = BalloonIcon.Warning;
1087
	                break;
1088
	            default:
1089
	                return;
1090
	        }
1091

    
1092
	        var tv = (ShellView) GetView();
1093
	        System.Action clickAction = null;
1094
	        if (notification is ExpirationNotification)
1095
	        {
1096
	            clickAction = () => ShowPreferences("AccountTab");
1097
	        }
1098
	        var balloon = new PithosBalloon
1099
	                          {
1100
	                              Title = notification.Title,
1101
	                              Message = notification.Message,
1102
	                              Icon = icon,
1103
	                              ClickAction = clickAction
1104
	                          };
1105
	        tv.TaskbarView.ShowCustomBalloon(balloon, PopupAnimation.Fade, 4000);
1106
	    }
1107

    
1108
	    #endregion
1109

    
1110
		public void Handle(ShowFilePropertiesEvent message)
1111
		{
1112
			if (message == null)
1113
				throw new ArgumentNullException("message");
1114
			if (String.IsNullOrWhiteSpace(message.FileName) )
1115
				throw new ArgumentException("message");
1116
			Contract.EndContractBlock();
1117

    
1118
			var fileName = message.FileName;
1119
			//TODO: Display file properties for non-container folders
1120
			if (File.Exists(fileName))
1121
				//Retrieve the full name with exact casing. Pithos names are case sensitive				
1122
				ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
1123
			else if (Directory.Exists(fileName))
1124
				//Retrieve the full name with exact casing. Pithos names are case sensitive
1125
			{
1126
				var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
1127
				if (IsContainer(path))
1128
					ShowContainerProperties(path);
1129
				else
1130
					ShowFileProperties(path);
1131
			}
1132
		}
1133

    
1134
		private bool IsContainer(string path)
1135
		{
1136
			var matchingFolders = from account in _accounts
1137
								  from rootFolder in Directory.GetDirectories(account.AccountPath)
1138
								  where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
1139
								  select rootFolder;
1140
			return matchingFolders.Any();
1141
		}
1142

    
1143
		public FileStatus GetFileStatus(string localFileName)
1144
		{
1145
			if (String.IsNullOrWhiteSpace(localFileName))
1146
				throw new ArgumentNullException("localFileName");
1147
			Contract.EndContractBlock();
1148
			
1149
			var statusKeeper = IoC.Get<IStatusKeeper>();
1150
			var status=statusKeeper.GetFileStatus(localFileName);
1151
			return status;
1152
		}
1153

    
1154
	    public void RemoveAccountFromDatabase(AccountSettings account)
1155
	    {
1156
            var statusKeeper = IoC.Get<IStatusKeeper>();
1157
            statusKeeper.ClearFolderStatus(account.RootPath);	        
1158
	    }
1159
	}
1160
}