Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / Shell / ShellViewModel.cs @ ee950288

History | View | Annotate | Download (36.5 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="ShellViewModel.cs" company="GRNet">
4
 * 
5
 * Copyright 2011-2012 GRNET S.A. All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or
8
 * without modification, are permitted provided that the following
9
 * conditions are met:
10
 *
11
 *   1. Redistributions of source code must retain the above
12
 *      copyright notice, this list of conditions and the following
13
 *      disclaimer.
14
 *
15
 *   2. Redistributions in binary form must reproduce the above
16
 *      copyright notice, this list of conditions and the following
17
 *      disclaimer in the documentation and/or other materials
18
 *      provided with the distribution.
19
 *
20
 *
21
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 * The views and conclusions contained in the software and
35
 * documentation are those of the authors and should not be
36
 * interpreted as representing official policies, either expressed
37
 * or implied, of GRNET S.A.
38
 * </copyright>
39
 * -----------------------------------------------------------------------
40
 */
41
#endregion
42
using System.Collections.Concurrent;
43
using System.Diagnostics;
44
using System.Diagnostics.Contracts;
45
using System.IO;
46
using System.Net;
47
using System.Reflection;
48
using System.Runtime.InteropServices;
49
using System.ServiceModel;
50
using System.Threading.Tasks;
51
using System.Windows;
52
using System.Windows.Controls.Primitives;
53
using 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)), Export(typeof(ShellViewModel))]
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<Uri, PithosMonitor> _monitors = new ConcurrentDictionary<Uri, 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<Uri, 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
	    private readonly PollAgent _pollAgent;
126
	    private readonly NetworkAgent _networkAgent;
127

    
128
	    [Import]
129
	    public Selectives Selectives { get; set; }
130

    
131
	    private MiniStatusViewModel _miniStatus;
132

    
133
	    [Import]
134
        public MiniStatusViewModel MiniStatus
135
	    {
136
	        get { return _miniStatus; }
137
	        set
138
	        {
139
	            _miniStatus = value;
140
	            _miniStatus.Shell = this;
141
	            _miniStatus.Deactivated += (sender, arg) =>
142
	                                           {
143
	                                               _statusVisible = false;
144
                                                   NotifyOfPropertyChange(()=>MiniStatusCaption);
145
	                                           };
146
	        }
147
	    }
148

    
149
	    ///<summary>
150
		/// The Shell depends on MEF to provide implementations for windowManager, events, the status checker service and the settings
151
		///</summary>
152
		///<remarks>
153
		/// The PithosSettings class encapsulates the app's settings to abstract their storage mechanism (App settings, a database or registry)
154
		///</remarks>
155
		[ImportingConstructor]		
156
		public ShellViewModel(IWindowManager windowManager, IEventAggregator events, IStatusChecker statusChecker, PithosSettings settings,PollAgent pollAgent,NetworkAgent networkAgent)
157
		{
158
			try
159
			{
160

    
161
				_windowManager = windowManager;
162
				//CHECK: Caliburn doesn't need explicit command construction
163
				//OpenPithosFolderCommand = new PithosCommand(OpenPithosFolder);
164
				_statusChecker = statusChecker;
165
				//The event subst
166
				_events = events;
167
				_events.Subscribe(this);
168

    
169
			    _pollAgent = pollAgent;
170
			    _networkAgent = networkAgent;
171
				Settings = settings;
172

    
173
				Proxy.SetFromSettings(settings);
174

    
175
                StatusMessage = Settings.Accounts.Count==0 
176
                    ? "No Accounts added\r\nPlease add an account" 
177
                    : "Starting";
178

    
179
				_accounts.CollectionChanged += (sender, e) =>
180
												   {
181
													   NotifyOfPropertyChange(() => OpenFolderCaption);
182
													   NotifyOfPropertyChange(() => HasAccounts);
183
												   };
184

    
185
                SetVersionMessage();
186
			}
187
			catch (Exception exc)
188
			{
189
				Log.Error("Error while starting the ShellViewModel",exc);
190
				throw;
191
			}
192

    
193
		}
194

    
195
	    private void SetVersionMessage()
196
	    {
197
	        Assembly assembly = Assembly.GetExecutingAssembly();
198
	        var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
199
	        VersionMessage = String.Format("Pithos+ {0}", fileVersion.FileVersion);
200
	    }
201

    
202
        public void CurrentSyncStatus()
