1 using System.Collections.Concurrent;
2 using System.ComponentModel;
3 using System.ComponentModel.Composition;
4 using System.Diagnostics;
5 using System.Diagnostics.Contracts;
8 using System.Reflection;
9 using System.Runtime.InteropServices;
10 using System.ServiceModel;
11 using System.ServiceModel.Description;
12 using System.Threading.Tasks;
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;
23 using Pithos.Interfaces;
25 using System.Collections.Generic;
29 using StatusService = Pithos.Client.WPF.Services.StatusService;
31 namespace Pithos.Client.WPF {
32 using System.ComponentModel.Composition;
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
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
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>
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;
56 public PithosSettings Settings { get; private set; }
59 private Dictionary<string, PithosMonitor> _monitors = new Dictionary<string, PithosMonitor>();
61 /// Dictionary of account monitors, keyed by account
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
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
71 get { return _monitors; }
76 /// The status service is used by Shell extensions to retrieve file status information
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; }
81 //Logging in the Pithos client is provided by log4net
82 private static readonly log4net.ILog Log = log4net.LogManager.GetLogger("Pithos");
85 /// The Shell depends on MEF to provide implementations for windowManager, events, the status checker service and the settings
88 /// The PithosSettings class encapsulates the app's settings to abstract their storage mechanism (App settings, a database or registry)
90 [ImportingConstructor]
91 public ShellViewModel(IWindowManager windowManager, IEventAggregator events, IStatusChecker statusChecker, PithosSettings settings)
96 _windowManager = windowManager;
97 //CHECK: Caliburn doesn't need explicit command construction
98 //OpenPithosFolderCommand = new PithosCommand(OpenPithosFolder);
99 _statusChecker = statusChecker;
102 _events.Subscribe(this);
106 StatusMessage = "In Synch";
108 _accounts.CollectionChanged += (sender, e) =>
110 NotifyOfPropertyChange(() => OpenFolderCaption);
111 NotifyOfPropertyChange(() => HasAccounts);
115 catch (Exception exc)
117 Log.Error("Error while starting the ShellViewModel",exc);
123 protected override void OnActivate()
131 private async Task StartMonitoring()
135 if (Settings.Accounts == null)
137 Settings.Accounts=new AccountsCollection();
142 foreach (var account in Settings.Accounts)
144 await MonitorAccount(account);
146 _statusService = StatusService.Start();
148 catch (AggregateException exc)
152 Log.Error("Error while starting monitoring", e);
159 protected override void OnDeactivate(bool close)
161 base.OnDeactivate(close);
164 StatusService.Stop(_statusService);
165 _statusService = null;
169 public Task MonitorAccount(AccountSettings account)
171 return Task.Factory.StartNew(() =>
173 PithosMonitor monitor = null;
174 var accountName = account.AccountName;
176 if (_monitors.TryGetValue(accountName, out monitor))
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();
185 //If the account is inactive
186 //Stop and remove the monitor
187 RemoveMonitor(accountName);
192 //Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
193 monitor = new PithosMonitor
195 UserName = accountName,
196 ApiKey = account.ApiKey,
197 StatusNotification = this,
198 RootPath = account.RootPath
200 //PithosMonitor uses MEF so we need to resolve it
201 IoC.BuildUp(monitor);
203 var appSettings = Properties.Settings.Default;
204 monitor.AuthenticationUrl = account.ServerUrl;
206 _monitors[accountName] = monitor;
208 if (account.IsActive)
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))
214 StartMonitor(monitor);
220 protected override void OnViewLoaded(object view)
223 var window = (Window)view;
224 TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
225 base.OnViewLoaded(view);
229 #region Status Properties
231 private string _statusMessage;
232 public string StatusMessage
234 get { return _statusMessage; }
237 _statusMessage = value;
238 NotifyOfPropertyChange(() => StatusMessage);
242 private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
243 public ObservableConcurrentCollection<AccountInfo> Accounts
245 get { return _accounts; }
248 public bool HasAccounts
250 get { return _accounts.Count > 0; }
254 public string OpenFolderCaption
258 return (_accounts.Count == 0)
259 ? "No Accounts Defined"
260 : "Open Pithos Folder";
264 private string _pauseSyncCaption="Pause Synching";
265 public string PauseSyncCaption
267 get { return _pauseSyncCaption; }
270 _pauseSyncCaption = value;
271 NotifyOfPropertyChange(() => PauseSyncCaption);
275 private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
276 public ObservableConcurrentCollection<FileEntry> RecentFiles
278 get { return _recentFiles; }
282 private string _statusIcon="../Images/Pithos.ico";
283 public string StatusIcon
285 get { return _statusIcon; }
288 //_statusIcon = value;
289 NotifyOfPropertyChange(() => StatusIcon);
297 public void ShowPreferences()
300 var preferences = new PreferencesViewModel(_windowManager,_events, this,Settings);
301 _windowManager.ShowDialog(preferences);
305 public void AboutPithos()
307 var about = new AboutViewModel();
308 _windowManager.ShowWindow(about);
311 public void SendFeedback()
313 var feedBack = IoC.Get<FeedbackViewModel>();
314 _windowManager.ShowWindow(feedBack);
317 //public PithosCommand OpenPithosFolderCommand { get; private set; }
319 public void OpenPithosFolder()
321 var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
324 Process.Start(account.RootPath);
327 public void OpenPithosFolder(AccountInfo account)
329 Process.Start(account.AccountPath);
334 public void GoToSite()
336 var site = Properties.Settings.Default.PithosSite;
341 public void GoToSite(AccountInfo account)
343 var site = String.Format("{0}/ui/?token={1}&user={2}",
344 account.SiteUri,account.Token,
349 public void ShowFileProperties()
351 var account = Settings.Accounts.First(acc => acc.IsActive);
352 var dir = new DirectoryInfo(account.RootPath + @"\pithos");
353 var files=dir.GetFiles();
355 var idx=r.Next(0, files.Length);
356 ShowFileProperties(files[idx].FullName);
359 public void ShowFileProperties(string filePath)
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();
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;
373 if (accountMonitor == null)
376 var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
380 var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
381 _windowManager.ShowWindow(fileProperties);
384 public void ShowContainerProperties()
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);
394 public void ShowContainerProperties(string filePath)
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();
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);
411 var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
412 _windowManager.ShowWindow(containerProperties);
415 public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
417 if (currentInfo==null)
418 throw new ArgumentNullException("currentInfo");
419 Contract.EndContractBlock();
421 var monitor = Monitors[currentInfo.Account];
422 var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
426 public ContainerInfo RefreshContainerInfo(ContainerInfo container)
428 if (container == null)
429 throw new ArgumentNullException("container");
430 Contract.EndContractBlock();
432 var monitor = Monitors[container.Account];
433 var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
438 public void ToggleSynching()
441 foreach (var pair in Monitors)
443 var monitor = pair.Value;
444 monitor.Pause = !monitor.Pause;
445 isPaused = monitor.Pause;
448 PauseSyncCaption = isPaused ? "Resume syncing" : "Pause syncing";
449 var iconKey = isPaused? "TraySyncPaused" : "TrayInSynch";
450 StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
453 public void ExitPithos()
455 foreach (var pair in Monitors)
457 var monitor = pair.Value;
461 ((Window)GetView()).Close();
466 private Dictionary<PithosStatus, StatusInfo> iconNames = new List<StatusInfo>
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);
473 readonly IWindowManager _windowManager;
477 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat
479 public void UpdateStatus()
481 var pithosStatus = _statusChecker.GetPithosStatus();
483 if (iconNames.ContainsKey(pithosStatus))
485 var info = iconNames[pithosStatus];
486 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
488 Assembly assembly = Assembly.GetExecutingAssembly();
489 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
492 StatusMessage = String.Format("Pithos {0}\r\n{1}", fileVersion.FileVersion,info.StatusText);
495 _events.Publish(new Notification { Title = "Start", Message = "Start Monitoring", Level = TraceLevel.Info});
500 private Task StartMonitor(PithosMonitor monitor,int retries=0)
502 return Task.Factory.StartNew(() =>
504 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
508 Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
512 catch (WebException exc)
514 if (AbandonRetry(monitor, retries))
517 if (IsUnauthorized(exc))
519 var message = String.Format("API Key Expired for {0}. Starting Renewal",monitor.UserName);
520 Log.Error(message,exc);
521 TryAuthorize(monitor,retries).Wait();
525 TryLater(monitor, exc,retries);
528 catch (Exception exc)
530 if (AbandonRetry(monitor, retries))
533 TryLater(monitor,exc,retries);
539 private bool AbandonRetry(PithosMonitor monitor, int retries)
543 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
545 _events.Publish(new Notification
546 {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
553 private async Task TryAuthorize(PithosMonitor monitor,int retries)
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 });
560 var credentials = await PithosAccount.RetrieveCredentials(Settings.PithosLoginUrl);
562 var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
563 account.ApiKey = credentials.Password;
564 monitor.ApiKey = credentials.Password;
566 await TaskEx.Delay(10000);
567 StartMonitor(monitor, retries + 1);
568 NotifyOfPropertyChange(()=>Accounts);
570 catch (AggregateException exc)
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 });
577 catch (Exception exc)
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 });
588 private static bool IsUnauthorized(WebException exc)
591 throw new ArgumentNullException("exc");
592 Contract.EndContractBlock();
594 var response = exc.Response as HttpWebResponse;
595 if (response == null)
597 return (response.StatusCode == HttpStatusCode.Unauthorized);
600 private void TryLater(PithosMonitor monitor, Exception exc,int retries)
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);
610 public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
612 this.StatusMessage = status;
614 _events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
617 public void NotifyChangedFile(string filePath)
619 var entry = new FileEntry {FullPath=filePath};
620 IProducerConsumerCollection<FileEntry> files=this.RecentFiles;
622 while (files.Count > 5)
623 files.TryTake(out popped);
627 public void NotifyAccount(AccountInfo account)
632 account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
633 account.SiteUri, account.Token,
636 IProducerConsumerCollection<AccountInfo> accounts = Accounts;
637 for (var i = 0; i < _accounts.Count; i++)
640 if (accounts.TryTake(out item))
642 if (item.UserName!=account.UserName)
644 accounts.TryAdd(item);
649 accounts.TryAdd(account);
653 public void RemoveMonitor(string accountName)
655 if (String.IsNullOrWhiteSpace(accountName))
658 var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName);
659 _accounts.TryRemove(accountInfo);
661 PithosMonitor monitor;
662 if (Monitors.TryGetValue(accountName, out monitor))
664 Monitors.Remove(accountName);
669 public void RefreshOverlays()
671 foreach (var pair in Monitors)
673 var monitor = pair.Value;
675 var path = monitor.RootPath;
677 if (String.IsNullOrWhiteSpace(path))
680 if (!Directory.Exists(path) && !File.Exists(path))
683 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
687 NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
688 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
689 pathPointer, IntPtr.Zero);
693 Marshal.FreeHGlobal(pathPointer);
698 #region Event Handlers
700 public void Handle(SelectiveSynchChanges message)
702 var accountName = message.Account.AccountName;
703 PithosMonitor monitor;
704 if (_monitors.TryGetValue(accountName, out monitor))
706 monitor.AddSelectivePaths(message.Added);
707 monitor.RemoveSelectivePaths(message.Removed);
714 public void Handle(Notification notification)
716 if (!Settings.ShowDesktopNotifications)
718 BalloonIcon icon = BalloonIcon.None;
719 switch (notification.Level)
721 case TraceLevel.Error:
722 icon = BalloonIcon.Error;
724 case TraceLevel.Info:
725 case TraceLevel.Verbose:
726 icon = BalloonIcon.Info;
728 case TraceLevel.Warning:
729 icon = BalloonIcon.Warning;
732 icon = BalloonIcon.None;
736 if (Settings.ShowDesktopNotifications)
738 var tv = (ShellView) this.GetView();
739 tv.TaskbarView.ShowBalloonTip(notification.Title, notification.Message, icon);
744 public void Handle(ShowFilePropertiesEvent message)
747 throw new ArgumentNullException("message");
748 if (String.IsNullOrWhiteSpace(message.FileName) )
749 throw new ArgumentException("message");
750 Contract.EndContractBlock();
752 var fileName = message.FileName;
754 if (File.Exists(fileName))
755 this.ShowFileProperties(fileName);
756 else if (Directory.Exists(fileName))
757 this.ShowContainerProperties(fileName);