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 ConcurrentDictionary<string, PithosMonitor> _monitors = new ConcurrentDictionary<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 ConcurrentDictionary<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 var accounts = Settings.Accounts.Select(MonitorAccount);
136 await TaskEx.WhenAll(accounts);
137 _statusService = StatusService.Start();
140 foreach (var account in Settings.Accounts)
142 await MonitorAccount(account);
147 catch (AggregateException exc)
151 Log.Error("Error while starting monitoring", e);
158 protected override void OnDeactivate(bool close)
160 base.OnDeactivate(close);
163 StatusService.Stop(_statusService);
164 _statusService = null;
168 public Task MonitorAccount(AccountSettings account)
170 return Task.Factory.StartNew(() =>
172 PithosMonitor monitor = null;
173 var accountName = account.AccountName;
175 if (_monitors.TryGetValue(accountName, out monitor))
177 //If the account is active
178 if (account.IsActive)
179 //Start the monitor. It's OK to start an already started monitor,
180 //it will just ignore the call
181 StartMonitor(monitor).Wait();
184 //If the account is inactive
185 //Stop and remove the monitor
186 RemoveMonitor(accountName);
191 //Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
192 monitor = new PithosMonitor
194 UserName = accountName,
195 ApiKey = account.ApiKey,
196 StatusNotification = this,
197 RootPath = account.RootPath
199 //PithosMonitor uses MEF so we need to resolve it
200 IoC.BuildUp(monitor);
202 var appSettings = Properties.Settings.Default;
203 monitor.AuthenticationUrl = account.ServerUrl;
205 _monitors[accountName] = monitor;
207 if (account.IsActive)
209 //Don't start a monitor if it doesn't have an account and ApiKey
210 if (String.IsNullOrWhiteSpace(monitor.UserName) ||
211 String.IsNullOrWhiteSpace(monitor.ApiKey))
213 StartMonitor(monitor);
219 protected override void OnViewLoaded(object view)
222 var window = (Window)view;
223 TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
224 base.OnViewLoaded(view);
228 #region Status Properties
230 private string _statusMessage;
231 public string StatusMessage
233 get { return _statusMessage; }
236 _statusMessage = value;
237 NotifyOfPropertyChange(() => StatusMessage);
241 private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
242 public ObservableConcurrentCollection<AccountInfo> Accounts
244 get { return _accounts; }
247 public bool HasAccounts
249 get { return _accounts.Count > 0; }
253 public string OpenFolderCaption
257 return (_accounts.Count == 0)
258 ? "No Accounts Defined"
259 : "Open Pithos Folder";
263 private string _pauseSyncCaption="Pause Synching";
264 public string PauseSyncCaption
266 get { return _pauseSyncCaption; }
269 _pauseSyncCaption = value;
270 NotifyOfPropertyChange(() => PauseSyncCaption);
274 private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
275 public ObservableConcurrentCollection<FileEntry> RecentFiles
277 get { return _recentFiles; }
281 private string _statusIcon="../Images/Pithos.ico";
282 public string StatusIcon
284 get { return _statusIcon; }
287 //_statusIcon = value;
288 NotifyOfPropertyChange(() => StatusIcon);
296 public void ShowPreferences()
299 var preferences = new PreferencesViewModel(_windowManager,_events, this,Settings);
300 _windowManager.ShowDialog(preferences);
304 public void AboutPithos()
306 var about = new AboutViewModel();
307 _windowManager.ShowWindow(about);
310 public void SendFeedback()
312 var feedBack = IoC.Get<FeedbackViewModel>();
313 _windowManager.ShowWindow(feedBack);
316 //public PithosCommand OpenPithosFolderCommand { get; private set; }
318 public void OpenPithosFolder()
320 var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
323 Process.Start(account.RootPath);
326 public void OpenPithosFolder(AccountInfo account)
328 Process.Start(account.AccountPath);
333 public void GoToSite()
335 var site = Properties.Settings.Default.PithosSite;
340 public void GoToSite(AccountInfo account)
342 /*var site = String.Format("{0}/ui/?token={1}&user={2}",
343 account.SiteUri,account.Token,
345 Process.Start(account.SiteUri);
348 public void ShowFileProperties()
350 var account = Settings.Accounts.First(acc => acc.IsActive);
351 var dir = new DirectoryInfo(account.RootPath + @"\pithos");
352 var files=dir.GetFiles();
354 var idx=r.Next(0, files.Length);
355 ShowFileProperties(files[idx].FullName);
358 public void ShowFileProperties(string filePath)
360 if (String.IsNullOrWhiteSpace(filePath))
361 throw new ArgumentNullException("filePath");
362 if (!File.Exists(filePath))
363 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
364 Contract.EndContractBlock();
366 var pair=(from monitor in Monitors
367 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
368 select monitor).FirstOrDefault();
369 var account = pair.Key;
370 var accountMonitor = pair.Value;
372 if (accountMonitor == null)
375 var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
379 var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
380 _windowManager.ShowWindow(fileProperties);
383 public void ShowContainerProperties()
385 var account = Settings.Accounts.First(acc => acc.IsActive);
386 var dir = new DirectoryInfo(account.RootPath);
387 var fullName = (from folder in dir.EnumerateDirectories()
388 where (folder.Attributes & FileAttributes.Hidden) == 0
389 select folder.FullName).First();
390 ShowContainerProperties(fullName);
393 public void ShowContainerProperties(string filePath)
395 if (String.IsNullOrWhiteSpace(filePath))
396 throw new ArgumentNullException("filePath");
397 if (!Directory.Exists(filePath))
398 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
399 Contract.EndContractBlock();
401 var pair=(from monitor in Monitors
402 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
403 select monitor).FirstOrDefault();
404 var account = pair.Key;
405 var accountMonitor = pair.Value;
406 var info = accountMonitor.GetContainerInfo(filePath);
410 var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
411 _windowManager.ShowWindow(containerProperties);
414 public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
416 if (currentInfo==null)
417 throw new ArgumentNullException("currentInfo");
418 Contract.EndContractBlock();
420 var monitor = Monitors[currentInfo.Account];
421 var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
425 public ContainerInfo RefreshContainerInfo(ContainerInfo container)
427 if (container == null)
428 throw new ArgumentNullException("container");
429 Contract.EndContractBlock();
431 var monitor = Monitors[container.Account];
432 var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
437 public void ToggleSynching()
440 foreach (var pair in Monitors)
442 var monitor = pair.Value;
443 monitor.Pause = !monitor.Pause;
444 isPaused = monitor.Pause;
447 PauseSyncCaption = isPaused ? "Resume syncing" : "Pause syncing";
448 var iconKey = isPaused? "TraySyncPaused" : "TrayInSynch";
449 StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
452 public void ExitPithos()
454 foreach (var pair in Monitors)
456 var monitor = pair.Value;
460 ((Window)GetView()).Close();
465 private Dictionary<PithosStatus, StatusInfo> iconNames = new List<StatusInfo>
467 new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
468 new StatusInfo(PithosStatus.Syncing, "Syncing Files", "TraySynching"),
469 new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
470 }.ToDictionary(s => s.Status);
472 readonly IWindowManager _windowManager;
476 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat
478 public void UpdateStatus()
480 var pithosStatus = _statusChecker.GetPithosStatus();
482 if (iconNames.ContainsKey(pithosStatus))
484 var info = iconNames[pithosStatus];
485 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
487 Assembly assembly = Assembly.GetExecutingAssembly();
488 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
491 StatusMessage = String.Format("Pithos {0}\r\n{1}", fileVersion.FileVersion,info.StatusText);
494 _events.Publish(new Notification { Title = "Start", Message = "Start Monitoring", Level = TraceLevel.Info});
499 private Task StartMonitor(PithosMonitor monitor,int retries=0)
501 return Task.Factory.StartNew(() =>
503 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
507 Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
511 catch (WebException exc)
513 if (AbandonRetry(monitor, retries))
516 if (IsUnauthorized(exc))
518 var message = String.Format("API Key Expired for {0}. Starting Renewal",monitor.UserName);
519 Log.Error(message,exc);
520 TryAuthorize(monitor,retries).Wait();
524 TryLater(monitor, exc,retries);
527 catch (Exception exc)
529 if (AbandonRetry(monitor, retries))
532 TryLater(monitor,exc,retries);
538 private bool AbandonRetry(PithosMonitor monitor, int retries)
542 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
544 _events.Publish(new Notification
545 {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
552 private async Task TryAuthorize(PithosMonitor monitor,int retries)
554 _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 });
559 var credentials = await PithosAccount.RetrieveCredentials(Settings.PithosLoginUrl);
561 var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
562 account.ApiKey = credentials.Password;
563 monitor.ApiKey = credentials.Password;
565 await TaskEx.Delay(10000);
566 StartMonitor(monitor, retries + 1);
567 NotifyOfPropertyChange(()=>Accounts);
569 catch (AggregateException exc)
571 string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
572 Log.Error(message, exc.InnerException);
573 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
576 catch (Exception exc)
578 string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
579 Log.Error(message, exc);
580 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
587 private static bool IsUnauthorized(WebException exc)
590 throw new ArgumentNullException("exc");
591 Contract.EndContractBlock();
593 var response = exc.Response as HttpWebResponse;
594 if (response == null)
596 return (response.StatusCode == HttpStatusCode.Unauthorized);
599 private void TryLater(PithosMonitor monitor, Exception exc,int retries)
601 var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
602 Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
603 _events.Publish(new Notification
604 {Title = "Error", Message = message, Level = TraceLevel.Error});
605 Log.Error(message, exc);
609 public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
611 this.StatusMessage = status;
613 _events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
616 public void NotifyChangedFile(string filePath)
618 var entry = new FileEntry {FullPath=filePath};
619 IProducerConsumerCollection<FileEntry> files=this.RecentFiles;
621 while (files.Count > 5)
622 files.TryTake(out popped);
626 public void NotifyAccount(AccountInfo account)
630 //TODO: What happens to an existing account whose Token has changed?
631 account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
632 account.SiteUri, account.Token,
635 if (Accounts.All(item => item.UserName != account.UserName))
636 Accounts.TryAdd(account);
641 public void RemoveMonitor(string accountName)
643 if (String.IsNullOrWhiteSpace(accountName))
646 var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName);
647 _accounts.TryRemove(accountInfo);
649 PithosMonitor monitor;
650 if (Monitors.TryRemove(accountName, out monitor))
656 public void RefreshOverlays()
658 foreach (var pair in Monitors)
660 var monitor = pair.Value;
662 var path = monitor.RootPath;
664 if (String.IsNullOrWhiteSpace(path))
667 if (!Directory.Exists(path) && !File.Exists(path))
670 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
674 NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
675 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
676 pathPointer, IntPtr.Zero);
680 Marshal.FreeHGlobal(pathPointer);
685 #region Event Handlers
687 public void Handle(SelectiveSynchChanges message)
689 var accountName = message.Account.AccountName;
690 PithosMonitor monitor;
691 if (_monitors.TryGetValue(accountName, out monitor))
693 monitor.AddSelectivePaths(message.Added);
694 monitor.RemoveSelectivePaths(message.Removed);
701 public void Handle(Notification notification)
703 if (!Settings.ShowDesktopNotifications)
705 BalloonIcon icon = BalloonIcon.None;
706 switch (notification.Level)
708 case TraceLevel.Error:
709 icon = BalloonIcon.Error;
711 case TraceLevel.Info:
712 case TraceLevel.Verbose:
713 icon = BalloonIcon.Info;
715 case TraceLevel.Warning:
716 icon = BalloonIcon.Warning;
719 icon = BalloonIcon.None;
723 if (Settings.ShowDesktopNotifications)
725 var tv = (ShellView) this.GetView();
726 tv.TaskbarView.ShowBalloonTip(notification.Title, notification.Message, icon);
731 public void Handle(ShowFilePropertiesEvent message)
734 throw new ArgumentNullException("message");
735 if (String.IsNullOrWhiteSpace(message.FileName) )
736 throw new ArgumentException("message");
737 Contract.EndContractBlock();
739 var fileName = message.FileName;
741 if (File.Exists(fileName))
742 this.ShowFileProperties(fileName);
743 else if (Directory.Exists(fileName))
744 this.ShowContainerProperties(fileName);