203
        {
204
            if (Accounts.Count == 0)
205
            {
206
                ShowPreferences("AccountTab");
207
            }
208
            else
209
            {
210
                if (!_statusVisible)
211
                    _windowManager.ShowWindow(MiniStatus);
212
                else
213
                {
214
                    if (MiniStatus.IsActive)
215
                        MiniStatus.TryClose();
216
                }
217
                _statusVisible = !_statusVisible;
218

    
219
                NotifyOfPropertyChange(() => MiniStatusCaption);
220
            }
221
        }
222

    
223
	    protected override void OnActivate()
224
		{
225
			base.OnActivate();
226

    
227
            InitializeSparkle();
228

    
229
	        //Must delay opening the upgrade window
230
            //to avoid Windows Messages sent by the TaskbarIcon
231
            TaskEx.Delay(5000).ContinueWith(_=>
232
                Execute.OnUIThread(()=> _sparkle.StartLoop(true,Settings.UpdateForceCheck,Settings.UpdateCheckInterval)));
233

    
234

    
235
			StartMonitoring();                    
236
		}
237

    
238

    
239
	    private void OnCheckFinished(object sender, bool updaterequired)
240
	    {
241
            
242
            Log.InfoFormat("Upgrade check finished. Need Upgrade: {0}", updaterequired);
243
            if (_manualUpgradeCheck)
244
            {
245
                _manualUpgradeCheck = false;
246
                if (!updaterequired)
247
                    //Sparkle raises events on a background thread
248
                    Execute.OnUIThread(()=>
249
                        ShowBalloonFor(new Notification{Title="Pithos+ is up to date",Message="You have the latest Pithos+ version. No update is required"}));
250
            }
251
	    }
252

    
253
	    private void OnUpgradeDetected(object sender, UpdateDetectedEventArgs e)
254
	    {            
255
	        Log.InfoFormat("Update detected {0}",e.LatestVersion);
256
	    }
257

    
258
        public void CheckForUpgrade()
259
        {
260
            ShowBalloonFor(new Notification{Title="Checking for upgrades",Message="Contacting the server to retrieve the latest Pithos+ version."});
261
            _sparkle.StopLoop();
262
            _sparkle.updateDetected -= OnUpgradeDetected;
263
            _sparkle.checkLoopFinished -= OnCheckFinished;
264
            _sparkle.Dispose();
265

    
266
            _manualUpgradeCheck = true;
267
            InitializeSparkle();
268
            _sparkle.StartLoop(true,true,Settings.UpdateCheckInterval);
269
        }
270

    
271
        private void InitializeSparkle()
272
        {
273
            _sparkle = new Sparkle(Settings.UpdateUrl);
274
            _sparkle.updateDetected += OnUpgradeDetected;
275
            _sparkle.checkLoopFinished += OnCheckFinished;
276
            _sparkle.ShowDiagnosticWindow = Settings.UpdateDiagnostics;
277
        }
278

    
279
	    private async void StartMonitoring()
280
		{
281
			try
282
			{
283
                if (Settings.IgnoreCertificateErrors)
284
                {
285
                    ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
286
                }
287
                    
288
				var accounts = Settings.Accounts.Select(MonitorAccount);
289
				await TaskEx.WhenAll(accounts);
290
				_statusService = StatusService.Start();
291

    
292
			}
293
			catch (AggregateException exc)
294
			{
295
				exc.Handle(e =>
296
				{
297
					Log.Error("Error while starting monitoring", e);
298
					return true;
299
				});
300
				throw;
301
			}
302
		}
303

    
304
		protected override void OnDeactivate(bool close)
305
		{
306
			base.OnDeactivate(close);
307
			if (close)
308
			{
309
				StatusService.Stop(_statusService);
310
				_statusService = null;
311
			}
312
		}
313

    
314
		public Task MonitorAccount(AccountSettings account)
