Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / Shell / ShellViewModel.cs @ 70e0b702

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

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

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

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

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

    
99

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

    
115

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

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

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

    
128
	    private readonly PollAgent _pollAgent;
129

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

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

    
150
			    _pollAgent = pollAgent;
151
				Settings = settings;
152

    
153
				Proxy.SetFromSettings(settings);
154

    
155
				StatusMessage = "In Synch";
156

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

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

    
176
		}
177

    
178

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

    
183
            _sparkle = new Sparkle(Settings.UpdateUrl);
184
            _sparkle.updateDetected += OnUpgradeDetected;
185
            _sparkle.ShowDiagnosticWindow = Settings.UpdateDiagnostics;
186

    
187
            //Must delay opening the upgrade window
188
            //to avoid Windows Messages sent by the TaskbarIcon
189
            TaskEx.Delay(5000).ContinueWith(_=>
190
                Execute.OnUIThread(()=> _sparkle.StartLoop(true,Settings.UpdateForceCheck,Settings.UpdateCheckInterval)));
191

    
192

    
193
			StartMonitoring();                    
194
		}
195

    
196
	    private void OnUpgradeDetected(object sender, UpdateDetectedEventArgs e)
197
	    {
198
	        Log.InfoFormat("Update detected {0}",e.LatestVersion);
199
	    }
200

    
201
        public void CheckForUpgrade()
202
        {
203
            Log.Error("Test Error message");
204
            _sparkle.StopLoop();
205
            _sparkle.Dispose();
206
            _sparkle=new Sparkle(Settings.UpdateUrl);
207
            _sparkle.StartLoop(true,true,Settings.UpdateCheckInterval);
208
        }
209

    
210
	    private async void StartMonitoring()
211
		{
212
			try
213
			{
214
				var accounts = Settings.Accounts.Select(MonitorAccount);
215
				await TaskEx.WhenAll(accounts);
216
				_statusService = StatusService.Start();
217

    
218
/*
219
				foreach (var account in Settings.Accounts)
220
				{
221
					await MonitorAccount(account);
222
				}
223
*/
224
				
225
			}
226
			catch (AggregateException exc)
227
			{
228
				exc.Handle(e =>
229
				{
230
					Log.Error("Error while starting monitoring", e);
231
					return true;
232
				});
233
				throw;
234
			}
235
		}
236

    
237
		protected override void OnDeactivate(bool close)
238
		{
239
			base.OnDeactivate(close);
240
			if (close)
241
			{
242
				StatusService.Stop(_statusService);
243
				_statusService = null;
244
			}
245
		}
246

    
247
		public Task MonitorAccount(AccountSettings account)
248
		{
249
			return Task.Factory.StartNew(() =>
250
			{                                                
251
				PithosMonitor monitor;
252
				var accountName = account.AccountName;
253

    
254
				if (_monitors.TryGetValue(accountName, out monitor))
255
				{
256
					//If the account is active
257
                    if (account.IsActive)
258
                    {
259
                        //The Api Key may have changed throuth the Preferences dialog
260
                        monitor.ApiKey = account.ApiKey;
261
						Debug.Assert(monitor.StatusNotification == this,"An existing monitor should already have a StatusNotification service object");
262
                        monitor.RootPath = account.RootPath;
263
                        //Start the monitor. It's OK to start an already started monitor,
264
                        //it will just ignore the call                        
265
                        StartMonitor(monitor).Wait();
266
                    }
267
                    else
268
                    {
269
                        //If the account is inactive
270
                        //Stop and remove the monitor
271
                        RemoveMonitor(accountName);
272
                    }
273
					return;
274
				}
275

    
276
				
277
				//Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
278
				monitor = new PithosMonitor
279
							  {
280
								  UserName = accountName,
281
								  ApiKey = account.ApiKey,                                  
282
								  StatusNotification = this,
283
								  RootPath = account.RootPath
284
							  };
285
				//PithosMonitor uses MEF so we need to resolve it
286
				IoC.BuildUp(monitor);
287

    
288
				monitor.AuthenticationUrl = account.ServerUrl;
289

    
290
				_monitors[accountName] = monitor;
291

    
292
				if (account.IsActive)
293
				{
294
					//Don't start a monitor if it doesn't have an account and ApiKey
295
					if (String.IsNullOrWhiteSpace(monitor.UserName) ||
296
						String.IsNullOrWhiteSpace(monitor.ApiKey))
297
						return;
298
					StartMonitor(monitor);
299
				}
300
			});
301
		}
