Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / Shell / ShellViewModel.cs @ 6bcdd8e2

History | View | Annotate | Download (27.4 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
			Process.Start(account.SiteUri);
413
		}
414

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

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

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

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

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

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

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

    
464
			
465

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

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

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

    
494
			
495

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

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

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

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

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

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

    
527

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

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

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

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

    
555

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

    
563
		readonly IWindowManager _windowManager;
564
		
565

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

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

    
578

    
579

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

    
586

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

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

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

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

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

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

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

    
666

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

    
676

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

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

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

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

    
709
		}
710

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

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

    
724
		}
725

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

    
733
			StatusMessage = message;
734

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

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

    
743

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

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

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

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

    
771
				var path = monitor.RootPath;
772

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

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

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

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

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

    
804
			}
805
			
806
		}
807

    
808

    
809
		private bool _pollStarted;
810

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

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

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

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

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

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

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

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

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

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