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";
109 catch (Exception exc)
111 Log.Error("Error while starting the ShellViewModel",exc);
116 protected override void OnActivate()
124 private async Task StartMonitoring()
128 foreach (var account in Settings.Accounts)
130 await MonitorAccount(account);
132 _statusService = StatusService.Start();
134 catch (AggregateException exc)
138 Log.Error("Error while starting monitoring", e);
145 protected override void OnDeactivate(bool close)
147 base.OnDeactivate(close);
150 StatusService.Stop(_statusService);
151 _statusService = null;
155 public Task MonitorAccount(AccountSettings account)
157 return Task.Factory.StartNew(() =>
159 PithosMonitor monitor = null;
160 var accountName = account.AccountName;
162 if (_monitors.TryGetValue(accountName, out monitor))
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
171 //If the account is inactive
172 //Stop and remove the monitor
173 RemoveMonitor(accountName);
178 //Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
179 monitor = new PithosMonitor
181 UserName = accountName,
182 ApiKey = account.ApiKey,
183 UsePithos = account.UsePithos,
184 StatusNotification = this,
185 RootPath = account.RootPath
187 //PithosMonitor uses MEF so we need to resolve it
188 IoC.BuildUp(monitor);
190 var appSettings = Properties.Settings.Default;
191 monitor.AuthenticationUrl = account.UsePithos
192 ? appSettings.PithosAuthenticationUrl
193 : appSettings.CloudfilesAuthenticationUrl;
195 _monitors[accountName] = monitor;
197 if (account.IsActive)
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))
203 StartMonitor(monitor);
209 protected override void OnViewLoaded(object view)
211 var window = (Window)view;
214 base.OnViewLoaded(view);
218 #region Status Properties
220 private string _statusMessage;
221 public string StatusMessage
223 get { return _statusMessage; }
226 _statusMessage = value;
227 NotifyOfPropertyChange(() => StatusMessage);
231 private ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
232 public ObservableConcurrentCollection<AccountInfo> Accounts
234 get { return _accounts; }
238 private string _pauseSyncCaption="Pause Syncing";
239 public string PauseSyncCaption
241 get { return _pauseSyncCaption; }
244 _pauseSyncCaption = value;
245 NotifyOfPropertyChange(() => PauseSyncCaption);
249 private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
250 public ObservableConcurrentCollection<FileEntry> RecentFiles
252 get { return _recentFiles; }
256 private string _statusIcon="../Images/Tray.ico";
257 public string StatusIcon
259 get { return _statusIcon; }
263 NotifyOfPropertyChange(() => StatusIcon);
271 public void ShowPreferences()
274 var preferences = new PreferencesViewModel(_windowManager,_events, this,Settings);
275 _windowManager.ShowDialog(preferences);
279 public void AboutPithos()
281 var about = new AboutViewModel();
282 _windowManager.ShowWindow(about);
285 public void SendFeedback()
287 var feedBack = IoC.Get<FeedbackViewModel>();
288 _windowManager.ShowWindow(feedBack);
291 //public PithosCommand OpenPithosFolderCommand { get; private set; }
293 public void OpenPithosFolder()
295 var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
298 Process.Start(account.RootPath);
301 public void OpenPithosFolder(AccountInfo account)
303 Process.Start(account.AccountPath);
307 public void GoToSite(AccountInfo account)
309 var site = String.Format("{0}/ui/?token={1}&user={2}",
310 Properties.Settings.Default.PithosSite,account.Token,
315 public void ShowFileProperties()
317 var account = Settings.Accounts.First(acc => acc.IsActive);
318 var dir = new DirectoryInfo(account.RootPath + @"\pithos");
319 var files=dir.GetFiles();
321 var idx=r.Next(0, files.Length);
322 ShowFileProperties(files[idx].FullName);
325 public void ShowFileProperties(string filePath)
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();
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;
339 if (accountMonitor == null)
342 var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
346 var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
347 _windowManager.ShowWindow(fileProperties);
350 public void ShowContainerProperties()
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);
360 public void ShowContainerProperties(string filePath)
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();
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);
377 var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
378 _windowManager.ShowWindow(containerProperties);
381 public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
383 if (currentInfo==null)
384 throw new ArgumentNullException("currentInfo");
385 Contract.EndContractBlock();
387 var monitor = Monitors[currentInfo.Account];
388 var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
392 public ContainerInfo RefreshContainerInfo(ContainerInfo container)
394 if (container == null)
395 throw new ArgumentNullException("container");
396 Contract.EndContractBlock();
398 var monitor = Monitors[container.Account];
399 var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
404 public void ToggleSynching()
407 foreach (var pair in Monitors)
409 var monitor = pair.Value;
410 monitor.Pause = !monitor.Pause;
411 isPaused = monitor.Pause;
414 PauseSyncCaption = isPaused ? "Resume syncing" : "Pause syncing";
415 var iconKey = isPaused? "TraySyncPaused" : "TrayInSynch";
416 StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
419 public void ExitPithos()
421 foreach (var pair in Monitors)
423 var monitor = pair.Value;
427 ((Window)GetView()).Close();
432 private Dictionary<PithosStatus, StatusInfo> iconNames = new List<StatusInfo>
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);
439 readonly IWindowManager _windowManager;
443 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat
445 public void UpdateStatus()
447 var pithosStatus = _statusChecker.GetPithosStatus();
449 if (iconNames.ContainsKey(pithosStatus))
451 var info = iconNames[pithosStatus];
452 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
454 Assembly assembly = Assembly.GetExecutingAssembly();
455 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
458 StatusMessage = String.Format("Pithos {0}\r\n{1}", fileVersion.FileVersion,info.StatusText);
461 _events.Publish(new Notification { Title = "Start", Message = "Start Monitoring", Level = TraceLevel.Info});
466 private Task StartMonitor(PithosMonitor monitor,int retries=0)
468 return Task.Factory.StartNew(() =>
470 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
474 Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
478 catch (WebException exc)
480 if (AbandonRetry(monitor, retries))
483 if (IsUnauthorized(exc))
485 var message = String.Format("API Key Expired for {0}. Starting Renewal",monitor.UserName);
486 Log.Error(message,exc);
487 TryAuthorize(monitor,retries).Wait();
491 TryLater(monitor, exc,retries);
494 catch (Exception exc)
496 if (AbandonRetry(monitor, retries))
499 TryLater(monitor,exc,retries);
505 private bool AbandonRetry(PithosMonitor monitor, int retries)
509 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
511 _events.Publish(new Notification
512 {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
519 private async Task TryAuthorize(PithosMonitor monitor,int retries)
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 });
526 var credentials = await PithosAccount.RetrieveCredentialsAsync(Settings.PithosLoginUrl);
528 var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
529 account.ApiKey = credentials.Password;
530 monitor.ApiKey = credentials.Password;
532 await TaskEx.Delay(10000);
533 StartMonitor(monitor, retries + 1);
534 NotifyOfPropertyChange(()=>Accounts);
536 catch (AggregateException exc)
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 });
543 catch (Exception exc)
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 });
554 private static bool IsUnauthorized(WebException exc)
557 throw new ArgumentNullException("exc");
558 Contract.EndContractBlock();
560 var response = exc.Response as HttpWebResponse;
561 if (response == null)
563 return (response.StatusCode == HttpStatusCode.Unauthorized);
566 private void TryLater(PithosMonitor monitor, Exception exc,int retries)
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);
576 public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
578 this.StatusMessage = status;
580 _events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
583 public void NotifyChangedFile(string filePath)
585 var entry = new FileEntry {FullPath=filePath};
586 IProducerConsumerCollection<FileEntry> files=this.RecentFiles;
588 while (files.Count > 5)
589 files.TryTake(out popped);
593 public void NotifyAccount(AccountInfo account)
598 account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
599 Properties.Settings.Default.PithosSite, account.Token,
602 IProducerConsumerCollection<AccountInfo> accounts = Accounts;
603 for (var i = 0; i < _accounts.Count; i++)
606 if (accounts.TryTake(out item))
608 if (item.UserName!=account.UserName)
610 accounts.TryAdd(item);
615 accounts.TryAdd(account);
619 public void RemoveMonitor(string accountName)
621 if (String.IsNullOrWhiteSpace(accountName))
624 PithosMonitor monitor;
625 if (Monitors.TryGetValue(accountName, out monitor))
627 Monitors.Remove(accountName);
632 public void RefreshOverlays()
634 foreach (var pair in Monitors)
636 var monitor = pair.Value;
638 var path = monitor.RootPath;
640 if (String.IsNullOrWhiteSpace(path))
643 if (!Directory.Exists(path) && !File.Exists(path))
646 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
650 NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
651 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
652 pathPointer, IntPtr.Zero);
656 Marshal.FreeHGlobal(pathPointer);
661 #region Event Handlers
663 public void Handle(SelectiveSynchChanges message)
665 var accountName = message.Account.AccountName;
666 PithosMonitor monitor;
667 if (_monitors.TryGetValue(accountName, out monitor))
669 monitor.AddSelectivePaths(message.Added);
670 monitor.RemoveSelectivePaths(message.Removed);
677 public void Handle(Notification notification)
679 if (!Settings.ShowDesktopNotifications)
681 BalloonIcon icon = BalloonIcon.None;
682 switch (notification.Level)
684 case TraceLevel.Error:
685 icon = BalloonIcon.Error;
687 case TraceLevel.Info:
688 case TraceLevel.Verbose:
689 icon = BalloonIcon.Info;
691 case TraceLevel.Warning:
692 icon = BalloonIcon.Warning;
695 icon = BalloonIcon.None;
699 if (Settings.ShowDesktopNotifications)
701 var tv = (ShellView) this.GetView();
702 tv.TaskbarView.ShowBalloonTip(notification.Title, notification.Message, icon);
707 public void Handle(ShowFilePropertiesEvent message)
710 throw new ArgumentNullException("message");
711 if (String.IsNullOrWhiteSpace(message.FileName) )
712 throw new ArgumentException("message");
713 Contract.EndContractBlock();
715 var fileName = message.FileName;
717 if (File.Exists(fileName))
718 this.ShowFileProperties(fileName);
719 else if (Directory.Exists(fileName))
720 this.ShowContainerProperties(fileName);