Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / Shell / ShellViewModel.cs @ 759bd3c4

History | View | Annotate | Download (26.1 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
		//The Status Checker provides the current synch state
91
		//TODO: Could we remove the status checker and use events in its place?
92
		private readonly IStatusChecker _statusChecker;
93
		private readonly IEventAggregator _events;
94

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

    
97

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

    
113

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

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

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

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

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

    
146
				Settings = settings;
147

    
148
				Proxy.SetFromSettings(settings);
149

    
150
				StatusMessage = "In Synch";
151

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

    
164
			}
165
			catch (Exception exc)
166
			{
167
				Log.Error("Error while starting the ShellViewModel",exc);
168
				throw;
169
			}
170
		}
171

    
172

    
173
		protected override void OnActivate()
174
		{
175
			base.OnActivate();
176

    
177
			
178

    
179
			StartMonitoring();                    
180
		}
181

    
182

    
183

    
184
		private async void StartMonitoring()
185
		{
186
			try
187
			{
188
				var accounts = Settings.Accounts.Select(MonitorAccount);
189
				await TaskEx.WhenAll(accounts);
190
				_statusService = StatusService.Start();
191

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

    
211
		protected override void OnDeactivate(bool close)
212
		{
213
			base.OnDeactivate(close);
214
			if (close)
215
			{
216
				StatusService.Stop(_statusService);
217
				_statusService = null;
218
			}
219
		}
220

    
221
		public Task MonitorAccount(AccountSettings account)
222
		{
223
			return Task.Factory.StartNew(() =>
224
			{                                                
225
				PithosMonitor monitor;
226
				var accountName = account.AccountName;
227

    
228
				if (_monitors.TryGetValue(accountName, out monitor))
229
				{
230
					//If the account is active
231
					if (account.IsActive)
232
						//Start the monitor. It's OK to start an already started monitor,
233
						//it will just ignore the call                        
234
						StartMonitor(monitor).Wait();                        
235
					else
236
					{
237
						//If the account is inactive
238
						//Stop and remove the monitor
239
						RemoveMonitor(accountName);
240
					}
241
					return;
242
				}
243

    
244
				
245
				//Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
246
				monitor = new PithosMonitor
247
							  {
248
								  UserName = accountName,
249
								  ApiKey = account.ApiKey,                                  
250
								  StatusNotification = this,
251
								  RootPath = account.RootPath
252
							  };
253
				//PithosMonitor uses MEF so we need to resolve it
254
				IoC.BuildUp(monitor);
255

    
256
				monitor.AuthenticationUrl = account.ServerUrl;
257

    
258
				_monitors[accountName] = monitor;
259

    
260
				if (account.IsActive)
261
				{
262
					//Don't start a monitor if it doesn't have an account and ApiKey
263
					if (String.IsNullOrWhiteSpace(monitor.UserName) ||
264
						String.IsNullOrWhiteSpace(monitor.ApiKey))
265
						return;
266
					StartMonitor(monitor);
267
				}
268
			});
269
		}
270

    
271

    
272
		protected override void OnViewLoaded(object view)
273
		{
274
			UpdateStatus();
275
			var window = (Window)view;            
276
			TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
277
			base.OnViewLoaded(view);
278
		}
279

    
280

    
281
		#region Status Properties
282

    
283
		private string _statusMessage;
284
		public string StatusMessage
285
		{
286
			get { return _statusMessage; }
287
			set
288
			{
289
				_statusMessage = value;
290
				NotifyOfPropertyChange(() => StatusMessage);
291
			}
292
		}
293

    
294
		private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
295
		public ObservableConcurrentCollection<AccountInfo> Accounts
296
		{
297
			get { return _accounts; }
298
		}
299

    
300
		public bool HasAccounts
301
		{
302
			get { return _accounts.Count > 0; }
303
		}
304

    
305

    
306
		public string OpenFolderCaption
307
		{
308
			get
309
			{
310
				return (_accounts.Count == 0)
311
						? "No Accounts Defined"
312
						: "Open Pithos Folder";
313
			}
314
		}
315

    
316
		private string _pauseSyncCaption="Pause Synching";
317
		public string PauseSyncCaption
318
		{
319
			get { return _pauseSyncCaption; }
320
			set
321
			{
322
				_pauseSyncCaption = value;
323
				NotifyOfPropertyChange(() => PauseSyncCaption);
324
			}
325
		}
326

    
327
		private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
328
		public ObservableConcurrentCollection<FileEntry> RecentFiles
329
		{
330
			get { return _recentFiles; }
331
		}
332

    
333

    
334
		private string _statusIcon="../Images/Pithos.ico";
335
		public string StatusIcon
336
		{
337
			get { return _statusIcon; }
338
			set
339
			{
340
				//TODO: Ensure all status icons use the Pithos logo
341
				_statusIcon = value;
342
				NotifyOfPropertyChange(() => StatusIcon);
343
			}
344
		}
345

    
346
		#endregion
347

    
348
		#region Commands
349

    
350
		public void ShowPreferences()
351
		{
352
			Settings.Reload();
353
			var preferences = new PreferencesViewModel(_windowManager,_events, this,Settings);            
354
			_windowManager.ShowDialog(preferences);
355
			
356
		}
357

    
358
		public void AboutPithos()
359
		{
360
			var about = new AboutViewModel();
361
			_windowManager.ShowWindow(about);
362
		}
363

    
364
		public void SendFeedback()
365
		{
366
			var feedBack =  IoC.Get<FeedbackViewModel>();
367
			_windowManager.ShowWindow(feedBack);
368
		}
369

    
370
		//public PithosCommand OpenPithosFolderCommand { get; private set; }
371

    
372
		public void OpenPithosFolder()
373
		{
374
			var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
375
			if (account == null)
376
				return;
377
			Process.Start(account.RootPath);
378
		}
379

    
380
		public void OpenPithosFolder(AccountInfo account)
381
		{
382
			Process.Start(account.AccountPath);
383
		}
384

    
385
		
386
/*
387
		public void GoToSite()
388
		{            
389
			var site = Properties.Settings.Default.PithosSite;
390
			Process.Start(site);            
391
		}
392
*/
393

    
394
		public void GoToSite(AccountInfo account)
395
		{
396
			/*var site = String.Format("{0}/ui/?token={1}&user={2}",
397
				account.SiteUri,account.Token,
398
				account.UserName);*/
399
			Process.Start(account.SiteUri);
400
		}
401

    
402
		public void ShowFileProperties()
403
		{
404
			var account = Settings.Accounts.First(acc => acc.IsActive);            
405
			var dir = new DirectoryInfo(account.RootPath + @"\pithos");
406
			var files=dir.GetFiles();
407
			var r=new Random();
408
			var idx=r.Next(0, files.Length);
409
			ShowFileProperties(files[idx].FullName);            
410
		}
411

    
412
		public void ShowFileProperties(string filePath)
413
		{
414
			if (String.IsNullOrWhiteSpace(filePath))
415
				throw new ArgumentNullException("filePath");
416
			if (!File.Exists(filePath) && !Directory.Exists(filePath))
417
				throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
418
			Contract.EndContractBlock();
419

    
420
			var pair=(from monitor in  Monitors
421
							   where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
422
								   select monitor).FirstOrDefault();
423
			var accountMonitor = pair.Value;
424

    
425
			if (accountMonitor == null)
426
				return;
427

    
428
			var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
429

    
430
			
431

    
432
			var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
433
			_windowManager.ShowWindow(fileProperties);
434
		} 
435
		
436
		public void ShowContainerProperties()
437
		{
438
			var account = Settings.Accounts.First(acc => acc.IsActive);            
439
			var dir = new DirectoryInfo(account.RootPath);
440
			var fullName = (from folder in dir.EnumerateDirectories()
441
							where (folder.Attributes & FileAttributes.Hidden) == 0
442
							select folder.FullName).First();
443
			ShowContainerProperties(fullName);            
444
		}
445

    
446
		public void ShowContainerProperties(string filePath)
447
		{
448
			if (String.IsNullOrWhiteSpace(filePath))
449
				throw new ArgumentNullException("filePath");
450
			if (!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
			var info = accountMonitor.GetContainerInfo(filePath);
459

    
460
			
461

    
462
			var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
463
			_windowManager.ShowWindow(containerProperties);
464
		}
465

    
466
		public void SynchNow()
467
		{
468
			var agent = IoC.Get<PollAgent>();
469
			agent.SynchNow();
470
		}
471

    
472
		public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
473
		{
474
			if (currentInfo==null)
475
				throw new ArgumentNullException("currentInfo");
476
			Contract.EndContractBlock();
477

    
478
			var monitor = Monitors[currentInfo.Account];
479
			var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
480
			return newInfo;
481
		}
482

    
483
		public ContainerInfo RefreshContainerInfo(ContainerInfo container)
484
		{
485
			if (container == null)
486
				throw new ArgumentNullException("container");
487
			Contract.EndContractBlock();
488

    
489
			var monitor = Monitors[container.Account];
490
			var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
491
			return newInfo;
492
		}
493

    
494

    
495
		public void ToggleSynching()
496
		{
497
			bool isPaused=false;
498
			foreach (var pair in Monitors)
499
			{
500
				var monitor = pair.Value;
501
				monitor.Pause = !monitor.Pause;
502
				isPaused = monitor.Pause;
503
			}
504

    
505
			PauseSyncCaption = isPaused ? "Resume syncing" : "Pause syncing";
506
			var iconKey = isPaused? "TraySyncPaused" : "TrayInSynch";
507
			StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
508
		}
509

    
510
		public void ExitPithos()
511
		{
512
			foreach (var pair in Monitors)
513
			{
514
				var monitor = pair.Value;
515
				monitor.Stop();
516
			}
517

    
518
			((Window)GetView()).Close();
519
		}
520
		#endregion
521

    
522

    
523
		private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
524
			{
525
				new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
526
				new StatusInfo(PithosStatus.Syncing, "Syncing Files", "TraySynching"),
527
				new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
528
			}.ToDictionary(s => s.Status);
529

    
530
		readonly IWindowManager _windowManager;
531
		
532

    
533
		///<summary>
534
		/// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat		
535
		///</summary>
536
		public void UpdateStatus()
537
		{
538
			var pithosStatus = _statusChecker.GetPithosStatus();
539

    
540
			if (_iconNames.ContainsKey(pithosStatus))
541
			{
542
				var info = _iconNames[pithosStatus];
543
				StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
544

    
545

    
546

    
547
				StatusMessage = String.Format("Pithos {0}\r\n{1}", _fileVersion.Value.FileVersion,info.StatusText);
548
			}
549
			
550
			//_events.Publish(new Notification { Title = "Start", Message = "Start Monitoring", Level = TraceLevel.Info});
551
		}
552

    
553

    
554
	   
555
		private Task StartMonitor(PithosMonitor monitor,int retries=0)
556
		{
557
			return Task.Factory.StartNew(() =>
558
			{
559
				using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
560
				{
561
					try
562
					{
563
						Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
564

    
565
						monitor.Start();
566
					}
567
					catch (WebException exc)
568
					{
569
						if (AbandonRetry(monitor, retries))
570
							return;
571

    
572
						HttpStatusCode statusCode =HttpStatusCode.OK;
573
						var response = exc.Response as HttpWebResponse;
574
						if(response!=null)
575
							statusCode = response.StatusCode;
576

    
577
						switch (statusCode)
578
						{
579
							case HttpStatusCode.Unauthorized:
580
								var message = String.Format("API Key Expired for {0}. Starting Renewal",
581
															monitor.UserName);
582
								Log.Error(message, exc);
583
								TryAuthorize(monitor, retries).Wait();
584
								break;
585
							case HttpStatusCode.ProxyAuthenticationRequired:
586
								TryAuthenticateProxy(monitor,retries);
587
								break;
588
							default:
589
								TryLater(monitor, exc, retries);
590
								break;
591
						}
592
					}
593
					catch (Exception exc)
594
					{
595
						if (AbandonRetry(monitor, retries)) 
596
							return;
597

    
598
						TryLater(monitor,exc,retries);
599
					}
600
				}
601
			});
602
		}
603

    
604
		private void TryAuthenticateProxy(PithosMonitor monitor,int retries)
605
		{
606
			Execute.OnUIThread(() =>
607
								   {                                       
608
									   var proxyAccount = IoC.Get<ProxyAccountViewModel>();
609
										proxyAccount.Settings = this.Settings;
610
									   if (true != _windowManager.ShowDialog(proxyAccount)) 
611
										   return;
612
									   StartMonitor(monitor, retries);
613
									   NotifyOfPropertyChange(() => Accounts);
614
								   });
615
		}
616

    
617
		private bool AbandonRetry(PithosMonitor monitor, int retries)
618
		{
619
			if (retries > 1)
620
			{
621
				var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
622
											monitor.UserName);
623
				_events.Publish(new Notification
624
									{Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
625
				return true;
626
			}
627
			return false;
628
		}
629

    
630

    
631
		private async Task TryAuthorize(PithosMonitor monitor,int retries)
632
		{
633
			_events.Publish(new Notification { Title = "Authorization failed", Message = "Your API Key has probably expired. You will be directed to a page where you can renew it", Level = TraceLevel.Error });
634

    
635
			try
636
			{
637

    
638
				var credentials = await PithosAccount.RetrieveCredentials(Settings.PithosLoginUrl);
639

    
640
				var account = Settings.Accounts.First(act => act.AccountName == credentials.UserName);
641
				account.ApiKey = credentials.Password;
642
				monitor.ApiKey = credentials.Password;
643
				Settings.Save();
644
				await TaskEx.Delay(10000);
645
				StartMonitor(monitor, retries + 1);
646
				NotifyOfPropertyChange(()=>Accounts);
647
			}
648
			catch (AggregateException exc)
649
			{
650
				string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
651
				Log.Error(message, exc.InnerException);
652
				_events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
653
			}
654
			catch (Exception exc)
655
			{
656
				string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
657
				Log.Error(message, exc);
658
				_events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
659
			}
660

    
661
		}
662

    
663
		private static bool IsUnauthorized(WebException exc)
664
		{
665
			if (exc==null)
666
				throw new ArgumentNullException("exc");
667
			Contract.EndContractBlock();
668

    
669
			var response = exc.Response as HttpWebResponse;
670
			if (response == null)
671
				return false;
672
			return (response.StatusCode == HttpStatusCode.Unauthorized);
673
		}
674

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

    
684

    
685
		public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
686
		{
687
			StatusMessage = status;
688
			
689
			_events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
690
		}
691

    
692
		public void NotifyChangedFile(string filePath)
693
		{
694
			var entry = new FileEntry {FullPath=filePath};
695
			IProducerConsumerCollection<FileEntry> files=RecentFiles;
696
			FileEntry popped;
697
			while (files.Count > 5)
698
				files.TryTake(out popped);
699
			files.TryAdd(entry);
700
		}
701

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

    
711
			if (Accounts.All(item => item.UserName != account.UserName))
712
				Accounts.TryAdd(account);
713

    
714
		}
715

    
716
		public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
717
		{
718
			if (conflictFiles == null)
719
				return;
720
			if (!conflictFiles.Any())
721
				return;
722

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

    
727
		}
728

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

    
736
			StatusMessage = message;
737

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

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

    
746

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

    
752
			var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName);
753
			_accounts.TryRemove(accountInfo);
754

    
755
			PithosMonitor monitor;
756
			if (Monitors.TryRemove(accountName, out monitor))
757
			{
758
				monitor.Stop();
759
			}
760
		}
761

    
762
		public void RefreshOverlays()
763
		{
764
			foreach (var pair in Monitors)
765
			{
766
				var monitor = pair.Value;
767

    
768
				var path = monitor.RootPath;
769

    
770
				if (String.IsNullOrWhiteSpace(path))
771
					continue;
772

    
773
				if (!Directory.Exists(path) && !File.Exists(path))
774
					continue;
775

    
776
				IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
777

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

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

    
801
			}
802
			
803
		}
804

    
805

    
806
		private bool _pollStarted = false;
807

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

    
817
			if (!Settings.ShowDesktopNotifications)
818
				return;
819

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

    
834
			if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
835
				return;
836

    
837
			BalloonIcon icon;
838
			switch (notification.Level)
839
			{
840
				case TraceLevel.Error:
841
					icon = BalloonIcon.Error;
842
					break;
843
				case TraceLevel.Info:
844
				case TraceLevel.Verbose:
845
					icon = BalloonIcon.Info;
846
					break;
847
				case TraceLevel.Warning:
848
					icon = BalloonIcon.Warning;
849
					break;
850
				default:
851
					icon = BalloonIcon.None;
852
					break;
853
			}
854
			
855
			if (Settings.ShowDesktopNotifications)
856
			{
857
				var tv = (ShellView) GetView();                
858
				var balloon=new PithosBalloon{Title=notification.Title,Message=notification.Message,Icon=icon};
859
				tv.TaskbarView.ShowCustomBalloon(balloon,PopupAnimation.Fade,4000);
860
//				tv.TaskbarView.ShowBalloonTip(notification.Title, notification.Message, icon);
861
			}
862
		}