302

    
303

    
304
		protected override void OnViewLoaded(object view)
305
		{
306
			UpdateStatus();
307
			var window = (Window)view;            
308
			TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
309
			base.OnViewLoaded(view);
310
		}
311

    
312

    
313
		#region Status Properties
314

    
315
		private string _statusMessage;
316
		public string StatusMessage
317
		{
318
			get { return _statusMessage; }
319
			set
320
			{
321
				_statusMessage = value;
322
				NotifyOfPropertyChange(() => StatusMessage);
323
			}
324
		}
325

    
326
		private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
327
		public ObservableConcurrentCollection<AccountInfo> Accounts
328
		{
329
			get { return _accounts; }
330
		}
331

    
332
		public bool HasAccounts
333
		{
334
			get { return _accounts.Count > 0; }
335
		}
336

    
337

    
338
		public string OpenFolderCaption
339
		{
340
			get
341
			{
342
				return (_accounts.Count == 0)
343
						? "No Accounts Defined"
344
						: "Open Pithos Folder";
345
			}
346
		}
347

    
348
		private string _pauseSyncCaption="Pause Synching";
349
		public string PauseSyncCaption
350
		{
351
			get { return _pauseSyncCaption; }
352
			set
353
			{
354
				_pauseSyncCaption = value;
355
				NotifyOfPropertyChange(() => PauseSyncCaption);
356
			}
357
		}
358

    
359
		private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
360
		public ObservableConcurrentCollection<FileEntry> RecentFiles
361
		{
362
			get { return _recentFiles; }
363
		}
364

    
365

    
366
		private string _statusIcon="../Images/Pithos.ico";
367
		public string StatusIcon
368
		{
369
			get { return _statusIcon; }
370
			set
371
			{
372
				//TODO: Ensure all status icons use the Pithos logo
373
				_statusIcon = value;
374
				NotifyOfPropertyChange(() => StatusIcon);
375
			}
376
		}
377

    
378
		#endregion
379

    
380
		#region Commands
381

    
382
        public void ShowPreferences()
383
        {
384
            ShowPreferences(null);
385
        }
386

    
387
		public void ShowPreferences(string currentTab)
388
		{
389
			//Settings.Reload();
390
		    var preferences = new PreferencesViewModel(_windowManager, _events, this, Settings,currentTab);
391
		    _windowManager.ShowDialog(preferences);
392
			
393
		}
394

    
395
		public void AboutPithos()
396
		{
397
			var about = new AboutViewModel();
398
			_windowManager.ShowWindow(about);
399
		}
400

    
401
		public void SendFeedback()
402
		{
403
			var feedBack =  IoC.Get<FeedbackViewModel>();
404
			_windowManager.ShowWindow(feedBack);
405
		}
406

    
407
		//public PithosCommand OpenPithosFolderCommand { get; private set; }
408

    
409
		public void OpenPithosFolder()
410
		{
411
			var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
412
			if (account == null)
413
				return;
414
			Process.Start(account.RootPath);
415
		}
416

    
417
		public void OpenPithosFolder(AccountInfo account)
418
		{
419
			Process.Start(account.AccountPath);
420
		}
421

    
422
		
423
/*
424
		public void GoToSite()
425
		{            
426
			var site = Properties.Settings.Default.PithosSite;
427
			Process.Start(site);            
428
		}
429
*/
430

    
431
		public void GoToSite(AccountInfo account)
432
		{
433
		    var uri = account.SiteUri.Replace("http://","https://");            
434
		    Process.Start(uri);
435
		}
436

    
437
        public void ShowMiniStatus()
438
        {
439
            var model=IoC.Get<MiniStatusViewModel>();
440
            model.Shell = this;
441
            _windowManager.ShowWindow(model);
442
        }
443

    
444
	    /// <summary>
445
        /// Open an explorer window to the target path's directory
446
        /// and select the file
447
        /// </summary>
448
        /// <param name="entry"></param>
449
        public void GoToFile(FileEntry entry)
450
        {
451
            var fullPath = entry.FullPath;
452
            if (!File.Exists(fullPath) && !Directory.Exists(fullPath))
453
                return;
454
            Process.Start("explorer.exe","/select, " + fullPath);
455
        }