315
		{
316
			return Task.Factory.StartNew(() =>
317
			{                                                
318
				PithosMonitor monitor;
319
				var accountName = account.AccountName;
320

    
321
			    MigrateFolders(account);
322

    
323
			    Selectives.SetIsSelectiveEnabled(account.AccountKey, account.SelectiveSyncEnabled);
324

    
325
				if (Monitors.TryGetValue(account.AccountKey, out monitor))
326
				{
327
					//If the account is active
328
                    if (account.IsActive)
329
                    {
330
                        //The Api Key may have changed throuth the Preferences dialog
331
                        monitor.ApiKey = account.ApiKey;
332
						Debug.Assert(monitor.StatusNotification == this,"An existing monitor should already have a StatusNotification service object");
333
                        monitor.RootPath = account.RootPath;
334
                        //Start the monitor. It's OK to start an already started monitor,
335
                        //it will just ignore the call                        
336
                        StartMonitor(monitor).Wait();
337
                    }
338
                    else
339
                    {
340
                        //If the account is inactive
341
                        //Stop and remove the monitor
342
                        RemoveMonitor(account.ServerUrl,accountName);
343
                    }
344
					return;
345
				}
346

    
347
				
348
				//Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
349
				monitor = new PithosMonitor
350
							  {
351
								  UserName = accountName,
352
								  ApiKey = account.ApiKey,                                  
353
								  StatusNotification = this,
354
								  RootPath = account.RootPath
355
							  };
356
				//PithosMonitor uses MEF so we need to resolve it
357
				IoC.BuildUp(monitor);
358

    
359
				monitor.AuthenticationUrl = account.ServerUrl;
360

    
361
				Monitors[account.AccountKey] = monitor;
362

    
363
				if (account.IsActive)
364
				{
365
					//Don't start a monitor if it doesn't have an account and ApiKey
366
					if (String.IsNullOrWhiteSpace(monitor.UserName) ||
367
						String.IsNullOrWhiteSpace(monitor.ApiKey))
368
						return;
369
					StartMonitor(monitor);
370
				}
371
			});
372
		}
373

    
374
	    private void MigrateFolders(AccountSettings account)
375
	    {
376
	        var oldOthersFolder=Path.Combine(account.RootPath, FolderConstants.OldOthersFolder);
377
	        var newOthersFolder = Path.Combine(account.RootPath, FolderConstants.OthersFolder);
378
	        var oldFolder = new DirectoryInfo(oldOthersFolder);
379
	        var newFolder = new DirectoryInfo(newOthersFolder);
380

    
381
            if (oldFolder.Exists && !newFolder.Exists)
382
            {
383
                oldFolder.MoveTo(newOthersFolder);
384
            }
385
	    }
386

    
387

    
388
	    protected override void OnViewLoaded(object view)
389
		{
390
			UpdateStatus();
391
			var window = (Window)view;            
392
			TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
393
			base.OnViewLoaded(view);
394
		}
395

    
396

    
397
		#region Status Properties
398

    
399
		private string _statusMessage;
400
		public string StatusMessage
401
		{
402
			get { return _statusMessage; }
403
			set
404
			{
405
				_statusMessage = value;
406
				NotifyOfPropertyChange(() => StatusMessage);
407
                NotifyOfPropertyChange(() => TooltipMessage);
408
			}
409
		}
410

    
411
        public string VersionMessage { get; set; }
412

    
413
	    public string TooltipMessage
414
	    {
415
	        get
416
	        {
417
	            return String.Format("{0}\r\n{1}",VersionMessage,StatusMessage);
418
	        }
419
	    }
420

    
421
        public string TooltipMiniStatus
422
        {
423
            get
424
            {
425
                return String.Format("{0}\r\n{1}", "Status Window", "Enable / Dissable the stuatus window");
426
            }
427
        }
428

    
429
        public string ToggleStatusWindowMessage
430
        {
431
            get
432
            {
433
                return String.Format("{0}" + Environment.NewLine + "{1} Toggle Mini Status");
434
            }
435
        }
436

    
437
	    private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
438
		public ObservableConcurrentCollection<AccountInfo> Accounts
439
		{
440
			get { return _accounts; }
441
		}
442

    
443
		public bool HasAccounts
444
		{
445
			get { return _accounts.Count > 0; }
446
		}
447

    
448

    
449
		public string OpenFolderCaption
450
		{
451
			get
452
			{
453
				return (_accounts.Count == 0)
454
						? "No Accounts Defined"
455
						: "Open Pithos Folder";
456
			}
457
		}
458

    
459
		private string _pauseSyncCaption="Pause Synching";
460
		public string PauseSyncCaption
461
		{
462
			get { return _pauseSyncCaption; }
463
			set
464
			{
465
				_pauseSyncCaption = value;
466
				NotifyOfPropertyChange(() => PauseSyncCaption);
467
			}
468
		}
469

    
470
		private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
471
		public ObservableConcurrentCollection<FileEntry> RecentFiles
472
		{
473
			get { return _recentFiles; }
474
		}
475

    
476

    
477
		private string _statusIcon="../Images/Pithos.ico";
478
		public string StatusIcon