863
		#endregion
864

    
865
		public void Handle(ShowFilePropertiesEvent message)
866
		{
867
			if (message == null)
868
				throw new ArgumentNullException("message");
869
			if (String.IsNullOrWhiteSpace(message.FileName) )
870
				throw new ArgumentException("message");
871
			Contract.EndContractBlock();
872

    
873
			var fileName = message.FileName;
874
			//TODO: Display file properties for non-container folders
875
			if (File.Exists(fileName))
876
				//Retrieve the full name with exact casing. Pithos names are case sensitive				
877
				ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
878
			else if (Directory.Exists(fileName))
879
				//Retrieve the full name with exact casing. Pithos names are case sensitive
880
			{
881
				var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
882
				if (IsContainer(path))
883
					ShowContainerProperties(path);
884
				else
885
					ShowFileProperties(path);
886
			}
887
		}
888

    
889
		private bool IsContainer(string path)
890
		{
891
			var matchingFolders = from account in _accounts
892
								  from rootFolder in Directory.GetDirectories(account.AccountPath)
893
								  where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
894
								  select rootFolder;
895
			return matchingFolders.Any();
896
		}
897

    
898
		public FileStatus GetFileStatus(string localFileName)
899
		{
900
			if (String.IsNullOrWhiteSpace(localFileName))
901
				throw new ArgumentNullException("localFileName");
902
			Contract.EndContractBlock();
903
			
904
			var statusKeeper = IoC.Get<IStatusKeeper>();
905
			var status=statusKeeper.GetFileStatus(localFileName);
906
			return status;
907
		}
908
	}
909
}