456

    
457
        public void OpenLogPath()
458
        {
459
            var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
460
            var pithosDataPath = Path.Combine(appDataPath, "GRNET");
461

    
462
            Process.Start(pithosDataPath);
463
        }
464
        
465
        public void ShowFileProperties()
466
		{
467
			var account = Settings.Accounts.First(acc => acc.IsActive);            
468
			var dir = new DirectoryInfo(account.RootPath + @"\pithos");
469
			var files=dir.GetFiles();
470
			var r=new Random();
471
			var idx=r.Next(0, files.Length);
472
			ShowFileProperties(files[idx].FullName);            
473
		}
474

    
475
		public void ShowFileProperties(string filePath)
476
		{
477
			if (String.IsNullOrWhiteSpace(filePath))
478
				throw new ArgumentNullException("filePath");
479
			if (!File.Exists(filePath) && !Directory.Exists(filePath))
480
				throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
481
			Contract.EndContractBlock();
482

    
483
			var pair=(from monitor in  Monitors
484
							   where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
485
								   select monitor).FirstOrDefault();
486
			var accountMonitor = pair.Value;
487

    
488
			if (accountMonitor == null)
489
				return;
490

    
491
			var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
492

    
493
			
494

    
495
			var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
496
			_windowManager.ShowWindow(fileProperties);
497
		} 
498
		
499
		public void ShowContainerProperties()
500
		{
501
			var account = Settings.Accounts.First(acc => acc.IsActive);            
502
			var dir = new DirectoryInfo(account.RootPath);
503
			var fullName = (from folder in dir.EnumerateDirectories()
504
							where (folder.Attributes & FileAttributes.Hidden) == 0
505
							select folder.FullName).First();
506
			ShowContainerProperties(fullName);            
507
		}
508

    
509
		public void ShowContainerProperties(string filePath)
510
		{
511
			if (String.IsNullOrWhiteSpace(filePath))
512
				throw new ArgumentNullException("filePath");
513
			if (!Directory.Exists(filePath))
514
				throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
515
			Contract.EndContractBlock();
516

    
517
			var pair=(from monitor in  Monitors
518
							   where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
519
								   select monitor).FirstOrDefault();
520
			var accountMonitor = pair.Value;            
521
			var info = accountMonitor.GetContainerInfo(filePath);
522

    
523
			
524

    
525
			var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
526
			_windowManager.ShowWindow(containerProperties);
527
		}
528

    
529
		public void SynchNow()
530
		{
531
			_pollAgent.SynchNow();
532
		}
533

    
534
		public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
535
		{
536
			if (currentInfo==null)
537
				throw new ArgumentNullException("currentInfo");
538
			Contract.EndContractBlock();
539

    
540
			var monitor = Monitors[currentInfo.Account];
541
			var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
542
			return newInfo;
543
		}
544

    
545
		public ContainerInfo RefreshContainerInfo(ContainerInfo container)
546
		{
547
			if (container == null)
548
				throw new ArgumentNullException("container");
549
			Contract.EndContractBlock();
550

    
551
			var monitor = Monitors[container.Account];
552
			var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
553
			return newInfo;
554
		}
555

    
556

    
557
		public void ToggleSynching()
558
		{
559
			bool isPaused=false;
560
			foreach (var pair in Monitors)
561
			{
562
				var monitor = pair.Value;
563
				monitor.Pause = !monitor.Pause;
564
				isPaused = monitor.Pause;
565
			}
566
                        
567

    
568
			PauseSyncCaption = isPaused ? "Resume syncing" : "Pause syncing";
569
			var iconKey = isPaused? "TraySyncPaused" : "TrayInSynch";
570
			StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
571
		}
572

    
573
		public void ExitPithos()
574
		{
575
			foreach (var pair in Monitors)
576
			{
577
				var monitor = pair.Value;
578
				monitor.Stop();
579
			}
580

    
581
			((Window)GetView()).Close();
582
		}
583
		#endregion
584

    
585

    
586
		private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
587
			{
588
				new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
589
				new StatusInfo(PithosStatus.PollSyncing, "Polling Files", "TraySynching"),
590
                new StatusInfo(PithosStatus.LocalSyncing, "Syncing Files", "TraySynching"),
591
				new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
592
			}.ToDictionary(s => s.Status);