479
		{
480
			get { return _statusIcon; }
481
			set
482
			{
483
				//TODO: Ensure all status icons use the Pithos logo
484
				_statusIcon = value;
485
				NotifyOfPropertyChange(() => StatusIcon);
486
			}
487
		}
488

    
489
		#endregion
490

    
491
		#region Commands
492

    
493
        public void CancelCurrentOperation()
494
        {
495
            _networkAgent.CancelCurrentOperation();
496
        }
497

    
498
        public void ShowPreferences()
499
        {
500
            ShowPreferences(null);
501
        }
502

    
503
		public void ShowPreferences(string currentTab)
504
		{
505
			//Settings.Reload();
506
            
507
		    var preferences = new PreferencesViewModel(_windowManager, _events, this, Settings,currentTab);
508
		    _windowManager.ShowDialog(preferences);
509
			
510
		}
511

    
512
		public void AboutPithos()
513
		{
514
			var about = IoC.Get<AboutViewModel>();
515
		    about.LatestVersion=_sparkle.LatestVersion;
516
			_windowManager.ShowWindow(about);
517
		}
518

    
519
		public void SendFeedback()
520
		{
521
			var feedBack =  IoC.Get<FeedbackViewModel>();
522
			_windowManager.ShowWindow(feedBack);
523
		}
524

    
525
		//public PithosCommand OpenPithosFolderCommand { get; private set; }
526

    
527
		public void OpenPithosFolder()
528
		{
529
			var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
530
			if (account == null)
531
				return;
532
			Process.Start(account.RootPath);
533
		}
534

    
535
		public void OpenPithosFolder(AccountInfo account)
536
		{
537
			Process.Start(account.AccountPath);
538
		}
539

    
540
		
541

    
542
		public void GoToSite()
543
		{            
544
			var site = Properties.Settings.Default.ProductionServer;
545
			Process.Start(site);            
546
		}
547

    
548

    
549
		public void GoToSite(AccountInfo account)
550
		{
551
		    var uri = account.SiteUri.Replace("http://","https://");            
552
		    Process.Start(uri);
553
		}
554

    
555
	    private bool _statusVisible;
556

    
557
	    public string MiniStatusCaption
558
	    {
559
	        get
560
	        {
561
	            return  _statusVisible ? "Hide Status Window" : "Show Status Window";
562
	        }
563
	    }
564

    
565
	    public bool HasConflicts
566
	    {
567
            get { return true; }
568
	    }
569
        public void ShowConflicts()
570
        {
571
            _windowManager.ShowWindow(IoC.Get<ConflictsViewModel>());            
572
        }
573

    
574
	    /// <summary>
575
        /// Open an explorer window to the target path's directory
576
        /// and select the file
577
        /// </summary>
578
        /// <param name="entry"></param>
579
        public void GoToFile(FileEntry entry)
580
        {
581
            var fullPath = entry.FullPath;
582
            if (!File.Exists(fullPath) && !Directory.Exists(fullPath))
583
                return;
584
            Process.Start("explorer.exe","/select, " + fullPath);
585
        }
586

    
587
        public void OpenLogPath()
588
        {
589
            var pithosDataPath = PithosSettings.PithosDataPath;
590

    
591
            Process.Start(pithosDataPath);
592
        }
593
        
594
        public void ShowFileProperties()
595
		{
596
			var account = Settings.Accounts.First(acc => acc.IsActive);            
597
			var dir = new DirectoryInfo(account.RootPath + @"\pithos");
598
			var files=dir.GetFiles();
599
			var r=new Random();
600
			var idx=r.Next(0, files.Length);
601
			ShowFileProperties(files[idx].FullName);            
602
		}
603

    
604
		public void ShowFileProperties(string filePath)
605
		{
606
			if (String.IsNullOrWhiteSpace(filePath))
607
				throw new ArgumentNullException("filePath");
608
			if (!File.Exists(filePath) && !Directory.Exists(filePath))
609
				throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
610
			Contract.EndContractBlock();
611

    
612
			var pair=(from monitor in  Monitors
613
							   where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
614
								   select monitor).FirstOrDefault();
615
			var accountMonitor = pair.Value;
616

    
617
			if (accountMonitor == null)
618
				return;
619

    
620
			var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
621

    
622
			
623

    
624
			var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
625
			_windowManager.ShowWindow(fileProperties);
626
		} 
627
		
628
		public void ShowContainerProperties()
629
		{
630
			var account = Settings.Accounts.First(acc => acc.IsActive);            
631
			var dir = new DirectoryInfo(account.RootPath);
632
			var fullName = (from folder in dir.EnumerateDirectories()
633
							where (folder.Attributes & FileAttributes.Hidden) == 0
634
							select folder.FullName).First();
635
			ShowContainerProperties(fullName);            
636
		}
