Changed MonitorAccount to call StartMonitor which handles reauthentication
[pithos-ms-client] / trunk / Pithos.Client.WPF / Shell / ShellViewModel.cs
1 using System.Collections.Concurrent;
2 using System.ComponentModel;
3 using System.ComponentModel.Composition;
4 using System.Diagnostics;
5 using System.Diagnostics.Contracts;
6 using System.IO;
7 using System.Net;
8 using System.Reflection;
9 using System.Runtime.InteropServices;
10 using System.ServiceModel;
11 using System.ServiceModel.Description;
12 using System.Threading.Tasks;
13 using System.Windows;
14 using Caliburn.Micro;
15 using Hardcodet.Wpf.TaskbarNotification;
16 using Pithos.Client.WPF.Configuration;
17 using Pithos.Client.WPF.FileProperties;
18 using Pithos.Client.WPF.Properties;
19 using Pithos.Client.WPF.SelectiveSynch;
20 using Pithos.Client.WPF.Services;
21 using Pithos.Client.WPF.Shell;
22 using Pithos.Core;
23 using Pithos.Interfaces;
24 using System;
25 using System.Collections.Generic;
26 using System.Linq;
27 using System.Text;
28 using Pithos.Network;
29 using StatusService = Pithos.Client.WPF.Services.StatusService;
30
31 namespace Pithos.Client.WPF {
32     using System.ComponentModel.Composition;
33
34     
35         ///<summary>
36         /// The "shell" of the Pithos application displays the taskbar  icon, menu and notifications.
37         /// The shell also hosts the status service called by shell extensions to retrieve file info
38         ///</summary>
39         ///<remarks>
40         /// It is a strange "shell" as its main visible element is an icon instead of a window
41         /// The shell subscribes to the following events:
42         /// * Notification:  Raised by components that want to notify the user. Usually displayed in a balloon
43         /// * 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
44         /// * ShowFilePropertiesEvent: Raised when a shell command requests the display of the file/container properties dialog
45         ///</remarks>           
46         //TODO: CODE SMELL Why does the shell handle the SelectiveSynchChanges?
47     [Export(typeof(IShell))]
48     public class ShellViewModel : Screen, IStatusNotification, IShell,
49         IHandle<Notification>, IHandle<SelectiveSynchChanges>, IHandle<ShowFilePropertiesEvent>
50     {
51                 //The Status Checker provides the current synch state
52                 //TODO: Could we remove the status checker and use events in its place?
53         private IStatusChecker _statusChecker;
54         private IEventAggregator _events;
55
56         public PithosSettings Settings { get; private set; }        
57
58                 
59         private Dictionary<string, PithosMonitor> _monitors = new Dictionary<string, PithosMonitor>();
60                 ///<summary>
61                 /// Dictionary of account monitors, keyed by account
62                 ///</summary>
63                 ///<remarks>
64                 /// One monitor class is created for each account. The Shell needs access to the monitors to execute start/stop/pause commands,
65                 /// retrieve account and boject info            
66                 ///</remarks>
67                 // TODO: Does the Shell REALLY need access to the monitors? Could we achieve the same results with a better design?
68                 // TODO: The monitors should be internal to Pithos.Core, even though exposing them makes coding of the Object and Container windows easier
69         public Dictionary<string, PithosMonitor> Monitors
70         {
71             get { return _monitors; }
72         }
73
74
75                 ///<summary>
76                 /// The status service is used by Shell extensions to retrieve file status information
77                 ///</summary>
78                 //TODO: CODE SMELL! This is the shell! While hosting in the shell makes executing start/stop commands easier, it is still a smell
79         private ServiceHost _statusService { get; set; }
80
81                 //Logging in the Pithos client is provided by log4net
82         private static readonly log4net.ILog Log = log4net.LogManager.GetLogger("Pithos");
83
84                 ///<summary>
85                 /// The Shell depends on MEF to provide implementations for windowManager, events, the status checker service and the settings
86                 ///</summary>
87                 ///<remarks>
88                 /// The PithosSettings class encapsulates the app's settings to abstract their storage mechanism (App settings, a database or registry)
89                 ///</remarks>
90         [ImportingConstructor]          
91         public ShellViewModel(IWindowManager windowManager, IEventAggregator events, IStatusChecker statusChecker, PithosSettings settings)
92         {
93             try
94             {
95
96                 _windowManager = windowManager;
97                                 //CHECK: Caliburn doesn't need explicit command construction
98                 //OpenPithosFolderCommand = new PithosCommand(OpenPithosFolder);
99                 _statusChecker = statusChecker;
100                                 //The event subst
101                 _events = events;
102                 _events.Subscribe(this);
103
104                 Settings = settings;
105
106                 StatusMessage = "In Synch";
107
108                 _accounts.CollectionChanged += (sender, e) =>
109                                                    {
110                                                        NotifyOfPropertyChange(() => OpenFolderCaption);
111                                                        NotifyOfPropertyChange(() => HasAccounts);
112                                                    };
113
114             }
115             catch (Exception exc)
116             {
117                 Log.Error("Error while starting the ShellViewModel",exc);
118                 throw;
119             }
120         }
121
122
123         protected override void OnActivate()
124         {
125             base.OnActivate();
126
127             StartMonitoring();                    
128         }
129
130
131         private async Task StartMonitoring()
132         {
133             try
134             {                
135                 foreach (var account in Settings.Accounts)
136                 {
137                     await MonitorAccount(account);
138                 }
139                 _statusService = StatusService.Start();
140             }
141             catch (AggregateException exc)
142             {
143                 exc.Handle(e =>
144                 {
145                     Log.Error("Error while starting monitoring", e);
146                     return true;
147                 });
148                 throw;
149             }
150         }
151
152         protected override void OnDeactivate(bool close)
153         {
154             base.OnDeactivate(close);
155             if (close)
156             {
157                 StatusService.Stop(_statusService);
158                 _statusService = null;
159             }
160         }
161
162         public Task MonitorAccount(AccountSettings account)
163         {
164             return Task.Factory.StartNew(() =>
165             {                                                
166                 PithosMonitor monitor = null;
167                 var accountName = account.AccountName;
168
169                 if (_monitors.TryGetValue(accountName, out monitor))
170                 {
171                     //If the account is active
172                     if (account.IsActive)
173                         //Start the monitor. It's OK to start an already started monitor,
174                         //it will just ignore the call                        
175                         StartMonitor(monitor).Wait();                        
176                     else
177                     {
178                         //If the account is inactive
179                         //Stop and remove the monitor
180                         RemoveMonitor(accountName);
181                     }
182                     return;
183                 }
184
185                 //Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
186                 monitor = new PithosMonitor
187                               {
188                                   UserName = accountName,
189                                   ApiKey = account.ApiKey,
190                                   UsePithos = account.UsePithos,
191                                   StatusNotification = this,
192                                   RootPath = account.RootPath
193                               };
194                 //PithosMonitor uses MEF so we need to resolve it
195                 IoC.BuildUp(monitor);
196
197                 var appSettings = Properties.Settings.Default;
198                 monitor.AuthenticationUrl = account.UsePithos
199                                                 ? appSettings.PithosAuthenticationUrl
200                                                 : appSettings.CloudfilesAuthenticationUrl;
201
202                 _monitors[accountName] = monitor;
203
204                 if (account.IsActive)
205                 {
206                     //Don't start a monitor if it doesn't have an account and ApiKey
207                     if (String.IsNullOrWhiteSpace(monitor.UserName) ||
208                         String.IsNullOrWhiteSpace(monitor.ApiKey))
209                         return;
210                     StartMonitor(monitor);
211                 }
212             });
213         }
214
215
216         protected override void OnViewLoaded(object view)
217         {
218             UpdateStatus();
219             var window = (Window)view;            
220             TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
221             base.OnViewLoaded(view);
222         }
223
224
225         #region Status Properties
226
227         private string _statusMessage;
228         public string StatusMessage
229         {
230             get { return _statusMessage; }
231             set
232             {
233                 _statusMessage = value;
234                 NotifyOfPropertyChange(() => StatusMessage);
235             }
236         }
237
238         private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
239         public ObservableConcurrentCollection<AccountInfo> Accounts
240         {
241             get { return _accounts; }
242         }
243
244             public bool HasAccounts
245             {
246             get { return _accounts.Count > 0; }
247             }
248
249
250         public string OpenFolderCaption
251         {
252             get
253             {
254                 return (_accounts.Count == 0)
255                         ? "No Accounts Defined"
256                         : "Open Pithos Folder";
257             }
258         }
259
260         private string _pauseSyncCaption="Pause Synching";
261         public string PauseSyncCaption
262         {
263             get { return _pauseSyncCaption; }
264             set
265             {
266                 _pauseSyncCaption = value;
267                 NotifyOfPropertyChange(() => PauseSyncCaption);
268             }
269         }
270
271         private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
272         public ObservableConcurrentCollection<FileEntry> RecentFiles
273         {
274             get { return _recentFiles; }
275         }
276
277
278         private string _statusIcon="../Images/Pithos.ico";
279         public string StatusIcon
280         {
281             get { return _statusIcon; }
282             set
283             {
284                 //_statusIcon = value;
285                 NotifyOfPropertyChange(() => StatusIcon);
286             }
287         }
288
289         #endregion
290
291         #region Commands
292
293         public void ShowPreferences()
294         {
295             Settings.Reload();
296             var preferences = new PreferencesViewModel(_windowManager,_events, this,Settings);            
297             _windowManager.ShowDialog(preferences);
298             
299         }
300
301         public void AboutPithos()
302         {
303             var about = new AboutViewModel();
304             _windowManager.ShowWindow(about);
305         }
306
307         public void SendFeedback()
308         {
309             var feedBack =  IoC.Get<FeedbackViewModel>();
310             _windowManager.ShowWindow(feedBack);
311         }
312
313         //public PithosCommand OpenPithosFolderCommand { get; private set; }
314
315         public void OpenPithosFolder()
316         {
317             var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
318             if (account == null)
319                 return;
320             Process.Start(account.RootPath);
321         }
322
323         public void OpenPithosFolder(AccountInfo account)
324         {
325             Process.Start(account.AccountPath);
326         }
327
328         
329         public void GoToSite()
330         {            
331             var site = Properties.Settings.Default.PithosSite;
332             Process.Start(site);            
333         }
334
335         public void GoToSite(AccountInfo account)
336         {
337             var site = String.Format("{0}/ui/?token={1}&user={2}",
338                 Properties.Settings.Default.PithosSite,account.Token,
339                 account.UserName);
340             Process.Start(site);
341         }
342
343         public void ShowFileProperties()
344         {
345             var account = Settings.Accounts.First(acc => acc.IsActive);            
346             var dir = new DirectoryInfo(account.RootPath + @"\pithos");
347             var files=dir.GetFiles();
348             var r=new Random();
349             var idx=r.Next(0, files.Length);
350             ShowFileProperties(files[idx].FullName);            
351         }
352
353         public void ShowFileProperties(string filePath)
354         {
355             if (String.IsNullOrWhiteSpace(filePath))
356                 throw new ArgumentNullException("filePath");
357             if (!File.Exists(filePath))
358                 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
359             Contract.EndContractBlock();
360
361             var pair=(from monitor in  Monitors
362                                where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
363                                    select monitor).FirstOrDefault();
364             var account = pair.Key;
365             var accountMonitor = pair.Value;
366
367             if (accountMonitor == null)
368                 return;
369
370             var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
371
372             
373
374             var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
375             _windowManager.ShowWindow(fileProperties);
376         } 
377         
378         public void ShowContainerProperties()
379         {
380             var account = Settings.Accounts.First(acc => acc.IsActive);            
381             var dir = new DirectoryInfo(account.RootPath);
382             var fullName = (from folder in dir.EnumerateDirectories()
383                             where (folder.Attributes & FileAttributes.Hidden) == 0
384                             select folder.FullName).First();
385             ShowContainerProperties(fullName);            
386         }
387
388         public void ShowContainerProperties(string filePath)
389         {
390             if (String.IsNullOrWhiteSpace(filePath))
391                 throw new ArgumentNullException("filePath");
392             if (!Directory.Exists(filePath))
393                 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
394             Contract.EndContractBlock();
395
396             var pair=(from monitor in  Monitors
397                                where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
398                                    select monitor).FirstOrDefault();
399             var account = pair.Key;
400             var accountMonitor = pair.Value;            
401             var info = accountMonitor.GetContainerInfo(filePath);
402
403             
404
405             var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
406             _windowManager.ShowWindow(containerProperties);
407         }
408
409         public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
410         {
411             if (currentInfo==null)
412                 throw new ArgumentNullException("currentInfo");
413             Contract.EndContractBlock();
414
415             var monitor = Monitors[currentInfo.Account];
416             var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
417             return newInfo;
418         }
419
420         public ContainerInfo RefreshContainerInfo(ContainerInfo container)
421         {
422             if (container == null)
423                 throw new ArgumentNullException("container");
424             Contract.EndContractBlock();
425
426             var monitor = Monitors[container.Account];
427             var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
428             return newInfo;
429         }
430
431
432         public void ToggleSynching()
433         {
434             bool isPaused=false;
435             foreach (var pair in Monitors)
436             {
437                 var monitor = pair.Value;
438                 monitor.Pause = !monitor.Pause;
439                 isPaused = monitor.Pause;
440             }
441
442             PauseSyncCaption = isPaused ? "Resume syncing" : "Pause syncing";
443             var iconKey = isPaused? "TraySyncPaused" : "TrayInSynch";
444             StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
445         }
446
447         public void ExitPithos()
448         {
449             foreach (var pair in Monitors)
450             {
451                 var monitor = pair.Value;
452                 monitor.Stop();
453             }
454
455             ((Window)GetView()).Close();
456         }
457         #endregion
458
459
460         private Dictionary<PithosStatus, StatusInfo> iconNames = new List<StatusInfo>
461             {
462                 new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
463                 new StatusInfo(PithosStatus.Syncing, "Syncing Files", "TraySynching"),
464                 new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
465             }.ToDictionary(s => s.Status);
466
467         readonly IWindowManager _windowManager;
468
469
470                 ///<summary>
471                 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat                
472                 ///</summary>
473         public void UpdateStatus()
474         {
475             var pithosStatus = _statusChecker.GetPithosStatus();
476
477             if (iconNames.ContainsKey(pithosStatus))
478             {
479                 var info = iconNames[pithosStatus];
480                 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
481
482                 Assembly assembly = Assembly.GetExecutingAssembly();                               
483                 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
484
485
486                 StatusMessage = String.Format("Pithos {0}\r\n{1}", fileVersion.FileVersion,info.StatusText);
487             }
488             
489             _events.Publish(new Notification { Title = "Start", Message = "Start Monitoring", Level = TraceLevel.Info});
490         }
491
492
493        
494         private Task StartMonitor(PithosMonitor monitor,int retries=0)
495         {
496             return Task.Factory.StartNew(() =>
497             {
498                 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
499                 {
500                     try
501                     {
502                         Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
503
504                         monitor.Start();
505                     }
506                     catch (WebException exc)
507                     {
508                         if (AbandonRetry(monitor, retries))
509                             return;
510
511                         if (IsUnauthorized(exc))
512                         {
513                             var message = String.Format("API Key Expired for {0}. Starting Renewal",monitor.UserName);                            
514                             Log.Error(message,exc);
515                             TryAuthorize(monitor,retries).Wait();
516                         }
517                         else
518                         {
519                             TryLater(monitor, exc,retries);
520                         }
521                     }
522                     catch (Exception exc)
523                     {
524                         if (AbandonRetry(monitor, retries)) 
525                             return;
526
527                         TryLater(monitor,exc,retries);
528                     }
529                 }
530             });
531         }
532
533         private bool AbandonRetry(PithosMonitor monitor, int retries)
534         {
535             if (retries > 1)
536             {
537                 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
538                                             monitor.UserName);
539                 _events.Publish(new Notification
540                                     {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
541                 return true;
542             }
543             return false;
544         }
545
546
547         private async Task TryAuthorize(PithosMonitor monitor,int retries)
548         {
549             _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 });
550
551             try
552             {
553
554                 var credentials = await PithosAccount.RetrieveCredentials(Settings.PithosLoginUrl);
555
556                 var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
557                 account.ApiKey = credentials.Password;
558                 monitor.ApiKey = credentials.Password;
559                 Settings.Save();
560                 await TaskEx.Delay(10000);
561                 StartMonitor(monitor, retries + 1);
562                 NotifyOfPropertyChange(()=>Accounts);
563             }
564             catch (AggregateException exc)
565             {
566                 string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
567                 Log.Error(message, exc.InnerException);
568                 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
569                 return;
570             }
571             catch (Exception exc)
572             {
573                 string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
574                 Log.Error(message, exc);
575                 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
576                 return;
577                 
578             }
579
580         }
581
582         private static bool IsUnauthorized(WebException exc)
583         {
584             if (exc==null)
585                 throw new ArgumentNullException("exc");
586             Contract.EndContractBlock();
587
588             var response = exc.Response as HttpWebResponse;
589             if (response == null)
590                 return false;
591             return (response.StatusCode == HttpStatusCode.Unauthorized);
592         }
593
594         private void TryLater(PithosMonitor monitor, Exception exc,int retries)
595         {
596             var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
597             Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
598             _events.Publish(new Notification
599                                 {Title = "Error", Message = message, Level = TraceLevel.Error});
600             Log.Error(message, exc);
601         }
602
603
604         public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
605         {
606             this.StatusMessage = status;
607             
608             _events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
609         }
610
611         public void NotifyChangedFile(string filePath)
612         {
613             var entry = new FileEntry {FullPath=filePath};
614             IProducerConsumerCollection<FileEntry> files=this.RecentFiles;
615             FileEntry popped;
616             while (files.Count > 5)
617                 files.TryTake(out popped);
618             files.TryAdd(entry);
619         }
620
621         public void NotifyAccount(AccountInfo account)
622         {
623             if (account== null)
624                 return;
625
626             account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
627                 Properties.Settings.Default.PithosSite, account.Token,
628                 account.UserName);
629
630             IProducerConsumerCollection<AccountInfo> accounts = Accounts;
631             for (var i = 0; i < _accounts.Count; i++)
632             {
633                 AccountInfo item;
634                 if (accounts.TryTake(out item))
635                 {
636                     if (item.UserName!=account.UserName)
637                     {
638                         accounts.TryAdd(item);
639                     }
640                 }
641             }
642
643             accounts.TryAdd(account);
644         }
645
646
647         public void RemoveMonitor(string accountName)
648         {
649             if (String.IsNullOrWhiteSpace(accountName))
650                 return;
651
652             var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName);
653             _accounts.TryRemove(accountInfo);
654
655             PithosMonitor monitor;
656             if (Monitors.TryGetValue(accountName, out monitor))
657             {
658                 Monitors.Remove(accountName);
659                 monitor.Stop();
660             }
661         }
662
663         public void RefreshOverlays()
664         {
665             foreach (var pair in Monitors)
666             {
667                 var monitor = pair.Value;
668
669                 var path = monitor.RootPath;
670
671                 if (String.IsNullOrWhiteSpace(path))
672                     continue;
673
674                 if (!Directory.Exists(path) && !File.Exists(path))
675                     continue;
676
677                 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
678
679                 try
680                 {
681                     NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
682                                                  HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
683                                                  pathPointer, IntPtr.Zero);
684                 }
685                 finally
686                 {
687                     Marshal.FreeHGlobal(pathPointer);
688                 }
689             }
690         }
691
692         #region Event Handlers
693         
694         public void Handle(SelectiveSynchChanges message)
695         {
696             var accountName = message.Account.AccountName;
697             PithosMonitor monitor;
698             if (_monitors.TryGetValue(accountName, out monitor))
699             {
700                 monitor.AddSelectivePaths(message.Added);
701                 monitor.RemoveSelectivePaths(message.Removed);
702
703             }
704             
705         }
706
707
708         public void Handle(Notification notification)
709         {
710             if (!Settings.ShowDesktopNotifications)
711                 return;
712             BalloonIcon icon = BalloonIcon.None;
713             switch (notification.Level)
714             {
715                 case TraceLevel.Error:
716                     icon = BalloonIcon.Error;
717                     break;
718                 case TraceLevel.Info:
719                 case TraceLevel.Verbose:
720                     icon = BalloonIcon.Info;
721                     break;
722                 case TraceLevel.Warning:
723                     icon = BalloonIcon.Warning;
724                     break;
725                 default:
726                     icon = BalloonIcon.None;
727                     break;
728             }
729
730             if (Settings.ShowDesktopNotifications)
731             {
732                 var tv = (ShellView) this.GetView();
733                 tv.TaskbarView.ShowBalloonTip(notification.Title, notification.Message, icon);
734             }
735         }
736         #endregion
737
738         public void Handle(ShowFilePropertiesEvent message)
739         {
740             if (message == null)
741                 throw new ArgumentNullException("message");
742             if (String.IsNullOrWhiteSpace(message.FileName) )
743                 throw new ArgumentException("message");
744             Contract.EndContractBlock();
745
746             var fileName = message.FileName;
747
748             if (File.Exists(fileName))
749                 this.ShowFileProperties(fileName);
750             else if (Directory.Exists(fileName))
751                 this.ShowContainerProperties(fileName);
752         }
753     }
754 }