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