637

    
638
		public void ShowContainerProperties(string filePath)
639
		{
640
			if (String.IsNullOrWhiteSpace(filePath))
641
				throw new ArgumentNullException("filePath");
642
			if (!Directory.Exists(filePath))
643
				throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
644
			Contract.EndContractBlock();
645

    
646
			var pair=(from monitor in  Monitors
647
							   where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
648
								   select monitor).FirstOrDefault();
649
			var accountMonitor = pair.Value;            
650
			var info = accountMonitor.GetContainerInfo(filePath);
651

    
652
			
653

    
654
			var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
655
			_windowManager.ShowWindow(containerProperties);
656
		}
657

    
658
		public void SynchNow()
659
		{
660
			_pollAgent.SynchNow();
661
		}
662

    
663
		public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
664
		{
665
			if (currentInfo==null)
666
				throw new ArgumentNullException("currentInfo");
667
			Contract.EndContractBlock();		    
668
            var monitor = Monitors[currentInfo.AccountKey];
669
			var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
670
			return newInfo;
671
		}
672

    
673
		public ContainerInfo RefreshContainerInfo(ContainerInfo container)
674
		{
675
			if (container == null)
676
				throw new ArgumentNullException("container");
677
			Contract.EndContractBlock();
678

    
679
			var monitor = Monitors[container.AccountKey];
680
			var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
681
			return newInfo;
682
		}
683

    
684
	    private bool _isPaused;
685
	    public bool IsPaused
686
	    {
687
	        get { return _isPaused; }
688
	        set
689
	        {
690
	            _isPaused = value;
691
                PauseSyncCaption = IsPaused ? "Resume syncing" : "Pause syncing";
692
                var iconKey = IsPaused ? "TraySyncPaused" : "TrayInSynch";
693
                StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
694

    
695
                NotifyOfPropertyChange(() => IsPaused);
696
	        }
697
	    }
698

    
699
	    public void ToggleSynching()
700
		{
701
			IsPaused=!IsPaused;
702
			foreach (var monitor in Monitors.Values)
703
			{
704
			    monitor.Pause = IsPaused ;
705
			}
706
            _pollAgent.Pause = IsPaused;
707
            _networkAgent.Pause = IsPaused;
708

    
709

    
710
		}
711

    
712
        public void ExitPithos()
713
        {
714
            try
715
            {
716

    
717
                foreach (var monitor in Monitors.Select(pair => pair.Value))
718
                {
719
                    monitor.Stop();
720
                }
721

    
722
                var view = GetView() as Window;
723
                if (view != null)
724
                    view.Close();
725
            }
726
            catch (Exception exc)
727
            {
728
                Log.Info("Exception while exiting", exc);                
729
            }
730
            finally
731
            {
732
                Application.Current.Shutdown();
733
            }
734
        }
735

    
736
	    #endregion
737

    
738

    
739
		private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
740
			{
741
				new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
742
				new StatusInfo(PithosStatus.PollSyncing, "Polling Files", "TraySynching"),
743
                new StatusInfo(PithosStatus.LocalSyncing, "Syncing Files", "TraySynching"),
744
				new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
745
			}.ToDictionary(s => s.Status);
746

    
747
		readonly IWindowManager _windowManager;
748
		
749
        //private int _syncCount=0;
750

    
751

    
752
        private PithosStatus _pithosStatus = PithosStatus.Disconnected;
753

    
754
        public void SetPithosStatus(PithosStatus status)
755
        {
756
            if (_pithosStatus == PithosStatus.LocalSyncing && status == PithosStatus.PollComplete)
757
                return;
758
            if (_pithosStatus == PithosStatus.PollSyncing && status == PithosStatus.LocalComplete)
759
                return;
760
            if (status == PithosStatus.LocalComplete || status == PithosStatus.PollComplete)
761
                _pithosStatus = PithosStatus.InSynch;
762
            else
763
                _pithosStatus = status;
764
            UpdateStatus();
765
        }
766

    
767
        public void SetPithosStatus(PithosStatus status,string message)
768
        {
769
            StatusMessage = message;
770
            SetPithosStatus(status);
771
        }
772

    
773
	  /*  public Notifier GetNotifier(Notification startNotification, Notification endNotification)
774
	    {
775
	        return new Notifier(this, startNotification, endNotification);
776
	    }*/
