Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / Shell / ShellViewModel.cs @ 1e26eceb

History | View | Annotate | Download (26.6 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.Properties;
59
using Pithos.Client.WPF.SelectiveSynch;
60
using Pithos.Client.WPF.Services;
61
using Pithos.Client.WPF.Shell;
62
using Pithos.Core;
63
using Pithos.Core.Agents;
64
using Pithos.Interfaces;
65
using System;
66
using System.Collections.Generic;
67
using System.Linq;
68
using Pithos.Network;
69
using StatusService = Pithos.Client.WPF.Services.StatusService;
70

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

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

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

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

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

    
147
				Settings = settings;
148

    
149
				Proxy.SetFromSettings(settings);
150

    
151
				StatusMessage = "In Synch";
152

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

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

    
173

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

    
178
			
179

    
180
			StartMonitoring();                    
181
		}
182

    
183

    
184

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

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

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

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

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

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

    
257
				monitor.AuthenticationUrl = account.ServerUrl;
258

    
259
				_monitors[accountName] = monitor;
260

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

    
272

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

    
281

    
282
		#region Status Properties
283

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

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

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

    
306

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

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

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

    
334

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

    
347
		#endregion
348

    
349
		#region Commands
350

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

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

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

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

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

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

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

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

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

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

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

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

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

    
431
			
432

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

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

    
461
			
462

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

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

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

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

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

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

    
495

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

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

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

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

    
523

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

    
531
		readonly IWindowManager _windowManager;
532
		
533

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

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

    
546

    
547

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

    
554

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

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

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

    
578
						switch (statusCode)
579
						{
580
							case HttpStatusCode.Unauthorized:
581
								var message = String.Format("API Key Expired for {0}. Starting Renewal",
582
															monitor.UserName);
583
								Log.Error(message, exc);
584
						        var account = Settings.Accounts.Find(acc => acc.AccountName == monitor.UserName);                                
585
						        account.IsExpired = true;
586
                                Notify(new ExpirationNotification(account));
587
								//TryAuthorize(monitor.UserName, retries).Wait();
588
								break;
589
							case HttpStatusCode.ProxyAuthenticationRequired:
590
								TryAuthenticateProxy(monitor,retries);
591
								break;
592
							default:
593
								TryLater(monitor, exc, retries);
594
								break;
595
						}
596
					}
597
					catch (Exception exc)
598
					{
599
						if (AbandonRetry(monitor, retries)) 
600
							return;
601

    
602
						TryLater(monitor,exc,retries);
603
					}
604
				}
605
			});
606
		}
607

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

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

    
634

    
635
		public async Task TryAuthorize(string userName, int retries)
636
		{
637
			_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 });
638

    
639
			try
640
			{
641

    
642
				var credentials = await PithosAccount.RetrieveCredentials(Settings.PithosLoginUrl);
643

    
644
				var account = Settings.Accounts.First(act => act.AccountName == credentials.UserName);
645
                //The server may return credentials for a different account
646
			    var monitor = _monitors[account.AccountName];
647
				account.ApiKey = credentials.Password;
648
                monitor.ApiKey = credentials.Password;
649
			    account.IsExpired = false;
650
				Settings.Save();
651
				TaskEx.Delay(10000).ContinueWith(_=>
652
                            StartMonitor(monitor, retries + 1));
653
				NotifyOfPropertyChange(()=>Accounts);
654
			}
655
			catch (AggregateException exc)
656
			{
657
				string message = String.Format("API Key retrieval for {0} failed", userName);
658
				Log.Error(message, exc.InnerException);
659
				_events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
660
			}
661
			catch (Exception exc)
662
			{
663
				string message = String.Format("API Key retrieval for {0} failed", userName);
664
				Log.Error(message, exc);
665
				_events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
666
			}
667

    
668
		}
669

    
670
		private static bool IsUnauthorized(WebException exc)
671
		{
672
			if (exc==null)
673
				throw new ArgumentNullException("exc");
674
			Contract.EndContractBlock();
675

    
676
			var response = exc.Response as HttpWebResponse;
677
			if (response == null)
678
				return false;
679
			return (response.StatusCode == HttpStatusCode.Unauthorized);
680
		}
681

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

    
691

    
692
		public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
693
		{
694
			StatusMessage = status;
695
			
696
			_events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
697
		}
