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 foreach (var account in Settings.Accounts)
137 await MonitorAccount(account);
139 _statusService = StatusService.Start();
141 catch (AggregateException exc)
145 Log.Error("Error while starting monitoring", e);
152 protected override void OnDeactivate(bool close)
154 base.OnDeactivate(close);
157 StatusService.Stop(_statusService);
158 _statusService = null;
162 public Task MonitorAccount(AccountSettings account)
164 return Task.Factory.StartNew(() =>
166 PithosMonitor monitor = null;
167 var accountName = account.AccountName;
169 if (_monitors.TryGetValue(accountName, out monitor))
171 //If the account is active
172 if (account.IsActive)
173 //Start the monitor. It's OK to start an already started monitor,
174 //it will just ignore the call
175 StartMonitor(monitor).Wait();
178 //If the account is inactive
179 //Stop and remove the monitor
180 RemoveMonitor(accountName);
185 //Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
186 monitor = new PithosMonitor
188 UserName = accountName,
189 ApiKey = account.ApiKey,
190 UsePithos = account.UsePithos,
191 StatusNotification = this,
192 RootPath = account.RootPath
194 //PithosMonitor uses MEF so we need to resolve it
195 IoC.BuildUp(monitor);
197 var appSettings = Properties.Settings.Default;
198 monitor.AuthenticationUrl = account.UsePithos
199 ? appSettings.PithosAuthenticationUrl
200 : appSettings.CloudfilesAuthenticationUrl;
202 _monitors[accountName] = monitor;
204 if (account.IsActive)
206 //Don't start a monitor if it doesn't have an account and ApiKey
207 if (String.IsNullOrWhiteSpace(monitor.UserName) ||
208 String.IsNullOrWhiteSpace(monitor.ApiKey))
210 StartMonitor(monitor);
216 protected override void OnViewLoaded(object view)
219 var window = (Window)view;
220 TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
221 base.OnViewLoaded(view);
225 #region Status Properties
227 private string _statusMessage;
228 public string StatusMessage
230 get { return _statusMessage; }
233 _statusMessage = value;
234 NotifyOfPropertyChange(() => StatusMessage);
238 private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
239 public ObservableConcurrentCollection<AccountInfo> Accounts
241 get { return _accounts; }
244 public bool HasAccounts
246 get { return _accounts.Count > 0; }
250 public string OpenFolderCaption
254 return (_accounts.Count == 0)
255 ? "No Accounts Defined"
256 : "Open Pithos Folder";
260 private string _pauseSyncCaption="Pause Synching";
261 public string PauseSyncCaption
263 get { return _pauseSyncCaption; }
266 _pauseSyncCaption = value;
267 NotifyOfPropertyChange(() => PauseSyncCaption);
271 private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
272 public ObservableConcurrentCollection<FileEntry> RecentFiles
274 get { return _recentFiles; }
278 private string _statusIcon="../Images/Pithos.ico";
279 public string StatusIcon
281 get { return _statusIcon; }
284 //_statusIcon = value;
285 NotifyOfPropertyChange(() => StatusIcon);
293 public void ShowPreferences()
296 var preferences = new PreferencesViewModel(_windowManager,_events, this,Settings);
297 _windowManager.ShowDialog(preferences);
301 public void AboutPithos()
303 var about = new AboutViewModel();
304 _windowManager.ShowWindow(about);
307 public void SendFeedback()
309 var feedBack = IoC.Get<FeedbackViewModel>();
310 _windowManager.ShowWindow(feedBack);
313 //public PithosCommand OpenPithosFolderCommand { get; private set; }
315 public void OpenPithosFolder()
317 var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
320 Process.Start(account.RootPath);
323 public void OpenPithosFolder(AccountInfo account)
325 Process.Start(account.AccountPath);
329 public void GoToSite()
331 var site = Properties.Settings.Default.PithosSite;
335 public void GoToSite(AccountInfo account)
337 var site = String.Format("{0}/ui/?token={1}&user={2}",
338 Properties.Settings.Default.PithosSite,account.Token,
343 public void ShowFileProperties()
345 var account = Settings.Accounts.First(acc => acc.IsActive);
346 var dir = new DirectoryInfo(account.RootPath + @"\pithos");
347 var files=dir.GetFiles();
349 var idx=r.Next(0, files.Length);
350 ShowFileProperties(files[idx].FullName);
353 public void ShowFileProperties(string filePath)
355 if (String.IsNullOrWhiteSpace(filePath))
356 throw new ArgumentNullException("filePath");
357 if (!File.Exists(filePath))
358 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
359 Contract.EndContractBlock();
361 var pair=(from monitor in Monitors
362 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
363 select monitor).FirstOrDefault();
364 var account = pair.Key;
365 var accountMonitor = pair.Value;
367 if (accountMonitor == null)
370 var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
374 var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
375 _windowManager.ShowWindow(fileProperties);
378 public void ShowContainerProperties()
380 var account = Settings.Accounts.First(acc => acc.IsActive);
381 var dir = new DirectoryInfo(account.RootPath);
382 var fullName = (from folder in dir.EnumerateDirectories()
383 where (folder.Attributes & FileAttributes.Hidden) == 0
384 select folder.FullName).First();
385 ShowContainerProperties(fullName);
388 public void ShowContainerProperties(string filePath)
390 if (String.IsNullOrWhiteSpace(filePath))
391 throw new ArgumentNullException("filePath");
392 if (!Directory.Exists(filePath))
393 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
394 Contract.EndContractBlock();
396 var pair=(from monitor in Monitors
397 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
398 select monitor).FirstOrDefault();
399 var account = pair.Key;
400 var accountMonitor = pair.Value;
401 var info = accountMonitor.GetContainerInfo(filePath);
405 var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
406 _windowManager.ShowWindow(containerProperties);
409 public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
411 if (currentInfo==null)
412 throw new ArgumentNullException("currentInfo");
413 Contract.EndContractBlock();
415 var monitor = Monitors[currentInfo.Account];
416 var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
420 public ContainerInfo RefreshContainerInfo(ContainerInfo container)
422 if (container == null)
423 throw new ArgumentNullException("container");
424 Contract.EndContractBlock();
426 var monitor = Monitors[container.Account];
427 var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
432 public void ToggleSynching()
435 foreach (var pair in Monitors)
437 var monitor = pair.Value;
438 monitor.Pause = !monitor.Pause;
439 isPaused = monitor.Pause;
442 PauseSyncCaption = isPaused ? "Resume syncing" : "Pause syncing";
443 var iconKey = isPaused? "TraySyncPaused" : "TrayInSynch";
444 StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
447 public void ExitPithos()
449 foreach (var pair in Monitors)
451 var monitor = pair.Value;
455 ((Window)GetView()).Close();
460 private Dictionary<PithosStatus, StatusInfo> iconNames = new List<StatusInfo>
462 new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
463 new StatusInfo(PithosStatus.Syncing, "Syncing Files", "TraySynching"),
464 new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
465 }.ToDictionary(s => s.Status);
467 readonly IWindowManager _windowManager;
471 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat
473 public void UpdateStatus()
475 var pithosStatus = _statusChecker.GetPithosStatus();
477 if (iconNames.ContainsKey(pithosStatus))
479 var info = iconNames[pithosStatus];
480 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
482 Assembly assembly = Assembly.GetExecutingAssembly();
483 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
486 StatusMessage = String.Format("Pithos {0}\r\n{1}", fileVersion.FileVersion,info.StatusText);
489 _events.Publish(new Notification { Title = "Start", Message = "Start Monitoring", Level = TraceLevel.Info});
494 private Task StartMonitor(PithosMonitor monitor,int retries=0)
496 return Task.Factory.StartNew(() =>
498 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
502 Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
506 catch (WebException exc)
508 if (AbandonRetry(monitor, retries))
511 if (IsUnauthorized(exc))
513 var message = String.Format("API Key Expired for {0}. Starting Renewal",monitor.UserName);
514 Log.Error(message,exc);
515 TryAuthorize(monitor,retries).Wait();
519 TryLater(monitor, exc,retries);
522 catch (Exception exc)
524 if (AbandonRetry(monitor, retries))
527 TryLater(monitor,exc,retries);
533 private bool AbandonRetry(PithosMonitor monitor, int retries)
537 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
539 _events.Publish(new Notification
540 {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
547 private async Task TryAuthorize(PithosMonitor monitor,int retries)
549 _events.Publish(new Notification { Title = "Authorization failed", Message = "Your API Key has probably expired. You will be directed to a page where you can renew it", Level = TraceLevel.Error });
554 var credentials = await PithosAccount.RetrieveCredentials(Settings.PithosLoginUrl);
556 var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
557 account.ApiKey = credentials.Password;
558 monitor.ApiKey = credentials.Password;
560 await TaskEx.Delay(10000);
561 StartMonitor(monitor, retries + 1);
562 NotifyOfPropertyChange(()=>Accounts);
564 catch (AggregateException exc)
566 string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
567 Log.Error(message, exc.InnerException);
568 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
571 catch (Exception exc)
573 string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
574 Log.Error(message, exc);
575 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
582 private static bool IsUnauthorized(WebException exc)
585 throw new ArgumentNullException("exc");
586 Contract.EndContractBlock();
588 var response = exc.Response as HttpWebResponse;
589 if (response == null)
591 return (response.StatusCode == HttpStatusCode.Unauthorized);
594 private void TryLater(PithosMonitor monitor, Exception exc,int retries)
596 var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
597 Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
598 _events.Publish(new Notification
599 {Title = "Error", Message = message, Level = TraceLevel.Error});
600 Log.Error(message, exc);
604 public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
606 this.StatusMessage = status;
608 _events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
611 public void NotifyChangedFile(string filePath)
613 var entry = new FileEntry {FullPath=filePath};
614 IProducerConsumerCollection<FileEntry> files=this.RecentFiles;
616 while (files.Count > 5)
617 files.TryTake(out popped);
621 public void NotifyAccount(AccountInfo account)
626 account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
627 Properties.Settings.Default.PithosSite, account.Token,
630 IProducerConsumerCollection<AccountInfo> accounts = Accounts;
631 for (var i = 0; i < _accounts.Count; i++)
634 if (accounts.TryTake(out item))
636 if (item.UserName!=account.UserName)
638 accounts.TryAdd(item);
643 accounts.TryAdd(account);
647 public void RemoveMonitor(string accountName)
649 if (String.IsNullOrWhiteSpace(accountName))
652 var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName);
653 _accounts.TryRemove(accountInfo);
655 PithosMonitor monitor;
656 if (Monitors.TryGetValue(accountName, out monitor))
658 Monitors.Remove(accountName);
663 public void RefreshOverlays()
665 foreach (var pair in Monitors)
667 var monitor = pair.Value;
669 var path = monitor.RootPath;
671 if (String.IsNullOrWhiteSpace(path))
674 if (!Directory.Exists(path) && !File.Exists(path))
677 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
681 NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
682 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
683 pathPointer, IntPtr.Zero);
687 Marshal.FreeHGlobal(pathPointer);
692 #region Event Handlers
694 public void Handle(SelectiveSynchChanges message)
696 var accountName = message.Account.AccountName;
697 PithosMonitor monitor;
698 if (_monitors.TryGetValue(accountName, out monitor))
700 monitor.AddSelectivePaths(message.Added);
701 monitor.RemoveSelectivePaths(message.Removed);
708 public void Handle(Notification notification)
710 if (!Settings.ShowDesktopNotifications)
712 BalloonIcon icon = BalloonIcon.None;
713 switch (notification.Level)
715 case TraceLevel.Error:
716 icon = BalloonIcon.Error;
718 case TraceLevel.Info:
719 case TraceLevel.Verbose:
720 icon = BalloonIcon.Info;
722 case TraceLevel.Warning:
723 icon = BalloonIcon.Warning;
726 icon = BalloonIcon.None;
730 if (Settings.ShowDesktopNotifications)
732 var tv = (ShellView) this.GetView();
733 tv.TaskbarView.ShowBalloonTip(notification.Title, notification.Message, icon);
738 public void Handle(ShowFilePropertiesEvent message)
741 throw new ArgumentNullException("message");
742 if (String.IsNullOrWhiteSpace(message.FileName) )
743 throw new ArgumentException("message");
744 Contract.EndContractBlock();
746 var fileName = message.FileName;
748 if (File.Exists(fileName))
749 this.ShowFileProperties(fileName);
750 else if (Directory.Exists(fileName))
751 this.ShowContainerProperties(fileName);