593

    
594
		readonly IWindowManager _windowManager;
595
		
596
        //private int _syncCount=0;
597

    
598

    
599
        private PithosStatus _pithosStatus = PithosStatus.Disconnected;
600

    
601
        public void SetPithosStatus(PithosStatus status)
602
        {
603
            if (_pithosStatus == PithosStatus.LocalSyncing && status == PithosStatus.PollComplete)
604
                return;
605
            if (_pithosStatus == PithosStatus.PollSyncing && status == PithosStatus.LocalComplete)
606
                return;
607
            if (status == PithosStatus.LocalComplete || status == PithosStatus.PollComplete)
608
                _pithosStatus = PithosStatus.InSynch;
609
            else
610
                _pithosStatus = status;
611
            UpdateStatus();
612
        }
613

    
614
        public void SetPithosStatus(PithosStatus status,string message)
615
        {
616
            StatusMessage = message;
617
            SetPithosStatus(status);
618
        }
619

    
620

    
621

    
622
		///<summary>
623
		/// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat		
624
		///</summary>
625
		public void UpdateStatus()
626
		{
627

    
628
			if (_iconNames.ContainsKey(_pithosStatus))
629
			{
630
				var info = _iconNames[_pithosStatus];
631
				StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
632
			}
633

    
634
            if (_pithosStatus == PithosStatus.InSynch)
635
                StatusMessage = "All files up to date";
636
		}
637

    
638

    
639
	   
640
		private Task StartMonitor(PithosMonitor monitor,int retries=0)
641
		{
642
			return Task.Factory.StartNew(() =>
643
			{
644
				using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
645
				{
646
					try
647
					{
648
						Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
649

    
650
						monitor.Start();
651
					}
652
					catch (WebException exc)
653
					{
654
						if (AbandonRetry(monitor, retries))
655
							return;
656

    
657
						HttpStatusCode statusCode =HttpStatusCode.OK;
658
						var response = exc.Response as HttpWebResponse;
659
						if(response!=null)
660
							statusCode = response.StatusCode;
661

    
662
						switch (statusCode)
663
						{
664
							case HttpStatusCode.Unauthorized:
665
								var message = String.Format("API Key Expired for {0}. Starting Renewal",
666
															monitor.UserName);
667
								Log.Error(message, exc);
668
						        var account = Settings.Accounts.Find(acc => acc.AccountName == monitor.UserName);                                
669
						        account.IsExpired = true;
670
                                Notify(new ExpirationNotification(account));
671
								//TryAuthorize(monitor.UserName, retries).Wait();
672
								break;
673
							case HttpStatusCode.ProxyAuthenticationRequired:
674
								TryAuthenticateProxy(monitor,retries);
675
								break;
676
							default:
677
								TryLater(monitor, exc, retries);
678
								break;
679
						}
680
					}
681
					catch (Exception exc)
682
					{
683
						if (AbandonRetry(monitor, retries)) 
684
							return;
685

    
686
						TryLater(monitor,exc,retries);
687
					}
688
				}
689
			});
690
		}
691

    
692
		private void TryAuthenticateProxy(PithosMonitor monitor,int retries)
693
		{
694
			Execute.OnUIThread(() =>
695
								   {                                       
696
									   var proxyAccount = IoC.Get<ProxyAccountViewModel>();
697
										proxyAccount.Settings = Settings;
698
									   if (true != _windowManager.ShowDialog(proxyAccount)) 
699
										   return;
700
									   StartMonitor(monitor, retries);
701
									   NotifyOfPropertyChange(() => Accounts);
702
								   });
703
		}
704

    
705
		private bool AbandonRetry(PithosMonitor monitor, int retries)
