using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
+using AppLimit.NetSparkle;
using Caliburn.Micro;
using Hardcodet.Wpf.TaskbarNotification;
using Pithos.Client.WPF.Configuration;
/// * ShowFilePropertiesEvent: Raised when a shell command requests the display of the file/container properties dialog
///</remarks>
//TODO: CODE SMELL Why does the shell handle the SelectiveSynchChanges?
- [Export(typeof(IShell))]
+ [Export(typeof(IShell)), Export(typeof(ShellViewModel))]
public class ShellViewModel : Screen, IStatusNotification, IShell,
IHandle<Notification>, IHandle<SelectiveSynchChanges>, IHandle<ShowFilePropertiesEvent>
{
public PithosSettings Settings { get; private set; }
- private readonly ConcurrentDictionary<string, PithosMonitor> _monitors = new ConcurrentDictionary<string, PithosMonitor>();
+ private readonly ConcurrentDictionary<Uri, PithosMonitor> _monitors = new ConcurrentDictionary<Uri, PithosMonitor>();
///<summary>
/// Dictionary of account monitors, keyed by account
///</summary>
///</remarks>
// TODO: Does the Shell REALLY need access to the monitors? Could we achieve the same results with a better design?
// TODO: The monitors should be internal to Pithos.Core, even though exposing them makes coding of the Object and Container windows easier
- public ConcurrentDictionary<string, PithosMonitor> Monitors
+ public ConcurrentDictionary<Uri, PithosMonitor> Monitors
{
get { return _monitors; }
}
//Logging in the Pithos client is provided by log4net
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- //Lazily initialized File Version info. This is done once and lazily to avoid blocking the UI
- private readonly Lazy<FileVersionInfo> _fileVersion;
-
private readonly PollAgent _pollAgent;
- ///<summary>
+
+ private MiniStatusViewModel _miniStatus;
+
+ [Import]
+ public MiniStatusViewModel MiniStatus
+ {
+ get { return _miniStatus; }
+ set
+ {
+ _miniStatus = value;
+ _miniStatus.Shell = this;
+ _miniStatus.Deactivated += (sender, arg) =>
+ {
+ _statusVisible = false;
+ NotifyOfPropertyChange(()=>MiniStatusCaption);
+ };
+ }
+ }
+
+ ///<summary>
/// The Shell depends on MEF to provide implementations for windowManager, events, the status checker service and the settings
///</summary>
///<remarks>
Proxy.SetFromSettings(settings);
- StatusMessage = "In Synch";
+ StatusMessage = Settings.Accounts.Count==0
+ ? "No Accounts added\r\nPlease add an account"
+ : "Starting";
- _fileVersion= new Lazy<FileVersionInfo>(() =>
- {
- Assembly assembly = Assembly.GetExecutingAssembly();
- var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
- return fileVersion;
- });
_accounts.CollectionChanged += (sender, e) =>
{
NotifyOfPropertyChange(() => OpenFolderCaption);
NotifyOfPropertyChange(() => HasAccounts);
};
+ SetVersionMessage();
}
catch (Exception exc)
{
}
+ private void SetVersionMessage()
+ {
+ Assembly assembly = Assembly.GetExecutingAssembly();
+ var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
+ VersionMessage = String.Format("Pithos+ {0}", fileVersion.FileVersion);
+ }
- protected override void OnActivate()
+ public void OnStatusAction()
+ {
+ if (Accounts.Count==0)
+ {
+ ShowPreferences("AccountTab");
+ }
+ }
+ protected override void OnActivate()
{
base.OnActivate();
-
+ InitializeSparkle();
+
+ //Must delay opening the upgrade window
+ //to avoid Windows Messages sent by the TaskbarIcon
+ TaskEx.Delay(5000).ContinueWith(_=>
+ Execute.OnUIThread(()=> _sparkle.StartLoop(true,Settings.UpdateForceCheck,Settings.UpdateCheckInterval)));
+
StartMonitoring();
}
+ private void OnCheckFinished(object sender, bool updaterequired)
+ {
+
+ Log.InfoFormat("Upgrade check finished. Need Upgrade: {0}", updaterequired);
+ if (_manualUpgradeCheck)
+ {
+ _manualUpgradeCheck = false;
+ if (!updaterequired)
+ //Sparkle raises events on a background thread
+ Execute.OnUIThread(()=>
+ ShowBalloonFor(new Notification{Title="Pithos+ is up to date",Message="You have the latest Pithos+ version. No update is required"}));
+ }
+ }
+
+ private void OnUpgradeDetected(object sender, UpdateDetectedEventArgs e)
+ {
+ Log.InfoFormat("Update detected {0}",e.LatestVersion);
+ }
+
+ public void CheckForUpgrade()
+ {
+ ShowBalloonFor(new Notification{Title="Checking for upgrades",Message="Contacting the server to retrieve the latest Pithos+ version."});
+ _sparkle.StopLoop();
+ _sparkle.updateDetected -= OnUpgradeDetected;
+ _sparkle.checkLoopFinished -= OnCheckFinished;
+ _sparkle.Dispose();
+
+ _manualUpgradeCheck = true;
+ InitializeSparkle();
+ _sparkle.StartLoop(true,true,Settings.UpdateCheckInterval);
+ }
- private async void StartMonitoring()
+ private void InitializeSparkle()
+ {
+ _sparkle = new Sparkle(Settings.UpdateUrl);
+ _sparkle.updateDetected += OnUpgradeDetected;
+ _sparkle.checkLoopFinished += OnCheckFinished;
+ _sparkle.ShowDiagnosticWindow = Settings.UpdateDiagnostics;
+ }
+
+ private async void StartMonitoring()
{
try
{
+ if (Settings.IgnoreCertificateErrors)
+ {
+ ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
+ }
+
var accounts = Settings.Accounts.Select(MonitorAccount);
await TaskEx.WhenAll(accounts);
_statusService = StatusService.Start();
-/*
- foreach (var account in Settings.Accounts)
- {
- await MonitorAccount(account);
- }
-*/
-
}
catch (AggregateException exc)
{
PithosMonitor monitor;
var accountName = account.AccountName;
- if (_monitors.TryGetValue(accountName, out monitor))
+ if (Monitors.TryGetValue(account.AccountKey, out monitor))
{
//If the account is active
if (account.IsActive)
{
//If the account is inactive
//Stop and remove the monitor
- RemoveMonitor(accountName);
+ RemoveMonitor(account.ServerUrl,accountName);
}
return;
}
monitor.AuthenticationUrl = account.ServerUrl;
- _monitors[accountName] = monitor;
+ Monitors[account.AccountKey] = monitor;
if (account.IsActive)
{
{
_statusMessage = value;
NotifyOfPropertyChange(() => StatusMessage);
+ NotifyOfPropertyChange(() => TooltipMessage);
}
}
- private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
+ public string VersionMessage { get; set; }
+
+ public string TooltipMessage
+ {
+ get
+ {
+ return String.Format("{0}\r\n{1}",VersionMessage,StatusMessage);
+ }
+ }
+
+ private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
public ObservableConcurrentCollection<AccountInfo> Accounts
{
get { return _accounts; }
public void AboutPithos()
{
- var about = new AboutViewModel();
+ var about = IoC.Get<AboutViewModel>();
+ about.LatestVersion=_sparkle.LatestVersion;
_windowManager.ShowWindow(about);
}
}
-/*
+
public void GoToSite()
{
- var site = Properties.Settings.Default.PithosSite;
+ var site = Properties.Settings.Default.ProductionServer;
Process.Start(site);
}
-*/
+
public void GoToSite(AccountInfo account)
{
Process.Start(uri);
}
+ private bool _statusVisible;
+
+ public string MiniStatusCaption
+ {
+ get
+ {
+ return _statusVisible ? "Hide Status Window" : "Show Status Window";
+ }
+ }
+
+ public void ShowMiniStatus()
+ {
+ if (!_statusVisible)
+ _windowManager.ShowWindow(MiniStatus);
+ else
+ {
+ if (MiniStatus.IsActive)
+ MiniStatus.TryClose();
+ }
+ _statusVisible=!_statusVisible;
+
+ NotifyOfPropertyChange(()=>MiniStatusCaption);
+ }
+
+ public bool HasConflicts
+ {
+ get { return true; }
+ }
+ public void ShowConflicts()
+ {
+ _windowManager.ShowWindow(IoC.Get<ConflictsViewModel>());
+ }
+
/// <summary>
/// Open an explorer window to the target path's directory
/// and select the file
public void OpenLogPath()
{
- var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
- var pithosDataPath = Path.Combine(appDataPath, "GRNET");
+ var pithosDataPath = PithosSettings.PithosDataPath;
Process.Start(pithosDataPath);
}
{
if (currentInfo==null)
throw new ArgumentNullException("currentInfo");
- Contract.EndContractBlock();
-
- var monitor = Monitors[currentInfo.Account];
+ Contract.EndContractBlock();
+ var monitor = Monitors[currentInfo.AccountKey];
var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
return newInfo;
}
throw new ArgumentNullException("container");
Contract.EndContractBlock();
- var monitor = Monitors[container.Account];
+ var monitor = Monitors[container.AccountKey];
var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
return newInfo;
}
StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
}
- public void ExitPithos()
- {
- foreach (var pair in Monitors)
- {
- var monitor = pair.Value;
- monitor.Stop();
- }
+ public void ExitPithos()
+ {
+ try
+ {
- ((Window)GetView()).Close();
- }
- #endregion
+ foreach (var monitor in Monitors.Select(pair => pair.Value))
+ {
+ monitor.Stop();
+ }
+
+ var view = GetView() as Window;
+ if (view != null)
+ view.Close();
+ }
+ catch (Exception exc)
+ {
+ Log.Info("Exception while exiting", exc);
+ }
+ finally
+ {
+ Application.Current.Shutdown();
+ }
+ }
+
+ #endregion
private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
SetPithosStatus(status);
}
+ /* public Notifier GetNotifier(Notification startNotification, Notification endNotification)
+ {
+ return new Notifier(this, startNotification, endNotification);
+ }*/
+ public Notifier GetNotifier(string startMessage, string endMessage, params object[] args)
+ {
+ return new Notifier(this,
+ new StatusNotification(String.Format(startMessage,args)),
+ new StatusNotification(String.Format(endMessage,args)));
+ }
- ///<summary>
+
+ ///<summary>
/// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat
///</summary>
public void UpdateStatus()
{
StatusMessage = status;
- _events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
+ _events.Publish(new Notification { Title = "Pithos+", Message = status, Level = level });
}
public void NotifyChangedFile(string filePath)
account.SiteUri, Uri.EscapeDataString(account.Token),
Uri.EscapeDataString(account.UserName));
- if (Accounts.All(item => item.UserName != account.UserName))
+ if (!Accounts.Any(item => item.UserName == account.UserName && item.SiteUri == account.SiteUri))
Accounts.TryAdd(account);
}
StatusMessage = message;
- _events.Publish(new Notification { Title = "Pithos", Message = message, Level = level});
+ _events.Publish(new Notification { Title = "Pithos+", Message = message, Level = level});
}
public void Notify(Notification notification)
}
- public void RemoveMonitor(string accountName)
+ public void RemoveMonitor(string serverUrl,string accountName)
{
if (String.IsNullOrWhiteSpace(accountName))
return;
- var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName);
+ var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName && account.StorageUri.ToString().StartsWith(serverUrl));
if (accountInfo != null)
{
_accounts.TryRemove(accountInfo);
_pollAgent.RemoveAccount(accountInfo);
}
+ var accountKey = new Uri(new Uri(serverUrl),accountName);
PithosMonitor monitor;
- if (Monitors.TryRemove(accountName, out monitor))
+ if (Monitors.TryRemove(accountKey, out monitor))
{
monitor.Stop();
//TODO: Also remove any pending actions for this account
#region Event Handlers
public void Handle(SelectiveSynchChanges message)
- {
- var accountName = message.Account.AccountName;
+ {
PithosMonitor monitor;
- if (_monitors.TryGetValue(accountName, out monitor))
+ if (Monitors.TryGetValue(message.Account.AccountKey, out monitor))
{
monitor.SetSelectivePaths(message.Uris,message.Added,message.Removed);
}
-
+
+ var account = Accounts.First(acc => acc.AccountKey == message.Account.AccountKey);
+ this._pollAgent.SetSelectivePaths(account, message.Added, message.Removed);
+
+
}
private bool _pollStarted;
+ private Sparkle _sparkle;
+ private bool _manualUpgradeCheck;
- //SMELL: Doing so much work for notifications in the shell is wrong
+ //SMELL: Doing so much work for notifications in the shell is wrong
//The notifications should be moved to their own view/viewmodel pair
//and different templates should be used for different message types
//This will also allow the addition of extra functionality, eg. actions
if (!_pollStarted)
return;
_pollStarted= false;
- notification.Title = "Pithos";
+ notification.Title = "Pithos+";
notification.Message = "Start Synchronisation";
}
+ var deleteNotification = notification as CloudDeleteNotification;
+ if (deleteNotification != null)
+ {
+ StatusMessage = String.Format("Deleted {0}", deleteNotification.Data.Name);
+ return;
+ }
+
var progress = notification as ProgressNotification;
- if (progress != null)
+
+
+ if (progress != null)
{
- StatusMessage = String.Format("Pithos {0}\r\n{1} {2:p2} of {3} - {4}",
- _fileVersion.Value.FileVersion,
+ StatusMessage = String.Format("{0} {1:p2} of {2} - {3}",
progress.Action,
progress.Block/(double)progress.TotalBlocks,
progress.FileSize.ToByteSize(),
var info = notification as StatusNotification;
if (info != null)
{
- StatusMessage = String.Format("Pithos {0}\r\n{1}",
- _fileVersion.Value.FileVersion,
- info.Title);
+ StatusMessage = info.Title;
return;
}
if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
return;
- ShowBalloonFor(notification);
+ if (notification.Level <= TraceLevel.Warning)
+ ShowBalloonFor(notification);
}
private void ShowBalloonFor(Notification notification)
BalloonIcon icon;
switch (notification.Level)
{
- case TraceLevel.Info:
- case TraceLevel.Verbose:
+ case TraceLevel.Verbose:
return;
+ case TraceLevel.Info:
+ icon = BalloonIcon.Info;
+ break;
case TraceLevel.Error:
icon = BalloonIcon.Error;
break;
var status=statusKeeper.GetFileStatus(localFileName);
return status;
}
+
+ public void RemoveAccountFromDatabase(AccountSettings account)
+ {
+ var statusKeeper = IoC.Get<IStatusKeeper>();
+ statusKeeper.ClearFolderStatus(account.RootPath);
+ }
}
}