Finished account wizard that allows adding an account either by logging to the Pithos...
[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             }
109             catch (Exception exc)
110             {
111                 Log.Error("Error while starting the ShellViewModel",exc);
112                 throw;
113             }
114         }
115
116         protected override void OnActivate()
117         {
118             base.OnActivate();
119
120             StartMonitoring();                    
121         }
122
123
124         private async Task StartMonitoring()
125         {
126             try
127             {                
128                 foreach (var account in Settings.Accounts)
129                 {
130                     await MonitorAccount(account);
131                 }
132                 _statusService = StatusService.Start();
133             }
134             catch (AggregateException exc)
135             {
136                 exc.Handle(e =>
137                 {
138                     Log.Error("Error while starting monitoring", e);
139                     return true;
140                 });
141                 throw;
142             }
143         }
144
145         protected override void OnDeactivate(bool close)
146         {
147             base.OnDeactivate(close);
148             if (close)
149             {
150                 StatusService.Stop(_statusService);
151                 _statusService = null;
152             }
153         }
154
155         public Task MonitorAccount(AccountSettings account)
156         {
157             return Task.Factory.StartNew(() =>
158             {                                                
159                 PithosMonitor monitor = null;
160                 var accountName = account.AccountName;
161
162                 if (_monitors.TryGetValue(accountName, out monitor))
163                 {
164                     //If the account is active
165                     if (account.IsActive)
166                         //Start the monitor. It's OK to start an already started monitor,
167                         //it will just ignore the call
168                         monitor.Start();
169                     else
170                     {
171                         //If the account is inactive
172                         //Stop and remove the monitor
173                         RemoveMonitor(accountName);
174                     }
175                     return;
176                 }
177
178                 //Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
179                 monitor = new PithosMonitor
180                               {
181                                   UserName = accountName,
182                                   ApiKey = account.ApiKey,
183                                   UsePithos = account.UsePithos,
184                                   StatusNotification = this,
185                                   RootPath = account.RootPath
186                               };
187                 //PithosMonitor uses MEF so we need to resolve it
188                 IoC.BuildUp(monitor);
189
190                 var appSettings = Properties.Settings.Default;
191                 monitor.AuthenticationUrl = account.UsePithos
192                                                 ? appSettings.PithosAuthenticationUrl
193                                                 : appSettings.CloudfilesAuthenticationUrl;
194
195                 _monitors[accountName] = monitor;
196
197                 if (account.IsActive)
198                 {
199                     //Don't start a monitor if it doesn't have an account and ApiKey
200                     if (String.IsNullOrWhiteSpace(monitor.UserName) ||
201                         String.IsNullOrWhiteSpace(monitor.ApiKey))
202                         return;
203                     StartMonitor(monitor);
204                 }
205             });
206         }
207
208
209         protected override void OnViewLoaded(object view)
210         {
211             var window = (Window)view;
212             window.Hide();
213             UpdateStatus();
214             base.OnViewLoaded(view);
215         }
216
217
218         #region Status Properties
219
220         private string _statusMessage;
221         public string StatusMessage
222         {
223             get { return _statusMessage; }
224             set
225             {
226                 _statusMessage = value;
227                 NotifyOfPropertyChange(() => StatusMessage);
228             }
229         }
230
231         private ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
232         public ObservableConcurrentCollection<AccountInfo> Accounts
233         {
234             get { return _accounts; }
235         }
236
237
238         private string _pauseSyncCaption="Pause Syncing";
239         public string PauseSyncCaption
240         {
241             get { return _pauseSyncCaption; }
242             set
243             {
244                 _pauseSyncCaption = value;
245                 NotifyOfPropertyChange(() => PauseSyncCaption);
246             }
247         }
248
249         private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
250         public ObservableConcurrentCollection<FileEntry> RecentFiles
251         {
252             get { return _recentFiles; }
253         }
254
255
256         private string _statusIcon="../Images/Tray.ico";
257         public string StatusIcon
258         {
259             get { return _statusIcon; }
260             set
261             {
262                 _statusIcon = value;
263                 NotifyOfPropertyChange(() => StatusIcon);
264             }
265         }
266
267         #endregion
268
269         #region Commands
270
271         public void ShowPreferences()
272         {
273             Settings.Reload();
274             var preferences = new PreferencesViewModel(_windowManager,_events, this,Settings);            
275             _windowManager.ShowDialog(preferences);
276             
277         }
278
279         public void AboutPithos()
280         {
281             var about = new AboutViewModel();
282             _windowManager.ShowWindow(about);
283         }
284
285         public void SendFeedback()
286         {
287             var feedBack =  IoC.Get<FeedbackViewModel>();
288             _windowManager.ShowWindow(feedBack);
289         }
290
291         //public PithosCommand OpenPithosFolderCommand { get; private set; }
292
293         public void OpenPithosFolder()
294         {
295             var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
296             if (account == null)
297                 return;
298             Process.Start(account.RootPath);
299         }
300
301         public void OpenPithosFolder(AccountInfo account)
302         {
303             Process.Start(account.AccountPath);
304         }
305
306         
307         public void GoToSite(AccountInfo account)
308         {
309             var site = String.Format("{0}/ui/?token={1}&user={2}",
310                 Properties.Settings.Default.PithosSite,account.Token,
311                 account.UserName);
312             Process.Start(site);
313         }
314
315         public void ShowFileProperties()
316         {
317             var account = Settings.Accounts.First(acc => acc.IsActive);            
318             var dir = new DirectoryInfo(account.RootPath + @"\pithos");
319             var files=dir.GetFiles();
320             var r=new Random();
321             var idx=r.Next(0, files.Length);
322             ShowFileProperties(files[idx].FullName);            
323         }
324
325         public void ShowFileProperties(string filePath)
326         {
327             if (String.IsNullOrWhiteSpace(filePath))
328                 throw new ArgumentNullException("filePath");
329             if (!File.Exists(filePath))
330                 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
331             Contract.EndContractBlock();
332
333             var pair=(from monitor in  Monitors
334                                where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
335                                    select monitor).FirstOrDefault();
336             var account = pair.Key;
337             var accountMonitor = pair.Value;
338
339             if (accountMonitor == null)
340                 return;
341
342             var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
343
344             
345
346             var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
347             _windowManager.ShowWindow(fileProperties);
348         } 
349         
350         public void ShowContainerProperties()
351         {
352             var account = Settings.Accounts.First(acc => acc.IsActive);            
353             var dir = new DirectoryInfo(account.RootPath);
354             var fullName = (from folder in dir.EnumerateDirectories()
355                             where (folder.Attributes & FileAttributes.Hidden) == 0
356                             select folder.FullName).First();
357             ShowContainerProperties(fullName);            
358         }
359
360         public void ShowContainerProperties(string filePath)
361         {
362             if (String.IsNullOrWhiteSpace(filePath))
363                 throw new ArgumentNullException("filePath");
364             if (!Directory.Exists(filePath))
365                 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
366             Contract.EndContractBlock();
367
368             var pair=(from monitor in  Monitors
369                                where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
370                                    select monitor).FirstOrDefault();
371             var account = pair.Key;
372             var accountMonitor = pair.Value;            
373             var info = accountMonitor.GetContainerInfo(filePath);
374
375             
376
377             var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
378             _windowManager.ShowWindow(containerProperties);
379         }
380
381         public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
382         {
383             if (currentInfo==null)
384                 throw new ArgumentNullException("currentInfo");
385             Contract.EndContractBlock();
386
387             var monitor = Monitors[currentInfo.Account];
388             var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
389             return newInfo;
390         }
391
392         public ContainerInfo RefreshContainerInfo(ContainerInfo container)
393         {
394             if (container == null)
395                 throw new ArgumentNullException("container");
396             Contract.EndContractBlock();
397
398             var monitor = Monitors[container.Account];
399             var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
400             return newInfo;
401         }
402
403
404         public void ToggleSynching()
405         {
406             bool isPaused=false;
407             foreach (var pair in Monitors)
408             {
409                 var monitor = pair.Value;
410                 monitor.Pause = !monitor.Pause;
411                 isPaused = monitor.Pause;
412             }
413
414             PauseSyncCaption = isPaused ? "Resume syncing" : "Pause syncing";
415             var iconKey = isPaused? "TraySyncPaused" : "TrayInSynch";
416             StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
417         }
418
419         public void ExitPithos()
420         {
421             foreach (var pair in Monitors)
422             {
423                 var monitor = pair.Value;
424                 monitor.Stop();
425             }
426
427             ((Window)GetView()).Close();
428         }
429         #endregion
430
431
432         private Dictionary<PithosStatus, StatusInfo> iconNames = new List<StatusInfo>
433             {
434                 new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
435                 new StatusInfo(PithosStatus.Syncing, "Syncing Files", "TraySynching"),
436                 new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
437             }.ToDictionary(s => s.Status);
438
439         readonly IWindowManager _windowManager;
440
441
442                 ///<summary>
443                 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat                
444                 ///</summary>
445         public void UpdateStatus()
446         {
447             var pithosStatus = _statusChecker.GetPithosStatus();
448
449             if (iconNames.ContainsKey(pithosStatus))
450             {
451                 var info = iconNames[pithosStatus];
452                 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
453
454                 Assembly assembly = Assembly.GetExecutingAssembly();                               
455                 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
456
457
458                 StatusMessage = String.Format("Pithos {0}\r\n{1}", fileVersion.FileVersion,info.StatusText);
459             }
460             
461             _events.Publish(new Notification { Title = "Start", Message = "Start Monitoring", Level = TraceLevel.Info});
462         }
463
464
465        
466         private Task StartMonitor(PithosMonitor monitor,int retries=0)
467         {
468             return Task.Factory.StartNew(() =>
469             {
470                 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
471                 {
472                     try
473                     {
474                         Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
475
476                         monitor.Start();
477                     }
478                     catch (WebException exc)
479                     {
480                         if (AbandonRetry(monitor, retries))
481                             return;
482
483                         if (IsUnauthorized(exc))
484                         {
485                             var message = String.Format("API Key Expired for {0}. Starting Renewal",monitor.UserName);                            
486                             Log.Error(message,exc);
487                             TryAuthorize(monitor,retries).Wait();
488                         }
489                         else
490                         {
491                             TryLater(monitor, exc,retries);
492                         }
493                     }
494                     catch (Exception exc)
495                     {
496                         if (AbandonRetry(monitor, retries)) 
497                             return;
498
499                         TryLater(monitor,exc,retries);
500                     }
501                 }
502             });
503         }
504
505         private bool AbandonRetry(PithosMonitor monitor, int retries)
506         {
507             if (retries > 1)
508             {
509                 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
510                                             monitor.UserName);
511                 _events.Publish(new Notification
512                                     {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
513                 return true;
514             }
515             return false;
516         }
517
518
519         private async Task TryAuthorize(PithosMonitor monitor,int retries)
520         {
521             _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 });
522
523             try
524             {
525
526                 var credentials = await PithosAccount.RetrieveCredentialsAsync(Settings.PithosLoginUrl);
527
528                 var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
529                 account.ApiKey = credentials.Password;
530                 monitor.ApiKey = credentials.Password;
531                 Settings.Save();
532                 await TaskEx.Delay(10000);
533                 StartMonitor(monitor, retries + 1);
534                 NotifyOfPropertyChange(()=>Accounts);
535             }
536             catch (AggregateException exc)
537             {
538                 string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
539                 Log.Error(message, exc.InnerException);
540                 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
541                 return;
542             }
543             catch (Exception exc)
544             {
545                 string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
546                 Log.Error(message, exc);
547                 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
548                 return;
549                 
550             }
551
552         }
553
554         private static bool IsUnauthorized(WebException exc)
555         {
556             if (exc==null)
557                 throw new ArgumentNullException("exc");
558             Contract.EndContractBlock();
559
560             var response = exc.Response as HttpWebResponse;
561             if (response == null)
562                 return false;
563             return (response.StatusCode == HttpStatusCode.Unauthorized);
564         }
565
566         private void TryLater(PithosMonitor monitor, Exception exc,int retries)
567         {
568             var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
569             Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
570             _events.Publish(new Notification
571                                 {Title = "Error", Message = message, Level = TraceLevel.Error});
572             Log.Error(message, exc);
573         }
574
575
576         public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
577         {
578             this.StatusMessage = status;
579             
580             _events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
581         }
582
583         public void NotifyChangedFile(string filePath)
584         {
585             var entry = new FileEntry {FullPath=filePath};
586             IProducerConsumerCollection<FileEntry> files=this.RecentFiles;
587             FileEntry popped;
588             while (files.Count > 5)
589                 files.TryTake(out popped);
590             files.TryAdd(entry);
591         }
592
593         public void NotifyAccount(AccountInfo account)
594         {
595             if (account== null)
596                 return;
597
598             account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
599                 Properties.Settings.Default.PithosSite, account.Token,
600                 account.UserName);
601
602             IProducerConsumerCollection<AccountInfo> accounts = Accounts;
603             for (var i = 0; i < _accounts.Count; i++)
604             {
605                 AccountInfo item;
606                 if (accounts.TryTake(out item))
607                 {
608                     if (item.UserName!=account.UserName)
609                     {
610                         accounts.TryAdd(item);
611                     }
612                 }
613             }
614
615             accounts.TryAdd(account);
616         }
617
618
619         public void RemoveMonitor(string accountName)
620         {
621             if (String.IsNullOrWhiteSpace(accountName))
622                 return;
623
624             PithosMonitor monitor;
625             if (Monitors.TryGetValue(accountName, out monitor))
626             {
627                 Monitors.Remove(accountName);
628                 monitor.Stop();
629             }
630         }
631
632         public void RefreshOverlays()
633         {
634             foreach (var pair in Monitors)
635             {
636                 var monitor = pair.Value;
637
638                 var path = monitor.RootPath;
639
640                 if (String.IsNullOrWhiteSpace(path))
641                     continue;
642
643                 if (!Directory.Exists(path) && !File.Exists(path))
644                     continue;
645
646                 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
647
648                 try
649                 {
650                     NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
651                                                  HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
652                                                  pathPointer, IntPtr.Zero);
653                 }
654                 finally
655                 {
656                     Marshal.FreeHGlobal(pathPointer);
657                 }
658             }
659         }
660
661         #region Event Handlers
662         
663         public void Handle(SelectiveSynchChanges message)
664         {
665             var accountName = message.Account.AccountName;
666             PithosMonitor monitor;
667             if (_monitors.TryGetValue(accountName, out monitor))
668             {
669                 monitor.AddSelectivePaths(message.Added);
670                 monitor.RemoveSelectivePaths(message.Removed);
671
672             }
673             
674         }
675
676
677         public void Handle(Notification notification)
678         {
679             if (!Settings.ShowDesktopNotifications)
680                 return;
681             BalloonIcon icon = BalloonIcon.None;
682             switch (notification.Level)
683             {
684                 case TraceLevel.Error:
685                     icon = BalloonIcon.Error;
686                     break;
687                 case TraceLevel.Info:
688                 case TraceLevel.Verbose:
689                     icon = BalloonIcon.Info;
690                     break;
691                 case TraceLevel.Warning:
692                     icon = BalloonIcon.Warning;
693                     break;
694                 default:
695                     icon = BalloonIcon.None;
696                     break;
697             }
698
699             if (Settings.ShowDesktopNotifications)
700             {
701                 var tv = (ShellView) this.GetView();
702                 tv.TaskbarView.ShowBalloonTip(notification.Title, notification.Message, icon);
703             }
704         }
705         #endregion
706
707         public void Handle(ShowFilePropertiesEvent message)
708         {
709             if (message == null)
710                 throw new ArgumentNullException("message");
711             if (String.IsNullOrWhiteSpace(message.FileName) )
712                 throw new ArgumentException("message");
713             Contract.EndContractBlock();
714
715             var fileName = message.FileName;
716
717             if (File.Exists(fileName))
718                 this.ShowFileProperties(fileName);
719             else if (Directory.Exists(fileName))
720                 this.ShowContainerProperties(fileName);
721         }
722     }
723 }