777

    
778
	    public Notifier GetNotifier(string startMessage, string endMessage, params object[] args)
779
	    {
780
	        return new Notifier(this, 
781
                new StatusNotification(String.Format(startMessage,args)), 
782
                new StatusNotification(String.Format(endMessage,args)));
783
	    }
784

    
785

    
786
	    ///<summary>
787
		/// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat		
788
		///</summary>
789
		public void UpdateStatus()
790
		{
791

    
792
			if (_iconNames.ContainsKey(_pithosStatus))
793
			{
794
				var info = _iconNames[_pithosStatus];
795
				StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
796
			}
797

    
798
            if (_pithosStatus == PithosStatus.InSynch)
799
                StatusMessage = "All files up to date";
800
		}
801

    
802

    
803
	   
804
		private Task StartMonitor(PithosMonitor monitor,int retries=0)
805
		{
806
			return Task.Factory.StartNew(() =>
807
			{
808
				using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
809
				{
810
					try
811
					{
812
						Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
813

    
814
						monitor.Start();
815
					}
816
					catch (WebException exc)
817
					{
818
						if (AbandonRetry(monitor, retries))
819
							return;
820

    
821
						HttpStatusCode statusCode =HttpStatusCode.OK;
822
						var response = exc.Response as HttpWebResponse;
823
						if(response!=null)
824
							statusCode = response.StatusCode;
825

    
826
						switch (statusCode)
827
						{
828
							case HttpStatusCode.Unauthorized:
829
								var message = String.Format("API Key Expired for {0}. Starting Renewal",
830
															monitor.UserName);
831
								Log.Error(message, exc);
832
                                var account = Settings.Accounts.Find(acc => acc.AccountKey == new Uri(new Uri(monitor.AuthenticationUrl), monitor.UserName));                                
833
						        account.IsExpired = true;
834
                                Notify(new ExpirationNotification(account));
835
								//TryAuthorize(monitor.UserName, retries).Wait();
836
								break;
837
							case HttpStatusCode.ProxyAuthenticationRequired:
838
								TryAuthenticateProxy(monitor,retries);
839
								break;
840
							default:
841
								TryLater(monitor, exc, retries);
842
								break;
843
						}
844
					}
845
					catch (Exception exc)
846
					{
847
						if (AbandonRetry(monitor, retries)) 
848
							return;
849

    
850
						TryLater(monitor,exc,retries);
851
					}
852
				}
853
			});
854
		}
855

    
856
		private void TryAuthenticateProxy(PithosMonitor monitor,int retries)
857
		{
858
			Execute.OnUIThread(() =>
859
								   {                                       
860
									   var proxyAccount = IoC.Get<ProxyAccountViewModel>();
861
										proxyAccount.Settings = Settings;
862
									   if (true != _windowManager.ShowDialog(proxyAccount)) 
863
										   return;
864
									   StartMonitor(monitor, retries);
865
									   NotifyOfPropertyChange(() => Accounts);
866
								   });
867
		}
868

    
869
		private bool AbandonRetry(PithosMonitor monitor, int retries)
870
		{
871
			if (retries > 1)
872
			{
873
				var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
874
											monitor.UserName);
875
				_events.Publish(new Notification
876
									{Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
877
				return true;
878
			}
879
			return false;
880
		}
881

    
882

    
883
	    private void TryLater(PithosMonitor monitor, Exception exc,int retries)
884
		{
885
			var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
886
			Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
887
			_events.Publish(new Notification
888
								{Title = "Error", Message = message, Level = TraceLevel.Error});
889
			Log.Error(message, exc);
890
		}
891

    
892

    
893
		public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
894
		{
895
			StatusMessage = status;
896
			
897
			_events.Publish(new Notification { Title = "Pithos+", Message = status, Level = level });
898
		}
899

    
900
		public void NotifyChangedFile(string filePath)
901
		{
902
            if (RecentFiles.Any(e => e.FullPath == filePath))
903
                return;
904
            
905
			IProducerConsumerCollection<FileEntry> files=RecentFiles;
906
			FileEntry popped;
907
			while (files.Count > 5)
908
				files.TryTake(out popped);
909
            var entry = new FileEntry { FullPath = filePath };
910
			files.TryAdd(entry);
911
		}
912

    
913
		public void NotifyAccount(AccountInfo account)
914
		{
915
			if (account== null)
916
				return;
917
			//TODO: What happens to an existing account whose Token has changed?
918
			account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
919
				account.SiteUri, Uri.EscapeDataString(account.Token),
920
				Uri.EscapeDataString(account.UserName));
921

    
922
			if (!Accounts.Any(item => item.UserName == account.UserName && item.SiteUri == account.SiteUri))
923
				Accounts.TryAdd(account);
924

    
925
		}
