Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / Shell / ShellViewModel.cs @ 9d2c0fc0

History | View | Annotate | Download (27.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 Caliburn.Micro;
54
using Hardcodet.Wpf.TaskbarNotification;
55
using Pithos.Client.WPF.Configuration;
56
using Pithos.Client.WPF.FileProperties;
57
using Pithos.Client.WPF.Preferences;
58
using Pithos.Client.WPF.SelectiveSynch;
59
using Pithos.Client.WPF.Services;
60
using Pithos.Client.WPF.Shell;
61
using Pithos.Core;
62
using Pithos.Core.Agents;
63
using Pithos.Interfaces;
64
using System;
65
using System.Collections.Generic;
66
using System.Linq;
67
using Pithos.Network;
68
using StatusService = Pithos.Client.WPF.Services.StatusService;
69

    
70
namespace Pithos.Client.WPF {
71
	using System.ComponentModel.Composition;
72

    
73
	
74
	///<summary>
75
	/// The "shell" of the Pithos application displays the taskbar  icon, menu and notifications.
76
	/// The shell also hosts the status service called by shell extensions to retrieve file info
77
	///</summary>
78
	///<remarks>
79
	/// It is a strange "shell" as its main visible element is an icon instead of a window
80
	/// The shell subscribes to the following events:
81
	/// * Notification:  Raised by components that want to notify the user. Usually displayed in a balloon
82
	/// * 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
83
	/// * ShowFilePropertiesEvent: Raised when a shell command requests the display of the file/container properties dialog
84
	///</remarks>		
85
	//TODO: CODE SMELL Why does the shell handle the SelectiveSynchChanges?
86
	[Export(typeof(IShell))]
87
	public class ShellViewModel : Screen, IStatusNotification, IShell,
88
		IHandle<Notification>, IHandle<SelectiveSynchChanges>, IHandle<ShowFilePropertiesEvent>
89
	{
90

    
91
		//The Status Checker provides the current synch state
92
		//TODO: Could we remove the status checker and use events in its place?
93
		private readonly IStatusChecker _statusChecker;
94
		private readonly IEventAggregator _events;
95

    
96
		public PithosSettings Settings { get; private set; }
97

    
98

    
99
		private readonly ConcurrentDictionary<string, PithosMonitor> _monitors = new ConcurrentDictionary<string, PithosMonitor>();
100
		///<summary>
101
		/// Dictionary of account monitors, keyed by account
102
		///</summary>
103
		///<remarks>
104
		/// One monitor class is created for each account. The Shell needs access to the monitors to execute start/stop/pause commands,
105
		/// retrieve account and boject info		
106
		///</remarks>
107
		// TODO: Does the Shell REALLY need access to the monitors? Could we achieve the same results with a better design?
108
		// TODO: The monitors should be internal to Pithos.Core, even though exposing them makes coding of the Object and Container windows easier
109
		public ConcurrentDictionary<string, PithosMonitor> Monitors
110
		{
111
			get { return _monitors; }
112
		}
113

    
114

    
115
		///<summary>
116
		/// The status service is used by Shell extensions to retrieve file status information
117
		///</summary>
118
		//TODO: CODE SMELL! This is the shell! While hosting in the shell makes executing start/stop commands easier, it is still a smell
119
		private ServiceHost _statusService;
120

    
121
		//Logging in the Pithos client is provided by log4net
122
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
123

    
124
		//Lazily initialized File Version info. This is done once and lazily to avoid blocking the UI
125
		private readonly Lazy<FileVersionInfo> _fileVersion;
126

    
127
	    private readonly PollAgent _pollAgent;
128

    
129
		///<summary>
130
		/// The Shell depends on MEF to provide implementations for windowManager, events, the status checker service and the settings
131
		///</summary>
132
		///<remarks>
133
		/// The PithosSettings class encapsulates the app's settings to abstract their storage mechanism (App settings, a database or registry)
134
		///</remarks>
135
		[ImportingConstructor]		
136
		public ShellViewModel(IWindowManager windowManager, IEventAggregator events, IStatusChecker statusChecker, PithosSettings settings,PollAgent pollAgent)
137
		{
138
			try
139
			{
140

    
141
				_windowManager = windowManager;
142
				//CHECK: Caliburn doesn't need explicit command construction
143
				//OpenPithosFolderCommand = new PithosCommand(OpenPithosFolder);
144
				_statusChecker = statusChecker;
145
				//The event subst
146
				_events = events;
147
				_events.Subscribe(this);
148

    
149
			    _pollAgent = pollAgent;
150
				Settings = settings;
151

    
152
				Proxy.SetFromSettings(settings);
153

    
154
				StatusMessage = "In Synch";
155

    
156
				_fileVersion=  new Lazy<FileVersionInfo>(() =>
157
				{
158
					Assembly assembly = Assembly.GetExecutingAssembly();
159
					var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
160
					return fileVersion;
161
				});
162
				_accounts.CollectionChanged += (sender, e) =>
163
												   {
164
													   NotifyOfPropertyChange(() => OpenFolderCaption);
165
													   NotifyOfPropertyChange(() => HasAccounts);
166
												   };
167

    
168
			}
169
			catch (Exception exc)
170
			{
171
				Log.Error("Error while starting the ShellViewModel",exc);
172
				throw;
173
			}
174

    
175
		}
176

    
177

    
178
		protected override void OnActivate()
179
		{
180
			base.OnActivate();
181

    
182
			
183

    
184
			StartMonitoring();                    
185
		}
186

    
187

    
188

    
189
		private async void StartMonitoring()
190
		{
191
			try
192
			{
193
				var accounts = Settings.Accounts.Select(MonitorAccount);
194
				await TaskEx.WhenAll(accounts);
195
				_statusService = StatusService.Start();
196

    
197
/*
198
				foreach (var account in Settings.Accounts)
199
				{
200
					await MonitorAccount(account);
201
				}
202
*/
203
				
204
			}
205
			catch (AggregateException exc)
206
			{
207
				exc.Handle(e =>
208
				{
209
					Log.Error("Error while starting monitoring", e);
210
					return true;
211
				});
212
				throw;
213
			}
214
		}
215

    
216
		protected override void OnDeactivate(bool close)
217
		{
218
			base.OnDeactivate(close);
219
			if (close)
220
			{
221
				StatusService.Stop(_statusService);
222
				_statusService = null;
223
			}
224
		}
225

    
226
		public Task MonitorAccount(AccountSettings account)
227
		{
228
			return Task.Factory.StartNew(() =>
229
			{                                                
230
				PithosMonitor monitor;
231
				var accountName = account.AccountName;
232

    
233
				if (_monitors.TryGetValue(accountName, out monitor))
234
				{
235
					//If the account is active
236
                    if (account.IsActive)
237
                    {
238
                        //The Api Key may have changed throuth the Preferences dialog
239
                        monitor.ApiKey = account.ApiKey;
240
						Debug.Assert(monitor.StatusNotification == this,"An existing monitor should already have a StatusNotification service object");
241
                        monitor.RootPath = account.RootPath;
242
                        //Start the monitor. It's OK to start an already started monitor,
243
                        //it will just ignore the call                        
244
                        StartMonitor(monitor).Wait();
245
                    }
246
                    else
247
                    {
248
                        //If the account is inactive
249
                        //Stop and remove the monitor
250
                        RemoveMonitor(accountName);
251
                    }
252
					return;
253
				}
254

    
255
				
256
				//Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
257
				monitor = new PithosMonitor
258
							  {
259
								  UserName = accountName,
260
								  ApiKey = account.ApiKey,                                  
261
								  StatusNotification = this,
262
								  RootPath = account.RootPath
263
							  };
264
				//PithosMonitor uses MEF so we need to resolve it
265
				IoC.BuildUp(monitor);
266

    
267
				monitor.AuthenticationUrl = account.ServerUrl;
268

    
269
				_monitors[accountName] = monitor;
270

    
271
				if (account.IsActive)
272
				{
273
					//Don't start a monitor if it doesn't have an account and ApiKey
274
					if (String.IsNullOrWhiteSpace(monitor.UserName) ||
275
						String.IsNullOrWhiteSpace(monitor.ApiKey))
276
						return;
277
					StartMonitor(monitor);
278
				}
279
			});
280
		}
281

    
282

    
283
		protected override void OnViewLoaded(object view)
284
		{
285
			UpdateStatus();
286
			var window = (Window)view;            
287
			TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
288
			base.OnViewLoaded(view);
289
		}
290

    
291

    
292
		#region Status Properties
293

    
294
		private string _statusMessage;
295
		public string StatusMessage
296
		{
297
			get { return _statusMessage; }
298
			set
299
			{
300
				_statusMessage = value;
301
				NotifyOfPropertyChange(() => StatusMessage);
302
			}
303
		}
304

    
305
		private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
306
		public ObservableConcurrentCollection<AccountInfo> Accounts
307
		{
308
			get { return _accounts; }
309
		}
310

    
311
		public bool HasAccounts
312
		{
313
			get { return _accounts.Count > 0; }
314
		}
315

    
316

    
317
		public string OpenFolderCaption
318
		{
319
			get
320
			{
321
				return (_accounts.Count == 0)
322
						? "No Accounts Defined"
323
						: "Open Pithos Folder";
324
			}
325
		}
326

    
327
		private string _pauseSyncCaption="Pause Synching";
328
		public string PauseSyncCaption
329
		{
330
			get { return _pauseSyncCaption; }
331
			set
332
			{
333
				_pauseSyncCaption = value;
334
				NotifyOfPropertyChange(() => PauseSyncCaption);
335
			}
336
		}
337

    
338
		private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
339
		public ObservableConcurrentCollection<FileEntry> RecentFiles
340
		{
341
			get { return _recentFiles; }
342
		}
343

    
344

    
345
		private string _statusIcon="../Images/Pithos.ico";
346
		public string StatusIcon
347
		{
348
			get { return _statusIcon; }
349
			set
350
			{
351
				//TODO: Ensure all status icons use the Pithos logo
352
				_statusIcon = value;
353
				NotifyOfPropertyChange(() => StatusIcon);
354
			}
355
		}
356

    
357
		#endregion
358

    
359
		#region Commands
360

    
361
        public void ShowPreferences()
362
        {
363
            ShowPreferences(null);
364
        }
365

    
366
		public void ShowPreferences(string currentTab)
367
		{
368
			//Settings.Reload();
369
		    var preferences = new PreferencesViewModel(_windowManager, _events, this, Settings,currentTab);
370
		    _windowManager.ShowDialog(preferences);
371
			
372
		}
373

    
374
		public void AboutPithos()
375
		{
376
			var about = new AboutViewModel();
377
			_windowManager.ShowWindow(about);
378
		}
379

    
380
		public void SendFeedback()
381
		{
382
			var feedBack =  IoC.Get<FeedbackViewModel>();
383
			_windowManager.ShowWindow(feedBack);
384
		}
385

    
386
		//public PithosCommand OpenPithosFolderCommand { get; private set; }
387

    
388
		public void OpenPithosFolder()
389
		{
390
			var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
391
			if (account == null)
392
				return;
393
			Process.Start(account.RootPath);
394
		}
395

    
396
		public void OpenPithosFolder(AccountInfo account)
397
		{
398
			Process.Start(account.AccountPath);
399
		}
400

    
401
		
402
/*
403
		public void GoToSite()
404
		{            
405
			var site = Properties.Settings.Default.PithosSite;
406
			Process.Start(site);            
407
		}
408
*/
409

    
410
		public void GoToSite(AccountInfo account)
411
		{
412
		    var uri = account.SiteUri.Replace("http://","https://");            
413
		    Process.Start(uri);
414
		}
415

    
416
	    /// <summary>
417
        /// Open an explorer window to the target path's directory
418
        /// and select the file
419
        /// </summary>
420
        /// <param name="entry"></param>
421
        public void GoToFile(FileEntry entry)
422
        {
423
            var fullPath = entry.FullPath;
424
            if (!File.Exists(fullPath) && !Directory.Exists(fullPath))
425
                return;
426
            Process.Start("explorer.exe","/select, " + fullPath);
427
        }
428

    
429
        public void OpenLogPath()
430
        {
431
            var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
432
            var pithosDataPath = Path.Combine(appDataPath, "GRNET");
433

    
434
            Process.Start(pithosDataPath);
435
        }
436
        
437
        public void ShowFileProperties()
438
		{
439
			var account = Settings.Accounts.First(acc => acc.IsActive);            
440
			var dir = new DirectoryInfo(account.RootPath + @"\pithos");
441
			var files=dir.GetFiles();
442
			var r=new Random();
443
			var idx=r.Next(0, files.Length);
444
			ShowFileProperties(files[idx].FullName);            
445
		}
446

    
447
		public void ShowFileProperties(string filePath)
448
		{
449
			if (String.IsNullOrWhiteSpace(filePath))
450
				throw new ArgumentNullException("filePath");
451
			if (!File.Exists(filePath) && !Directory.Exists(filePath))
452
				throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
453
			Contract.EndContractBlock();
454

    
455
			var pair=(from monitor in  Monitors
456
							   where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
457
								   select monitor).FirstOrDefault();
458
			var accountMonitor = pair.Value;
459

    
460
			if (accountMonitor == null)
461
				return;
462

    
463
			var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
464

    
465
			
466

    
467
			var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
468
			_windowManager.ShowWindow(fileProperties);
469
		} 
470
		
471
		public void ShowContainerProperties()
472
		{
473
			var account = Settings.Accounts.First(acc => acc.IsActive);            
474
			var dir = new DirectoryInfo(account.RootPath);
475
			var fullName = (from folder in dir.EnumerateDirectories()
476
							where (folder.Attributes & FileAttributes.Hidden) == 0
477
							select folder.FullName).First();
478
			ShowContainerProperties(fullName);            
479
		}
480

    
481
		public void ShowContainerProperties(string filePath)
482
		{
483
			if (String.IsNullOrWhiteSpace(filePath))
484
				throw new ArgumentNullException("filePath");
485
			if (!Directory.Exists(filePath))
486
				throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
487
			Contract.EndContractBlock();
488

    
489
			var pair=(from monitor in  Monitors
490
							   where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
491
								   select monitor).FirstOrDefault();
492
			var accountMonitor = pair.Value;            
493
			var info = accountMonitor.GetContainerInfo(filePath);
494

    
495
			
496

    
497
			var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
498
			_windowManager.ShowWindow(containerProperties);
499
		}
500

    
501
		public void SynchNow()
502
		{
503
			_pollAgent.SynchNow();
504
		}
505

    
506
		public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
507
		{
508
			if (currentInfo==null)
509
				throw new ArgumentNullException("currentInfo");
510
			Contract.EndContractBlock();
511

    
512
			var monitor = Monitors[currentInfo.Account];
513
			var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
514
			return newInfo;
515
		}
516

    
517
		public ContainerInfo RefreshContainerInfo(ContainerInfo container)
518
		{
519
			if (container == null)
520
				throw new ArgumentNullException("container");
521
			Contract.EndContractBlock();
522

    
523
			var monitor = Monitors[container.Account];
524
			var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
525
			return newInfo;
526
		}
527

    
528

    
529
		public void ToggleSynching()
530
		{
531
			bool isPaused=false;
532
			foreach (var pair in Monitors)
533
			{
534
				var monitor = pair.Value;
535
				monitor.Pause = !monitor.Pause;
536
				isPaused = monitor.Pause;
537
			}
538

    
539
			PauseSyncCaption = isPaused ? "Resume syncing" : "Pause syncing";
540
			var iconKey = isPaused? "TraySyncPaused" : "TrayInSynch";
541
			StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
542
		}
543

    
544
		public void ExitPithos()
545
		{
546
			foreach (var pair in Monitors)
547
			{
548
				var monitor = pair.Value;
549
				monitor.Stop();
550
			}
551

    
552
			((Window)GetView()).Close();
553
		}
554
		#endregion
555

    
556

    
557
		private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
558
			{
559
				new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
560
				new StatusInfo(PithosStatus.Syncing, "Syncing Files", "TraySynching"),
561
				new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
562
			}.ToDictionary(s => s.Status);
563

    
564
		readonly IWindowManager _windowManager;
565
		
566

    
567
		///<summary>
568
		/// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat		
569
		///</summary>
570
		public void UpdateStatus()
571
		{
572
			var pithosStatus = _statusChecker.GetPithosStatus();
573

    
574
			if (_iconNames.ContainsKey(pithosStatus))
575
			{
576
				var info = _iconNames[pithosStatus];
577
				StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
578

    
579

    
580

    
581
				StatusMessage = String.Format("Pithos {0}\r\n{1}", _fileVersion.Value.FileVersion,info.StatusText);
582
			}
583
			
584
			//_events.Publish(new Notification { Title = "Start", Message = "Start Monitoring", Level = TraceLevel.Info});
585
		}
586

    
587

    
588
	   
589
		private Task StartMonitor(PithosMonitor monitor,int retries=0)
590
		{
591
			return Task.Factory.StartNew(() =>
592
			{
593
				using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
594
				{
595
					try
596
					{
597
						Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
598

    
599
						monitor.Start();
600
					}
601
					catch (WebException exc)
602
					{
603
						if (AbandonRetry(monitor, retries))
604
							return;
605

    
606
						HttpStatusCode statusCode =HttpStatusCode.OK;
607
						var response = exc.Response as HttpWebResponse;
608
						if(response!=null)
609
							statusCode = response.StatusCode;
610

    
611
						switch (statusCode)
612
						{
613
							case HttpStatusCode.Unauthorized:
614
								var message = String.Format("API Key Expired for {0}. Starting Renewal",
615
															monitor.UserName);
616
								Log.Error(message, exc);
617
						        var account = Settings.Accounts.Find(acc => acc.AccountName == monitor.UserName);                                
618
						        account.IsExpired = true;
619
                                Notify(new ExpirationNotification(account));
620
								//TryAuthorize(monitor.UserName, retries).Wait();
621
								break;
622
							case HttpStatusCode.ProxyAuthenticationRequired:
623
								TryAuthenticateProxy(monitor,retries);
624
								break;
625
							default:
626
								TryLater(monitor, exc, retries);
627
								break;
628
						}
629
					}
630
					catch (Exception exc)
631
					{
632
						if (AbandonRetry(monitor, retries)) 
633
							return;
634

    
635
						TryLater(monitor,exc,retries);
636
					}
637
				}
638
			});
639
		}
640

    
641
		private void TryAuthenticateProxy(PithosMonitor monitor,int retries)
642
		{
643
			Execute.OnUIThread(() =>
644
								   {                                       
645
									   var proxyAccount = IoC.Get<ProxyAccountViewModel>();
646
										proxyAccount.Settings = Settings;
647
									   if (true != _windowManager.ShowDialog(proxyAccount)) 
648
										   return;
649
									   StartMonitor(monitor, retries);
650
									   NotifyOfPropertyChange(() => Accounts);
651
								   });
652
		}
653

    
654
		private bool AbandonRetry(PithosMonitor monitor, int retries)
655
		{
656
			if (retries > 1)
657
			{
658
				var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
659
											monitor.UserName);
660
				_events.Publish(new Notification
661
									{Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
662
				return true;
663
			}
664
			return false;
665
		}
666

    
667

    
668
	    private void TryLater(PithosMonitor monitor, Exception exc,int retries)
669
		{
670
			var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
671
			Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
672
			_events.Publish(new Notification
673
								{Title = "Error", Message = message, Level = TraceLevel.Error});
674
			Log.Error(message, exc);
675
		}
676

    
677

    
678
		public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
679
		{
680
			StatusMessage = status;
681
			
682
			_events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
683
		}
684

    
685
		public void NotifyChangedFile(string filePath)
686
		{
687
            if (RecentFiles.Any(e => e.FullPath == filePath))
688
                return;
689
            
690
			IProducerConsumerCollection<FileEntry> files=RecentFiles;
691
			FileEntry popped;
692
			while (files.Count > 5)
693
				files.TryTake(out popped);
694
            var entry = new FileEntry { FullPath = filePath };
695
			files.TryAdd(entry);
696
		}
697

    
698
		public void NotifyAccount(AccountInfo account)
699
		{
700
			if (account== null)
701
				return;
702
			//TODO: What happens to an existing account whose Token has changed?
703
			account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
704
				account.SiteUri, Uri.EscapeDataString(account.Token),
705
				Uri.EscapeDataString(account.UserName));
706

    
707
			if (Accounts.All(item => item.UserName != account.UserName))
708
				Accounts.TryAdd(account);
709

    
710
		}
711

    
712
		public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
713
		{
714
			if (conflictFiles == null)
715
				return;
716
		    //Convert to list to avoid multiple iterations
717
            var files = conflictFiles.ToList();
718
			if (files.Count==0)
719
				return;
720

    
721
			UpdateStatus();
722
			//TODO: Create a more specific message. For now, just show a warning
723
			NotifyForFiles(files,message,TraceLevel.Warning);
724

    
725
		}
726

    
727
		public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info)
728
		{
729
			if (files == null)
730
				return;
731
			if (!files.Any())
732
				return;
733

    
734
			StatusMessage = message;
735

    
736
			_events.Publish(new Notification { Title = "Pithos", Message = message, Level = level});
737
		}
738

    
739
		public void Notify(Notification notification)
740
		{
741
			_events.Publish(notification);
742
		}
743

    
744

    
745
		public void RemoveMonitor(string accountName)
746
		{
747
			if (String.IsNullOrWhiteSpace(accountName))
748
				return;
749

    
750
			var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName);
751
            if (accountInfo != null)
752
            {
753
                _accounts.TryRemove(accountInfo);
754
                _pollAgent.RemoveAccount(accountInfo);
755
            }
756

    
757
		    PithosMonitor monitor;
758
			if (Monitors.TryRemove(accountName, out monitor))
759
			{
760
				monitor.Stop();
761
                //TODO: Also remove any pending actions for this account
762
                //from the network queue                
763
			}
764
		}
765

    
766
		public void RefreshOverlays()
767
		{
768
			foreach (var pair in Monitors)
769
			{
770
				var monitor = pair.Value;
771

    
772
				var path = monitor.RootPath;
773

    
774
				if (String.IsNullOrWhiteSpace(path))
775
					continue;
776

    
777
				if (!Directory.Exists(path) && !File.Exists(path))
778
					continue;
779

    
780
				IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
781

    
782
				try
783
				{
784
					NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
785
												 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
786
												 pathPointer, IntPtr.Zero);
787
				}
788
				finally
789
				{
790
					Marshal.FreeHGlobal(pathPointer);
791
				}
792
			}
793
		}