706
		{
707
			if (retries > 1)
708
			{
709
				var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
710
											monitor.UserName);
711
				_events.Publish(new Notification
712
									{Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
713
				return true;
714
			}
715
			return false;
716
		}
717

    
718

    
719
	    private void TryLater(PithosMonitor monitor, Exception exc,int retries)
720
		{
721
			var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
722
			Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
723
			_events.Publish(new Notification
724
								{Title = "Error", Message = message, Level = TraceLevel.Error});
725
			Log.Error(message, exc);
726
		}
727

    
728

    
729
		public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
730
		{
731
			StatusMessage = status;
732
			
733
			_events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
734
		}
735

    
736
		public void NotifyChangedFile(string filePath)
737
		{
738
            if (RecentFiles.Any(e => e.FullPath == filePath))
739
                return;
740
            
741
			IProducerConsumerCollection<FileEntry> files=RecentFiles;
742
			FileEntry popped;
743
			while (files.Count > 5)
744
				files.TryTake(out popped);
745
            var entry = new FileEntry { FullPath = filePath };
746
			files.TryAdd(entry);
747
		}
748

    
749
		public void NotifyAccount(AccountInfo account)
750
		{
751
			if (account== null)
752
				return;
753
			//TODO: What happens to an existing account whose Token has changed?
754
			account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
755
				account.SiteUri, Uri.EscapeDataString(account.Token),
756
				Uri.EscapeDataString(account.UserName));
757

    
758
			if (Accounts.All(item => item.UserName != account.UserName))
759
				Accounts.TryAdd(account);
760

    
761
		}
762

    
763
		public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
764
		{
765
			if (conflictFiles == null)
766
				return;
767
		    //Convert to list to avoid multiple iterations
768
            var files = conflictFiles.ToList();
769
			if (files.Count==0)
770
				return;
771

    
772
			UpdateStatus();
773
			//TODO: Create a more specific message. For now, just show a warning
774
			NotifyForFiles(files,message,TraceLevel.Warning);
775

    
776
		}
777

    
778
		public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info)
779
		{
780
			if (files == null)
781
				return;
782
			if (!files.Any())
783
				return;
784

    
785
			StatusMessage = message;
786

    
787
			_events.Publish(new Notification { Title = "Pithos", Message = message, Level = level});
788
		}
789

    
790
		public void Notify(Notification notification)
791
		{
792
			_events.Publish(notification);
793
		}
794

    
795

    
796
		public void RemoveMonitor(string accountName)
797
		{
798
			if (String.IsNullOrWhiteSpace(accountName))
799
				return;
800

    
801
			var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName);
802
            if (accountInfo != null)
803
            {
804
                _accounts.TryRemove(accountInfo);
805
                _pollAgent.RemoveAccount(accountInfo);
806
            }
807

    
808
		    PithosMonitor monitor;
809
			if (Monitors.TryRemove(accountName, out monitor))
810
			{
811
				monitor.Stop();
812
                //TODO: Also remove any pending actions for this account
813
                //from the network queue                
814
			}
815
		}
816

    
817
		public void RefreshOverlays()
818
		{
819
			foreach (var pair in Monitors)
820
			{
821
				var monitor = pair.Value;
822

    
823
				var path = monitor.RootPath;
824

    
825
				if (String.IsNullOrWhiteSpace(path))
826
					continue;
827

    
828
				if (!Directory.Exists(path) && !File.Exists(path))
829
					continue;
830

    
831
				IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
832

    
833
				try
834
				{
835
					NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
836
												 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
837
												 pathPointer, IntPtr.Zero);
838
				}
839
				finally
840
				{
841
					Marshal.FreeHGlobal(pathPointer);
842
				}
843
			}
844
		}
845

    
846
		#region Event Handlers
847
		
848
		public void Handle(SelectiveSynchChanges message)
849
		{
850
			var accountName = message.Account.AccountName;
851
			PithosMonitor monitor;
852
			if (_monitors.TryGetValue(accountName, out monitor))
853
			{
854
				monitor.SetSelectivePaths(message.Uris,message.Added,message.Removed);
855

    
856
			}
857
			
858
		}
859

    
860

    
861
		private bool _pollStarted;
862
	    private Sparkle _sparkle;
863

    
864
	    //SMELL: Doing so much work for notifications in the shell is wrong
865
		//The notifications should be moved to their own view/viewmodel pair
866
		//and different templates should be used for different message types
867
		//This will also allow the addition of extra functionality, eg. actions
868
		//
869
		public void Handle(Notification notification)