926

    
927
		public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
928
		{
929
			if (conflictFiles == null)
930
				return;
931
		    //Convert to list to avoid multiple iterations
932
            var files = conflictFiles.ToList();
933
			if (files.Count==0)
934
				return;
935

    
936
			UpdateStatus();
937
			//TODO: Create a more specific message. For now, just show a warning
938
			NotifyForFiles(files,message,TraceLevel.Warning);
939

    
940
		}
941

    
942
		public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info)
943
		{
944
			if (files == null)
945
				return;
946
			if (!files.Any())
947
				return;
948

    
949
			StatusMessage = message;
950

    
951
			_events.Publish(new Notification { Title = "Pithos+", Message = message, Level = level});
952
		}
953

    
954
		public void Notify(Notification notification)
955
		{
956
			_events.Publish(notification);
957
		}
958

    
959

    
960
		public void RemoveMonitor(string serverUrl,string accountName)
961
		{
962
			if (String.IsNullOrWhiteSpace(accountName))
963
				return;
964

    
965
			var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName && account.StorageUri.ToString().StartsWith(serverUrl));
966
            if (accountInfo != null)
967
            {
968
                _accounts.TryRemove(accountInfo);
969
                _pollAgent.RemoveAccount(accountInfo);
970
            }
971

    
972
            var accountKey = new Uri(new Uri(serverUrl),accountName);
973
		    PithosMonitor monitor;
974
			if (Monitors.TryRemove(accountKey, out monitor))
975
			{
976
				monitor.Stop();
977
                //TODO: Also remove any pending actions for this account
978
                //from the network queue                
979
			}
980
		}
981

    
982
		public void RefreshOverlays()
983
		{
984
			foreach (var pair in Monitors)
985
			{
986
				var monitor = pair.Value;
987

    
988
				var path = monitor.RootPath;
989

    
990
				if (String.IsNullOrWhiteSpace(path))
991
					continue;
992

    
993
				if (!Directory.Exists(path) && !File.Exists(path))
994
					continue;
995

    
996
				IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
997

    
998
				try
999
				{
1000
					NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
1001
												 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
1002
												 pathPointer, IntPtr.Zero);
1003
				}
1004
				finally
1005
				{
1006
					Marshal.FreeHGlobal(pathPointer);
1007
				}
1008
			}
1009
		}
1010

    
1011
		#region Event Handlers
1012
		
1013
		public void Handle(SelectiveSynchChanges message)
1014
		{
1015
		    TaskEx.Run(() =>
1016
		    {
1017
		        PithosMonitor monitor;
1018
		        if (Monitors.TryGetValue(message.Account.AccountKey, out monitor))
1019
		        {
1020
                    Selectives.SetIsSelectiveEnabled(message.Account.AccountKey, message.Enabled);
1021
		            monitor.SetSelectivePaths(message.Uris, message.Added, message.Removed);
1022
		        }
1023

    
1024
		        var account = Accounts.FirstOrDefault(acc => acc.AccountKey == message.Account.AccountKey);
1025
		        if (account != null)
1026
		        {
1027
		            this._pollAgent.SetSelectivePaths(account, message.Added, message.Removed);
1028
		        }
1029
		    });
1030

    
1031
		}
1032

    
1033

    
1034
		private bool _pollStarted;
1035
	    private Sparkle _sparkle;
1036
	    private bool _manualUpgradeCheck;
1037

    
1038
	    //SMELL: Doing so much work for notifications in the shell is wrong
1039
		//The notifications should be moved to their own view/viewmodel pair
1040
		//and different templates should be used for different message types
1041
		//This will also allow the addition of extra functionality, eg. actions
1042
		//
1043
		public void Handle(Notification notification)