794

    
795
		#region Event Handlers
796
		
797
		public void Handle(SelectiveSynchChanges message)
798
		{
799
			var accountName = message.Account.AccountName;
800
			PithosMonitor monitor;
801
			if (_monitors.TryGetValue(accountName, out monitor))
802
			{
803
				monitor.SetSelectivePaths(message.Uris,message.Added,message.Removed);
804

    
805
			}
806
			
807
		}
808

    
809

    
810
		private bool _pollStarted;
811

    
812
		//SMELL: Doing so much work for notifications in the shell is wrong
813
		//The notifications should be moved to their own view/viewmodel pair
814
		//and different templates should be used for different message types
815
		//This will also allow the addition of extra functionality, eg. actions
816
		//
817
		public void Handle(Notification notification)
818
		{
819
			UpdateStatus();
820

    
821
			if (!Settings.ShowDesktopNotifications)
822
				return;
823

    
824
			if (notification is PollNotification)
825
			{
826
				_pollStarted = true;
827
				return;
828
			}
829
			if (notification is CloudNotification)
830
			{
831
				if (!_pollStarted) 
832
					return;
833
				_pollStarted= false;
834
				notification.Title = "Pithos";
835
				notification.Message = "Start Synchronisation";
836
			}
837

    
838
		    var progress = notification as ProgressNotification;
839
		    if (progress != null)
840
		    {
841
		        StatusMessage = String.Format("Pithos {0}\r\n{1} {2} of {3} - {4}",
842
		                                      _fileVersion.Value.FileVersion, 
843
                                              progress.Action,
844
		                                      progress.Block/(double)progress.TotalBlocks,
845
		                                      progress.FileSize.ToByteSize(),
846
		                                      progress.FileName);
847
		        return;
848
		    }
849

    
850
			if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
851
				return;
852

    
853
			BalloonIcon icon;
854
			switch (notification.Level)
855
			{
856
				case TraceLevel.Error:
857
					icon = BalloonIcon.Error;
858
					break;
859
				case TraceLevel.Info:
860
				case TraceLevel.Verbose:
861
					icon = BalloonIcon.Info;
862
					break;
863
				case TraceLevel.Warning:
864
					icon = BalloonIcon.Warning;
865
					break;
866
				default:
867
					icon = BalloonIcon.None;
868
					break;
869
			}
870
			
871
			if (Settings.ShowDesktopNotifications)
872
			{
873
				var tv = (ShellView) GetView();
874
			    System.Action clickAction = null;
875
                if (notification is ExpirationNotification)
876
                {
877
                    clickAction = ()=>ShowPreferences("AccountTab");
878
                }
879
				var balloon=new PithosBalloon{Title=notification.Title,Message=notification.Message,Icon=icon,ClickAction=clickAction};
880
				tv.TaskbarView.ShowCustomBalloon(balloon,PopupAnimation.Fade,4000);
881
//				tv.TaskbarView.ShowBalloonTip(notification.Title, notification.Message, icon);
882
			}
883
		}