870
		{
871
			UpdateStatus();
872

    
873
			if (!Settings.ShowDesktopNotifications)
874
				return;
875

    
876
			if (notification is PollNotification)
877
			{
878
				_pollStarted = true;
879
				return;
880
			}
881
			if (notification is CloudNotification)
882
			{
883
				if (!_pollStarted) 
884
					return;
885
				_pollStarted= false;
886
				notification.Title = "Pithos";
887
				notification.Message = "Start Synchronisation";
888
			}
889

    
890
		    var deleteNotification = notification as CloudDeleteNotification;
891
            if (deleteNotification != null)
892
            {
893
                StatusMessage = String.Format("Deleted {0}", deleteNotification.Data.Name);
894
                return;
895
            }
896

    
897
		    var progress = notification as ProgressNotification;
898
		    if (progress != null)
899
		    {
900
		        StatusMessage = String.Format("Pithos {0}\r\n{1} {2:p2} of {3} - {4}",
901
		                                      _fileVersion.Value.FileVersion, 
902
                                              progress.Action,
903
		                                      progress.Block/(double)progress.TotalBlocks,
904
		                                      progress.FileSize.ToByteSize(),
905
		                                      progress.FileName);
906
		        return;
907
		    }
908

    
909
		    var info = notification as StatusNotification;
910
            if (info != null)
911
            {
912
                StatusMessage = String.Format("Pithos {0}\r\n{1}",
913
                                              _fileVersion.Value.FileVersion,
914
                                              info.Title);
915
                return;
916
            }
917
			if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
918
				return;
919

    
920
			ShowBalloonFor(notification);
921
		}
922

    
923
	    private void ShowBalloonFor(Notification notification)
924
	    {
925
            Contract.Requires(notification!=null);
926
            
927
            if (!Settings.ShowDesktopNotifications) 
928
                return;
929
            
930
            BalloonIcon icon;
931
	        switch (notification.Level)
932
	        {
933
	            case TraceLevel.Info:
934
	            case TraceLevel.Verbose:
935
	                return;
936
                case TraceLevel.Error:
937
                    icon = BalloonIcon.Error;
938
                    break;
939
                case TraceLevel.Warning:
940
	                icon = BalloonIcon.Warning;
941
	                break;
942
	            default:
943
	                return;
944
	        }
945

    
946
	        var tv = (ShellView) GetView();
947
	        System.Action clickAction = null;
948
	        if (notification is ExpirationNotification)
949
	        {
950
	            clickAction = () => ShowPreferences("AccountTab");
951
	        }
952
	        var balloon = new PithosBalloon
953
	                          {
954
	                              Title = notification.Title,
955
	                              Message = notification.Message,
956
	                              Icon = icon,
957
	                              ClickAction = clickAction
958
	                          };
959
	        tv.TaskbarView.ShowCustomBalloon(balloon, PopupAnimation.Fade, 4000);
960
	    }
961

    
962
	    #endregion
963

    
964
		public void Handle(ShowFilePropertiesEvent message)
965
		{
966
			if (message == null)
967
				throw new ArgumentNullException("message");
968
			if (String.IsNullOrWhiteSpace(message.FileName) )
969
				throw new ArgumentException("message");
970
			Contract.EndContractBlock();
971

    
972
			var fileName = message.FileName;
973
			//TODO: Display file properties for non-container folders
974
			if (File.Exists(fileName))
975
				//Retrieve the full name with exact casing. Pithos names are case sensitive				
976
				ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
977
			else if (Directory.Exists(fileName))
978
				//Retrieve the full name with exact casing. Pithos names are case sensitive
979
			{
980
				var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
981
				if (IsContainer(path))
982
					ShowContainerProperties(path);
983
				else
984
					ShowFileProperties(path);
985
			}
986
		}
987

    
988
		private bool IsContainer(string path)
989
		{
990
			var matchingFolders = from account in _accounts
991
								  from rootFolder in Directory.GetDirectories(account.AccountPath)
992
								  where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
993
								  select rootFolder;
994
			return matchingFolders.Any();
995
		}
996

    
997
		public FileStatus GetFileStatus(string localFileName)
998
		{
999
			if (String.IsNullOrWhiteSpace(localFileName))
1000
				throw new ArgumentNullException("localFileName");
1001
			Contract.EndContractBlock();
1002
			
1003
			var statusKeeper = IoC.Get<IStatusKeeper>();
1004
			var status=statusKeeper.GetFileStatus(localFileName);
1005
			return status;
1006
		}
1007

    
1008
	    public void RemoveAccountFromDatabase(AccountSettings account)
1009
	    {
1010
            var statusKeeper = IoC.Get<IStatusKeeper>();
1011
            statusKeeper.ClearFolderStatus(account.RootPath);	        
1012
	    }
1013
	}
1014
}