1044
		{
1045
			UpdateStatus();
1046

    
1047
			if (!Settings.ShowDesktopNotifications)
1048
				return;
1049

    
1050
			if (notification is PollNotification)
1051
			{
1052
				_pollStarted = true;
1053
				return;
1054
			}
1055
			if (notification is CloudNotification)
1056
			{
1057
				if (!_pollStarted) 
1058
					return;
1059
				_pollStarted= false;
1060
				notification.Title = "Pithos+";
1061
				notification.Message = "Start Synchronisation";
1062
			}
1063

    
1064
		    var deleteNotification = notification as CloudDeleteNotification;
1065
            if (deleteNotification != null)
1066
            {
1067
                StatusMessage = String.Format("Deleted {0}", deleteNotification.Data.Name);
1068
                return;
1069
            }
1070

    
1071
		    var progress = notification as ProgressNotification;
1072
		    
1073
		    
1074
            if (progress != null)
1075
		    {
1076
		        StatusMessage = String.Format("{0} {1:p2} of {2} - {3}",		                                      
1077
                                              progress.Action,
1078
		                                      progress.Block/(double)progress.TotalBlocks,
1079
		                                      progress.FileSize.ToByteSize(),
1080
		                                      progress.FileName);
1081
		        return;
1082
		    }
1083

    
1084
		    var info = notification as StatusNotification;
1085
            if (info != null)
1086
            {
1087
                StatusMessage = info.Title;
1088
                return;
1089
            }
1090
			if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
1091
				return;
1092

    
1093
            if (notification.Level <= TraceLevel.Warning)
1094
			    ShowBalloonFor(notification);
1095
		}
1096

    
1097
	    private void ShowBalloonFor(Notification notification)
1098
	    {
1099
            Contract.Requires(notification!=null);
1100
            
1101
            if (!Settings.ShowDesktopNotifications) 
1102
                return;
1103
            
1104
            BalloonIcon icon;
1105
	        switch (notification.Level)
1106
	        {
1107
                case TraceLevel.Verbose:
1108
	                return;
1109
	            case TraceLevel.Info:	            
1110
	                icon = BalloonIcon.Info;
1111
	                break;
1112
                case TraceLevel.Error:
1113
                    icon = BalloonIcon.Error;
1114
                    break;
1115
                case TraceLevel.Warning:
1116
	                icon = BalloonIcon.Warning;
1117
	                break;
1118
	            default:
1119
	                return;
1120
	        }
1121

    
1122
	        var tv = (ShellView) GetView();
1123
	        System.Action clickAction = null;
1124
	        if (notification is ExpirationNotification)
1125
	        {
1126
	            clickAction = () => ShowPreferences("AccountTab");
1127
	        }
1128
	        var balloon = new PithosBalloon
1129
	                          {
1130
	                              Title = notification.Title,
1131
	                              Message = notification.Message,
1132
	                              Icon = icon,
1133
	                              ClickAction = clickAction
1134
	                          };
1135
	        tv.TaskbarView.ShowCustomBalloon(balloon, PopupAnimation.Fade, 4000);
1136
	    }
1137

    
1138
	    #endregion
1139

    
1140
		public void Handle(ShowFilePropertiesEvent message)
1141
		{
1142
			if (message == null)
1143
				throw new ArgumentNullException("message");
1144
			if (String.IsNullOrWhiteSpace(message.FileName) )
1145
				throw new ArgumentException("message");
1146
			Contract.EndContractBlock();
1147

    
1148
			var fileName = message.FileName;
1149
			//TODO: Display file properties for non-container folders
1150
			if (File.Exists(fileName))
1151
				//Retrieve the full name with exact casing. Pithos names are case sensitive				
1152
				ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
1153
			else if (Directory.Exists(fileName))
1154
				//Retrieve the full name with exact casing. Pithos names are case sensitive
1155
			{
1156
				var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
1157
				if (IsContainer(path))
1158
					ShowContainerProperties(path);
1159
				else
1160
					ShowFileProperties(path);
1161
			}
1162
		}
1163

    
1164
		private bool IsContainer(string path)
1165
		{
1166
			var matchingFolders = from account in _accounts
1167
								  from rootFolder in Directory.GetDirectories(account.AccountPath)
1168
								  where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
1169
								  select rootFolder;
1170
			return matchingFolders.Any();
1171
		}
1172

    
1173
		public FileStatus GetFileStatus(string localFileName)
1174
		{
1175
			if (String.IsNullOrWhiteSpace(localFileName))
1176
				throw new ArgumentNullException("localFileName");
1177
			Contract.EndContractBlock();
1178
			
1179
			var statusKeeper = IoC.Get<IStatusKeeper>();
1180
			var status=statusKeeper.GetFileStatus(localFileName);
1181
			return status;
1182
		}
1183

    
1184
	    public void RemoveAccountFromDatabase(AccountSettings account)
1185
	    {
1186
            var statusKeeper = IoC.Get<IStatusKeeper>();
1187
            statusKeeper.ClearFolderStatus(account.RootPath);	        
1188
	    }
1189
	}
1190
}