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 UsePithos = account.UsePithos,
198 StatusNotification = this,
199 RootPath = account.RootPath
201 //PithosMonitor uses MEF so we need to resolve it
202 IoC.BuildUp(monitor);
204 var appSettings = Properties.Settings.Default;
205 monitor.AuthenticationUrl = account.UsePithos
206 ? account.ServerUrl.ToString()
207 : appSettings.CloudfilesAuthenticationUrl;
209 _monitors[accountName] = monitor;
211 if (account.IsActive)
213 //Don't start a monitor if it doesn't have an account and ApiKey
214 if (String.IsNullOrWhiteSpace(monitor.UserName) ||
215 String.IsNullOrWhiteSpace(monitor.ApiKey))
217 StartMonitor(monitor);
223 protected override void OnViewLoaded(object view)
226 var window = (Window)view;
227 TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
228 base.OnViewLoaded(view);
232 #region Status Properties
234 private string _statusMessage;
235 public string StatusMessage
237 get { return _statusMessage; }
240 _statusMessage = value;
241 NotifyOfPropertyChange(() => StatusMessage);
245 private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
246 public ObservableConcurrentCollection<AccountInfo> Accounts
248 get { return _accounts; }
251 public bool HasAccounts
253 get { return _accounts.Count > 0; }
257 public string OpenFolderCaption
261 return (_accounts.Count == 0)
262 ? "No Accounts Defined"
263 : "Open Pithos Folder";
267 private string _pauseSyncCaption="Pause Synching";
268 public string PauseSyncCaption
270 get { return _pauseSyncCaption; }
273 _pauseSyncCaption = value;
274 NotifyOfPropertyChange(() => PauseSyncCaption);
278 private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
279 public ObservableConcurrentCollection<FileEntry> RecentFiles
281 get { return _recentFiles; }
285 private string _statusIcon="../Images/Pithos.ico";
286 public string StatusIcon
288 get { return _statusIcon; }
291 //_statusIcon = value;
292 NotifyOfPropertyChange(() => StatusIcon);
300 public void ShowPreferences()
303 var preferences = new PreferencesViewModel(_windowManager,_events, this,Settings);
304 _windowManager.ShowDialog(preferences);
308 public void AboutPithos()
310 var about = new AboutViewModel();
311 _windowManager.ShowWindow(about);
314 public void SendFeedback()
316 var feedBack = IoC.Get<FeedbackViewModel>();
317 _windowManager.ShowWindow(feedBack);
320 //public PithosCommand OpenPithosFolderCommand { get; private set; }
322 public void OpenPithosFolder()
324 var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
327 Process.Start(account.RootPath);
330 public void OpenPithosFolder(AccountInfo account)
332 Process.Start(account.AccountPath);
337 public void GoToSite()
339 var site = Properties.Settings.Default.PithosSite;
344 public void GoToSite(AccountInfo account)
346 var site = String.Format("{0}/ui/?token={1}&user={2}",
347 account.SiteUri,account.Token,
352 public void ShowFileProperties()
354 var account = Settings.Accounts.First(acc => acc.IsActive);
355 var dir = new DirectoryInfo(account.RootPath + @"\pithos");
356 var files=dir.GetFiles();
358 var idx=r.Next(0, files.Length);
359 ShowFileProperties(files[idx].FullName);
362 public void ShowFileProperties(string filePath)
364 if (String.IsNullOrWhiteSpace(filePath))
365 throw new ArgumentNullException("filePath");
366 if (!File.Exists(filePath))
367 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
368 Contract.EndContractBlock();
370 var pair=(from monitor in Monitors
371 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
372 select monitor).FirstOrDefault();
373 var account = pair.Key;
374 var accountMonitor = pair.Value;
376 if (accountMonitor == null)
379 var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
383 var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
384 _windowManager.ShowWindow(fileProperties);
387 public void ShowContainerProperties()
389 var account = Settings.Accounts.First(acc => acc.IsActive);
390 var dir = new DirectoryInfo(account.RootPath);
391 var fullName = (from folder in dir.EnumerateDirectories()
392 where (folder.Attributes & FileAttributes.Hidden) == 0
393 select folder.FullName).First();
394 ShowContainerProperties(fullName);
397 public void ShowContainerProperties(string filePath)
399 if (String.IsNullOrWhiteSpace(filePath))
400 throw new ArgumentNullException("filePath");
401 if (!Directory.Exists(filePath))
402 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
403 Contract.EndContractBlock();
405 var pair=(from monitor in Monitors
406 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
407 select monitor).FirstOrDefault();
408 var account = pair.Key;
409 var accountMonitor = pair.Value;
410 var info = accountMonitor.GetContainerInfo(filePath);
414 var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
415 _windowManager.ShowWindow(containerProperties);
418 public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
420 if (currentInfo==null)
421 throw new ArgumentNullException("currentInfo");
422 Contract.EndContractBlock();
424 var monitor = Monitors[currentInfo.Account];
425 var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
429 public ContainerInfo RefreshContainerInfo(ContainerInfo container)
431 if (container == null)
432 throw new ArgumentNullException("container");
433 Contract.EndContractBlock();
435 var monitor = Monitors[container.Account];
436 var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
441 public void ToggleSynching()
444 foreach (var pair in Monitors)
446 var monitor = pair.Value;
447 monitor.Pause = !monitor.Pause;
448 isPaused = monitor.Pause;
451 PauseSyncCaption = isPaused ? "Resume syncing" : "Pause syncing";
452 var iconKey = isPaused? "TraySyncPaused" : "TrayInSynch";
453 StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
456 public void ExitPithos()
458 foreach (var pair in Monitors)
460 var monitor = pair.Value;
464 ((Window)GetView()).Close();
469 private Dictionary<PithosStatus, StatusInfo> iconNames = new List<StatusInfo>
471 new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
472 new StatusInfo(PithosStatus.Syncing, "Syncing Files", "TraySynching"),
473 new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
474 }.ToDictionary(s => s.Status);
476 readonly IWindowManager _windowManager;
480 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat
482 public void UpdateStatus()
484 var pithosStatus = _statusChecker.GetPithosStatus();
486 if (iconNames.ContainsKey(pithosStatus))
488 var info = iconNames[pithosStatus];
489 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
491 Assembly assembly = Assembly.GetExecutingAssembly();
492 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
495 StatusMessage = String.Format("Pithos {0}\r\n{1}", fileVersion.FileVersion,info.StatusText);
498 _events.Publish(new Notification { Title = "Start", Message = "Start Monitoring", Level = TraceLevel.Info});
503 private Task StartMonitor(PithosMonitor monitor,int retries=0)
505 return Task.Factory.StartNew(() =>
507 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
511 Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
515 catch (WebException exc)
517 if (AbandonRetry(monitor, retries))
520 if (IsUnauthorized(exc))
522 var message = String.Format("API Key Expired for {0}. Starting Renewal",monitor.UserName);
523 Log.Error(message,exc);
524 TryAuthorize(monitor,retries).Wait();
528 TryLater(monitor, exc,retries);
531 catch (Exception exc)
533 if (AbandonRetry(monitor, retries))
536 TryLater(monitor,exc,retries);
542 private bool AbandonRetry(PithosMonitor monitor, int retries)
546 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
548 _events.Publish(new Notification
549 {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
556 private async Task TryAuthorize(PithosMonitor monitor,int retries)
558 _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 });
563 var credentials = await PithosAccount.RetrieveCredentials(Settings.PithosLoginUrl);
565 var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
566 account.ApiKey = credentials.Password;
567 monitor.ApiKey = credentials.Password;
569 await TaskEx.Delay(10000);
570 StartMonitor(monitor, retries + 1);
571 NotifyOfPropertyChange(()=>Accounts);
573 catch (AggregateException exc)
575 string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
576 Log.Error(message, exc.InnerException);
577 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
580 catch (Exception exc)
582 string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
583 Log.Error(message, exc);
584 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
591 private static bool IsUnauthorized(WebException exc)
594 throw new ArgumentNullException("exc");
595 Contract.EndContractBlock();
597 var response = exc.Response as HttpWebResponse;
598 if (response == null)
600 return (response.StatusCode == HttpStatusCode.Unauthorized);
603 private void TryLater(PithosMonitor monitor, Exception exc,int retries)
605 var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
606 Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
607 _events.Publish(new Notification
608 {Title = "Error", Message = message, Level = TraceLevel.Error});
609 Log.Error(message, exc);
613 public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
615 this.StatusMessage = status;
617 _events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
620 public void NotifyChangedFile(string filePath)
622 var entry = new FileEntry {FullPath=filePath};
623 IProducerConsumerCollection<FileEntry> files=this.RecentFiles;
625 while (files.Count > 5)
626 files.TryTake(out popped);
630 public void NotifyAccount(AccountInfo account)
635 account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
636 account.SiteUri, account.Token,
639 IProducerConsumerCollection<AccountInfo> accounts = Accounts;
640 for (var i = 0; i < _accounts.Count; i++)
643 if (accounts.TryTake(out item))
645 if (item.UserName!=account.UserName)
647 accounts.TryAdd(item);
652 accounts.TryAdd(account);
656 public void RemoveMonitor(string accountName)
658 if (String.IsNullOrWhiteSpace(accountName))
661 var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName);
662 _accounts.TryRemove(accountInfo);
664 PithosMonitor monitor;
665 if (Monitors.TryGetValue(accountName, out monitor))
667 Monitors.Remove(accountName);
672 public void RefreshOverlays()
674 foreach (var pair in Monitors)
676 var monitor = pair.Value;
678 var path = monitor.RootPath;
680 if (String.IsNullOrWhiteSpace(path))
683 if (!Directory.Exists(path) && !File.Exists(path))
686 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
690 NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
691 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
692 pathPointer, IntPtr.Zero);
696 Marshal.FreeHGlobal(pathPointer);
701 #region Event Handlers
703 public void Handle(SelectiveSynchChanges message)
705 var accountName = message.Account.AccountName;
706 PithosMonitor monitor;
707 if (_monitors.TryGetValue(accountName, out monitor))
709 monitor.AddSelectivePaths(message.Added);
710 monitor.RemoveSelectivePaths(message.Removed);
717 public void Handle(Notification notification)
719 if (!Settings.ShowDesktopNotifications)
721 BalloonIcon icon = BalloonIcon.None;
722 switch (notification.Level)
724 case TraceLevel.Error:
725 icon = BalloonIcon.Error;
727 case TraceLevel.Info:
728 case TraceLevel.Verbose:
729 icon = BalloonIcon.Info;
731 case TraceLevel.Warning:
732 icon = BalloonIcon.Warning;
735 icon = BalloonIcon.None;
739 if (Settings.ShowDesktopNotifications)
741 var tv = (ShellView) this.GetView();
742 tv.TaskbarView.ShowBalloonTip(notification.Title, notification.Message, icon);
747 public void Handle(ShowFilePropertiesEvent message)
750 throw new ArgumentNullException("message");
751 if (String.IsNullOrWhiteSpace(message.FileName) )
752 throw new ArgumentException("message");
753 Contract.EndContractBlock();
755 var fileName = message.FileName;
757 if (File.Exists(fileName))
758 this.ShowFileProperties(fileName);
759 else if (Directory.Exists(fileName))
760 this.ShowContainerProperties(fileName);