884
		#endregion
885

    
886
		public void Handle(ShowFilePropertiesEvent message)
887
		{
888
			if (message == null)
889
				throw new ArgumentNullException("message");
890
			if (String.IsNullOrWhiteSpace(message.FileName) )
891
				throw new ArgumentException("message");
892
			Contract.EndContractBlock();
893

    
894
			var fileName = message.FileName;
895
			//TODO: Display file properties for non-container folders
896
			if (File.Exists(fileName))
897
				//Retrieve the full name with exact casing. Pithos names are case sensitive				
898
				ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
899
			else if (Directory.Exists(fileName))
900
				//Retrieve the full name with exact casing. Pithos names are case sensitive
901
			{
902
				var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
903
				if (IsContainer(path))
904
					ShowContainerProperties(path);
905
				else
906
					ShowFileProperties(path);
907
			}
908
		}
909

    
910
		private bool IsContainer(string path)
911
		{
912
			var matchingFolders = from account in _accounts
913
								  from rootFolder in Directory.GetDirectories(account.AccountPath)
914
								  where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
915
								  select rootFolder;
916
			return matchingFolders.Any();
917
		}
918

    
919
		public FileStatus GetFileStatus(string localFileName)
920
		{
921
			if (String.IsNullOrWhiteSpace(localFileName))
922
				throw new ArgumentNullException("localFileName");
923
			Contract.EndContractBlock();
924
			
925
			var statusKeeper = IoC.Get<IStatusKeeper>();
926
			var status=statusKeeper.GetFileStatus(localFileName);
927
			return status;
928
		}
929
	}
930
}