698

    
699
		public void NotifyChangedFile(string filePath)
700
		{
701
			var entry = new FileEntry {FullPath=filePath};
702
			IProducerConsumerCollection<FileEntry> files=RecentFiles;
703
			FileEntry popped;
704
			while (files.Count > 5)
705
				files.TryTake(out popped);
706
			files.TryAdd(entry);
707
		}
708

    
709
		public void NotifyAccount(AccountInfo account)
710
		{
711
			if (account== null)
712
				return;
713
			//TODO: What happens to an existing account whose Token has changed?
714
			account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
715
				account.SiteUri, Uri.EscapeDataString(account.Token),
716
				Uri.EscapeDataString(account.UserName));
717

    
718
			if (Accounts.All(item => item.UserName != account.UserName))
719
				Accounts.TryAdd(account);
720

    
721
		}
722

    
723
		public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
724
		{
725
			if (conflictFiles == null)
726
				return;
727
			if (!conflictFiles.Any())
728
				return;
729

    
730
			UpdateStatus();
731
			//TODO: Create a more specific message. For now, just show a warning
732
			NotifyForFiles(conflictFiles,message,TraceLevel.Warning);
733

    
734
		}
735

    
736
		public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info)
737
		{
738
			if (files == null)
739
				return;
740
			if (!files.Any())
741
				return;
742

    
743
			StatusMessage = message;
744

    
745
			_events.Publish(new Notification { Title = "Pithos", Message = message, Level = level});
746
		}
747

    
748
		public void Notify(Notification notification)
749
		{
750
			_events.Publish(notification);
751
		}
752

    
753

    
754
		public void RemoveMonitor(string accountName)
755
		{
756
			if (String.IsNullOrWhiteSpace(accountName))
757
				return;
758

    
759
			var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName);
760
			_accounts.TryRemove(accountInfo);
761

    
762
			PithosMonitor monitor;
763
			if (Monitors.TryRemove(accountName, out monitor))
764
			{
765
				monitor.Stop();
766
			}
767
		}
768

    
769
		public void RefreshOverlays()
770
		{
771
			foreach (var pair in Monitors)
772
			{
773
				var monitor = pair.Value;
774

    
775
				var path = monitor.RootPath;
776

    
777
				if (String.IsNullOrWhiteSpace(path))
778
					continue;
779

    
780
				if (!Directory.Exists(path) && !File.Exists(path))
781
					continue;
782

    
783
				IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
784

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

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

    
808
			}
809
			
810
		}
811

    
812

    
813
		private bool _pollStarted = false;
814

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

    
824
			if (!Settings.ShowDesktopNotifications)
825
				return;
826

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

    
841
			if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
842
				return;
843

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

    
872
		public void Handle(ShowFilePropertiesEvent message)
873
		{
874
			if (message == null)
875
				throw new ArgumentNullException("message");
876
			if (String.IsNullOrWhiteSpace(message.FileName) )
877
				throw new ArgumentException("message");
878
			Contract.EndContractBlock();
879

    
880
			var fileName = message.FileName;
881
			//TODO: Display file properties for non-container folders
882
			if (File.Exists(fileName))
883
				//Retrieve the full name with exact casing. Pithos names are case sensitive				
884
				ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
885
			else if (Directory.Exists(fileName))
886
				//Retrieve the full name with exact casing. Pithos names are case sensitive
887
			{
888
				var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
889
				if (IsContainer(path))
890
					ShowContainerProperties(path);
891
				else
892
					ShowFileProperties(path);
893
			}
894
		}
895

    
896
		private bool IsContainer(string path)
897
		{
898
			var matchingFolders = from account in _accounts
899
								  from rootFolder in Directory.GetDirectories(account.AccountPath)
900
								  where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
901
								  select rootFolder;
902
			return matchingFolders.Any();
903
		}
904

    
905
		public FileStatus GetFileStatus(string localFileName)
906
		{
907
			if (String.IsNullOrWhiteSpace(localFileName))
908
				throw new ArgumentNullException("localFileName");
909
			Contract.EndContractBlock();
910
			
911
			var statusKeeper = IoC.Get<IStatusKeeper>();
912
			var status=statusKeeper.GetFileStatus(localFileName);
913
			return status;
914
		}
915
	}
916
}