2 /* -----------------------------------------------------------------------
3 * <copyright file="ShellViewModel.cs" company="GRNet">
5 * Copyright 2011-2012 GRNET S.A. All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
11 * 1. Redistributions of source code must retain the above
12 * copyright notice, this list of conditions and the following
15 * 2. Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer in the documentation and/or other materials
18 * provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
34 * The views and conclusions contained in the software and
35 * documentation are those of the authors and should not be
36 * interpreted as representing official policies, either expressed
37 * or implied, of GRNET S.A.
39 * -----------------------------------------------------------------------
42 using System.Collections.Concurrent;
43 using System.Diagnostics;
44 using System.Diagnostics.Contracts;
47 using System.Reflection;
48 using System.Runtime.InteropServices;
49 using System.ServiceModel;
50 using System.Threading.Tasks;
52 using System.Windows.Controls.Primitives;
53 using AppLimit.NetSparkle;
55 using Hardcodet.Wpf.TaskbarNotification;
56 using Pithos.Client.WPF.Configuration;
57 using Pithos.Client.WPF.FileProperties;
58 using Pithos.Client.WPF.Preferences;
59 using Pithos.Client.WPF.SelectiveSynch;
60 using Pithos.Client.WPF.Services;
61 using Pithos.Client.WPF.Shell;
63 using Pithos.Core.Agents;
64 using Pithos.Interfaces;
66 using System.Collections.Generic;
69 using StatusService = Pithos.Client.WPF.Services.StatusService;
71 namespace Pithos.Client.WPF {
72 using System.ComponentModel.Composition;
76 /// The "shell" of the Pithos application displays the taskbar icon, menu and notifications.
77 /// The shell also hosts the status service called by shell extensions to retrieve file info
80 /// It is a strange "shell" as its main visible element is an icon instead of a window
81 /// The shell subscribes to the following events:
82 /// * Notification: Raised by components that want to notify the user. Usually displayed in a balloon
83 /// * 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
84 /// * ShowFilePropertiesEvent: Raised when a shell command requests the display of the file/container properties dialog
86 //TODO: CODE SMELL Why does the shell handle the SelectiveSynchChanges?
87 [Export(typeof(IShell)), Export(typeof(ShellViewModel))]
88 public class ShellViewModel : Screen, IStatusNotification, IShell,
89 IHandle<Notification>, IHandle<SelectiveSynchChanges>, IHandle<ShowFilePropertiesEvent>
92 //The Status Checker provides the current synch state
93 //TODO: Could we remove the status checker and use events in its place?
94 private readonly IStatusChecker _statusChecker;
95 private readonly IEventAggregator _events;
97 public PithosSettings Settings { get; private set; }
100 private readonly ConcurrentDictionary<Uri, PithosMonitor> _monitors = new ConcurrentDictionary<Uri, PithosMonitor>();
102 /// Dictionary of account monitors, keyed by account
105 /// One monitor class is created for each account. The Shell needs access to the monitors to execute start/stop/pause commands,
106 /// retrieve account and boject info
108 // TODO: Does the Shell REALLY need access to the monitors? Could we achieve the same results with a better design?
109 // TODO: The monitors should be internal to Pithos.Core, even though exposing them makes coding of the Object and Container windows easier
110 public ConcurrentDictionary<Uri, PithosMonitor> Monitors
112 get { return _monitors; }
117 /// The status service is used by Shell extensions to retrieve file status information
119 //TODO: CODE SMELL! This is the shell! While hosting in the shell makes executing start/stop commands easier, it is still a smell
120 private ServiceHost _statusService;
122 //Logging in the Pithos client is provided by log4net
123 private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
125 private readonly PollAgent _pollAgent;
126 private readonly NetworkAgent _networkAgent;
129 private MiniStatusViewModel _miniStatus;
132 public MiniStatusViewModel MiniStatus
134 get { return _miniStatus; }
138 _miniStatus.Shell = this;
139 _miniStatus.Deactivated += (sender, arg) =>
141 _statusVisible = false;
142 NotifyOfPropertyChange(()=>MiniStatusCaption);
148 /// The Shell depends on MEF to provide implementations for windowManager, events, the status checker service and the settings
151 /// The PithosSettings class encapsulates the app's settings to abstract their storage mechanism (App settings, a database or registry)
153 [ImportingConstructor]
154 public ShellViewModel(IWindowManager windowManager, IEventAggregator events, IStatusChecker statusChecker, PithosSettings settings,PollAgent pollAgent,NetworkAgent networkAgent)
159 _windowManager = windowManager;
160 //CHECK: Caliburn doesn't need explicit command construction
161 //OpenPithosFolderCommand = new PithosCommand(OpenPithosFolder);
162 _statusChecker = statusChecker;
165 _events.Subscribe(this);
167 _pollAgent = pollAgent;
168 _networkAgent = networkAgent;
171 Proxy.SetFromSettings(settings);
173 StatusMessage = Settings.Accounts.Count==0
174 ? "No Accounts added\r\nPlease add an account"
177 _accounts.CollectionChanged += (sender, e) =>
179 NotifyOfPropertyChange(() => OpenFolderCaption);
180 NotifyOfPropertyChange(() => HasAccounts);
185 catch (Exception exc)
187 Log.Error("Error while starting the ShellViewModel",exc);
193 private void SetVersionMessage()
195 Assembly assembly = Assembly.GetExecutingAssembly();
196 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
197 VersionMessage = String.Format("Pithos+ {0}", fileVersion.FileVersion);
200 public void CurrentSyncStatus()
202 if (Accounts.Count == 0)
204 ShowPreferences("AccountTab");
209 _windowManager.ShowWindow(MiniStatus);
212 if (MiniStatus.IsActive)
213 MiniStatus.TryClose();
215 _statusVisible = !_statusVisible;
217 NotifyOfPropertyChange(() => MiniStatusCaption);
221 protected override void OnActivate()
227 //Must delay opening the upgrade window
228 //to avoid Windows Messages sent by the TaskbarIcon
229 TaskEx.Delay(5000).ContinueWith(_=>
230 Execute.OnUIThread(()=> _sparkle.StartLoop(true,Settings.UpdateForceCheck,Settings.UpdateCheckInterval)));
237 private void OnCheckFinished(object sender, bool updaterequired)
240 Log.InfoFormat("Upgrade check finished. Need Upgrade: {0}", updaterequired);
241 if (_manualUpgradeCheck)
243 _manualUpgradeCheck = false;
245 //Sparkle raises events on a background thread
246 Execute.OnUIThread(()=>
247 ShowBalloonFor(new Notification{Title="Pithos+ is up to date",Message="You have the latest Pithos+ version. No update is required"}));
251 private void OnUpgradeDetected(object sender, UpdateDetectedEventArgs e)
253 Log.InfoFormat("Update detected {0}",e.LatestVersion);
256 public void CheckForUpgrade()
258 ShowBalloonFor(new Notification{Title="Checking for upgrades",Message="Contacting the server to retrieve the latest Pithos+ version."});
260 _sparkle.updateDetected -= OnUpgradeDetected;
261 _sparkle.checkLoopFinished -= OnCheckFinished;
264 _manualUpgradeCheck = true;
266 _sparkle.StartLoop(true,true,Settings.UpdateCheckInterval);
269 private void InitializeSparkle()
271 _sparkle = new Sparkle(Settings.UpdateUrl);
272 _sparkle.updateDetected += OnUpgradeDetected;
273 _sparkle.checkLoopFinished += OnCheckFinished;
274 _sparkle.ShowDiagnosticWindow = Settings.UpdateDiagnostics;
277 private async void StartMonitoring()
281 if (Settings.IgnoreCertificateErrors)
283 ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
286 var accounts = Settings.Accounts.Select(MonitorAccount);
287 await TaskEx.WhenAll(accounts);
288 _statusService = StatusService.Start();
291 catch (AggregateException exc)
295 Log.Error("Error while starting monitoring", e);
302 protected override void OnDeactivate(bool close)
304 base.OnDeactivate(close);
307 StatusService.Stop(_statusService);
308 _statusService = null;
312 public Task MonitorAccount(AccountSettings account)
314 return Task.Factory.StartNew(() =>
316 PithosMonitor monitor;
317 var accountName = account.AccountName;
319 MigrateFolders(account);
321 if (Monitors.TryGetValue(account.AccountKey, out monitor))
323 //If the account is active
324 if (account.IsActive)
326 //The Api Key may have changed throuth the Preferences dialog
327 monitor.ApiKey = account.ApiKey;
328 Debug.Assert(monitor.StatusNotification == this,"An existing monitor should already have a StatusNotification service object");
329 monitor.RootPath = account.RootPath;
330 //Start the monitor. It's OK to start an already started monitor,
331 //it will just ignore the call
332 StartMonitor(monitor).Wait();
336 //If the account is inactive
337 //Stop and remove the monitor
338 RemoveMonitor(account.ServerUrl,accountName);
344 //Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
345 monitor = new PithosMonitor
347 UserName = accountName,
348 ApiKey = account.ApiKey,
349 StatusNotification = this,
350 RootPath = account.RootPath
352 //PithosMonitor uses MEF so we need to resolve it
353 IoC.BuildUp(monitor);
355 monitor.AuthenticationUrl = account.ServerUrl;
357 Monitors[account.AccountKey] = monitor;
359 if (account.IsActive)
361 //Don't start a monitor if it doesn't have an account and ApiKey
362 if (String.IsNullOrWhiteSpace(monitor.UserName) ||
363 String.IsNullOrWhiteSpace(monitor.ApiKey))
365 StartMonitor(monitor);
370 private void MigrateFolders(AccountSettings account)
372 var oldOthersFolder=Path.Combine(account.RootPath, FolderConstants.OldOthersFolder);
373 var newOthersFolder = Path.Combine(account.RootPath, FolderConstants.OthersFolder);
374 var oldFolder = new DirectoryInfo(oldOthersFolder);
375 var newFolder = new DirectoryInfo(newOthersFolder);
377 if (oldFolder.Exists && !newFolder.Exists)
379 oldFolder.MoveTo(newOthersFolder);
384 protected override void OnViewLoaded(object view)
387 var window = (Window)view;
388 TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
389 base.OnViewLoaded(view);
393 #region Status Properties
395 private string _statusMessage;
396 public string StatusMessage
398 get { return _statusMessage; }
401 _statusMessage = value;
402 NotifyOfPropertyChange(() => StatusMessage);
403 NotifyOfPropertyChange(() => TooltipMessage);
407 public string VersionMessage { get; set; }
409 public string TooltipMessage
413 return String.Format("{0}\r\n{1}",VersionMessage,StatusMessage);
417 public string TooltipMiniStatus
421 return String.Format("{0}\r\n{1}", "Status Window", "Enable / Dissable the stuatus window");
425 public string ToggleStatusWindowMessage
429 return String.Format("{0}" + Environment.NewLine + "{1} Toggle Mini Status");
433 private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
434 public ObservableConcurrentCollection<AccountInfo> Accounts
436 get { return _accounts; }
439 public bool HasAccounts
441 get { return _accounts.Count > 0; }
445 public string OpenFolderCaption
449 return (_accounts.Count == 0)
450 ? "No Accounts Defined"
451 : "Open Pithos Folder";
455 private string _pauseSyncCaption="Pause Synching";
456 public string PauseSyncCaption
458 get { return _pauseSyncCaption; }
461 _pauseSyncCaption = value;
462 NotifyOfPropertyChange(() => PauseSyncCaption);
466 private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
467 public ObservableConcurrentCollection<FileEntry> RecentFiles
469 get { return _recentFiles; }
473 private string _statusIcon="../Images/Pithos.ico";
474 public string StatusIcon
476 get { return _statusIcon; }
479 //TODO: Ensure all status icons use the Pithos logo
481 NotifyOfPropertyChange(() => StatusIcon);
489 public void CancelCurrentOperation()
491 _networkAgent.CancelCurrentOperation();
494 public void ShowPreferences()
496 ShowPreferences(null);
499 public void ShowPreferences(string currentTab)
502 var preferences = new PreferencesViewModel(_windowManager, _events, this, Settings,currentTab);
503 _windowManager.ShowDialog(preferences);
507 public void AboutPithos()
509 var about = IoC.Get<AboutViewModel>();
510 about.LatestVersion=_sparkle.LatestVersion;
511 _windowManager.ShowWindow(about);
514 public void SendFeedback()
516 var feedBack = IoC.Get<FeedbackViewModel>();
517 _windowManager.ShowWindow(feedBack);
520 //public PithosCommand OpenPithosFolderCommand { get; private set; }
522 public void OpenPithosFolder()
524 var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
527 Process.Start(account.RootPath);
530 public void OpenPithosFolder(AccountInfo account)
532 Process.Start(account.AccountPath);
537 public void GoToSite()
539 var site = Properties.Settings.Default.ProductionServer;
544 public void GoToSite(AccountInfo account)
546 var uri = account.SiteUri.Replace("http://","https://");
550 private bool _statusVisible;
552 public string MiniStatusCaption
556 return _statusVisible ? "Hide Status Window" : "Show Status Window";
560 public bool HasConflicts
564 public void ShowConflicts()
566 _windowManager.ShowWindow(IoC.Get<ConflictsViewModel>());
570 /// Open an explorer window to the target path's directory
571 /// and select the file
573 /// <param name="entry"></param>
574 public void GoToFile(FileEntry entry)
576 var fullPath = entry.FullPath;
577 if (!File.Exists(fullPath) && !Directory.Exists(fullPath))
579 Process.Start("explorer.exe","/select, " + fullPath);
582 public void OpenLogPath()
584 var pithosDataPath = PithosSettings.PithosDataPath;
586 Process.Start(pithosDataPath);
589 public void ShowFileProperties()
591 var account = Settings.Accounts.First(acc => acc.IsActive);
592 var dir = new DirectoryInfo(account.RootPath + @"\pithos");
593 var files=dir.GetFiles();
595 var idx=r.Next(0, files.Length);
596 ShowFileProperties(files[idx].FullName);
599 public void ShowFileProperties(string filePath)
601 if (String.IsNullOrWhiteSpace(filePath))
602 throw new ArgumentNullException("filePath");
603 if (!File.Exists(filePath) && !Directory.Exists(filePath))
604 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
605 Contract.EndContractBlock();
607 var pair=(from monitor in Monitors
608 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
609 select monitor).FirstOrDefault();
610 var accountMonitor = pair.Value;
612 if (accountMonitor == null)
615 var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
619 var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
620 _windowManager.ShowWindow(fileProperties);
623 public void ShowContainerProperties()
625 var account = Settings.Accounts.First(acc => acc.IsActive);
626 var dir = new DirectoryInfo(account.RootPath);
627 var fullName = (from folder in dir.EnumerateDirectories()
628 where (folder.Attributes & FileAttributes.Hidden) == 0
629 select folder.FullName).First();
630 ShowContainerProperties(fullName);
633 public void ShowContainerProperties(string filePath)
635 if (String.IsNullOrWhiteSpace(filePath))
636 throw new ArgumentNullException("filePath");
637 if (!Directory.Exists(filePath))
638 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
639 Contract.EndContractBlock();
641 var pair=(from monitor in Monitors
642 where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
643 select monitor).FirstOrDefault();
644 var accountMonitor = pair.Value;
645 var info = accountMonitor.GetContainerInfo(filePath);
649 var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
650 _windowManager.ShowWindow(containerProperties);
653 public void SynchNow()
655 _pollAgent.SynchNow();
658 public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
660 if (currentInfo==null)
661 throw new ArgumentNullException("currentInfo");
662 Contract.EndContractBlock();
663 var monitor = Monitors[currentInfo.AccountKey];
664 var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
668 public ContainerInfo RefreshContainerInfo(ContainerInfo container)
670 if (container == null)
671 throw new ArgumentNullException("container");
672 Contract.EndContractBlock();
674 var monitor = Monitors[container.AccountKey];
675 var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
679 private bool _isPaused;
682 get { return _isPaused; }
686 PauseSyncCaption = IsPaused ? "Resume syncing" : "Pause syncing";
687 var iconKey = IsPaused ? "TraySyncPaused" : "TrayInSynch";
688 StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
690 NotifyOfPropertyChange(() => IsPaused);
694 public void ToggleSynching()
697 foreach (var monitor in Monitors.Values)
699 monitor.Pause = IsPaused ;
701 _pollAgent.Pause = IsPaused;
702 _networkAgent.Pause = IsPaused;
707 public void ExitPithos()
712 foreach (var monitor in Monitors.Select(pair => pair.Value))
717 var view = GetView() as Window;
721 catch (Exception exc)
723 Log.Info("Exception while exiting", exc);
727 Application.Current.Shutdown();
734 private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
736 new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
737 new StatusInfo(PithosStatus.PollSyncing, "Polling Files", "TraySynching"),
738 new StatusInfo(PithosStatus.LocalSyncing, "Syncing Files", "TraySynching"),
739 new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
740 }.ToDictionary(s => s.Status);
742 readonly IWindowManager _windowManager;
744 //private int _syncCount=0;
747 private PithosStatus _pithosStatus = PithosStatus.Disconnected;
749 public void SetPithosStatus(PithosStatus status)
751 if (_pithosStatus == PithosStatus.LocalSyncing && status == PithosStatus.PollComplete)
753 if (_pithosStatus == PithosStatus.PollSyncing && status == PithosStatus.LocalComplete)
755 if (status == PithosStatus.LocalComplete || status == PithosStatus.PollComplete)
756 _pithosStatus = PithosStatus.InSynch;
758 _pithosStatus = status;
762 public void SetPithosStatus(PithosStatus status,string message)
764 StatusMessage = message;
765 SetPithosStatus(status);
768 /* public Notifier GetNotifier(Notification startNotification, Notification endNotification)
770 return new Notifier(this, startNotification, endNotification);
773 public Notifier GetNotifier(string startMessage, string endMessage, params object[] args)
775 return new Notifier(this,
776 new StatusNotification(String.Format(startMessage,args)),
777 new StatusNotification(String.Format(endMessage,args)));
782 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat
784 public void UpdateStatus()
787 if (_iconNames.ContainsKey(_pithosStatus))
789 var info = _iconNames[_pithosStatus];
790 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
793 if (_pithosStatus == PithosStatus.InSynch)
794 StatusMessage = "All files up to date";
799 private Task StartMonitor(PithosMonitor monitor,int retries=0)
801 return Task.Factory.StartNew(() =>
803 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
807 Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
811 catch (WebException exc)
813 if (AbandonRetry(monitor, retries))
816 HttpStatusCode statusCode =HttpStatusCode.OK;
817 var response = exc.Response as HttpWebResponse;
819 statusCode = response.StatusCode;
823 case HttpStatusCode.Unauthorized:
824 var message = String.Format("API Key Expired for {0}. Starting Renewal",
826 Log.Error(message, exc);
827 var account = Settings.Accounts.Find(acc => acc.AccountKey == new Uri(new Uri(monitor.AuthenticationUrl), monitor.UserName));
828 account.IsExpired = true;
829 Notify(new ExpirationNotification(account));
830 //TryAuthorize(monitor.UserName, retries).Wait();
832 case HttpStatusCode.ProxyAuthenticationRequired:
833 TryAuthenticateProxy(monitor,retries);
836 TryLater(monitor, exc, retries);
840 catch (Exception exc)
842 if (AbandonRetry(monitor, retries))
845 TryLater(monitor,exc,retries);
851 private void TryAuthenticateProxy(PithosMonitor monitor,int retries)
853 Execute.OnUIThread(() =>
855 var proxyAccount = IoC.Get<ProxyAccountViewModel>();
856 proxyAccount.Settings = Settings;
857 if (true != _windowManager.ShowDialog(proxyAccount))
859 StartMonitor(monitor, retries);
860 NotifyOfPropertyChange(() => Accounts);
864 private bool AbandonRetry(PithosMonitor monitor, int retries)
868 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
870 _events.Publish(new Notification
871 {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
878 private void TryLater(PithosMonitor monitor, Exception exc,int retries)
880 var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
881 Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
882 _events.Publish(new Notification
883 {Title = "Error", Message = message, Level = TraceLevel.Error});
884 Log.Error(message, exc);
888 public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
890 StatusMessage = status;
892 _events.Publish(new Notification { Title = "Pithos+", Message = status, Level = level });
895 public void NotifyChangedFile(string filePath)
897 if (RecentFiles.Any(e => e.FullPath == filePath))
900 IProducerConsumerCollection<FileEntry> files=RecentFiles;
902 while (files.Count > 5)
903 files.TryTake(out popped);
904 var entry = new FileEntry { FullPath = filePath };
908 public void NotifyAccount(AccountInfo account)
912 //TODO: What happens to an existing account whose Token has changed?
913 account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
914 account.SiteUri, Uri.EscapeDataString(account.Token),
915 Uri.EscapeDataString(account.UserName));
917 if (!Accounts.Any(item => item.UserName == account.UserName && item.SiteUri == account.SiteUri))
918 Accounts.TryAdd(account);
922 public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
924 if (conflictFiles == null)
926 //Convert to list to avoid multiple iterations
927 var files = conflictFiles.ToList();
932 //TODO: Create a more specific message. For now, just show a warning
933 NotifyForFiles(files,message,TraceLevel.Warning);
937 public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info)
944 StatusMessage = message;
946 _events.Publish(new Notification { Title = "Pithos+", Message = message, Level = level});
949 public void Notify(Notification notification)
951 _events.Publish(notification);
955 public void RemoveMonitor(string serverUrl,string accountName)
957 if (String.IsNullOrWhiteSpace(accountName))
960 var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName && account.StorageUri.ToString().StartsWith(serverUrl));
961 if (accountInfo != null)
963 _accounts.TryRemove(accountInfo);
964 _pollAgent.RemoveAccount(accountInfo);
967 var accountKey = new Uri(new Uri(serverUrl),accountName);
968 PithosMonitor monitor;
969 if (Monitors.TryRemove(accountKey, out monitor))
972 //TODO: Also remove any pending actions for this account
973 //from the network queue
977 public void RefreshOverlays()
979 foreach (var pair in Monitors)
981 var monitor = pair.Value;
983 var path = monitor.RootPath;
985 if (String.IsNullOrWhiteSpace(path))
988 if (!Directory.Exists(path) && !File.Exists(path))
991 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
995 NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
996 HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
997 pathPointer, IntPtr.Zero);
1001 Marshal.FreeHGlobal(pathPointer);
1006 #region Event Handlers
1008 public void Handle(SelectiveSynchChanges message)
1012 PithosMonitor monitor;
1013 if (Monitors.TryGetValue(message.Account.AccountKey, out monitor))
1015 monitor.Selectives.SetIsSelectiveEnabled(message.Account.AccountKey, message.Enabled);
1016 monitor.SetSelectivePaths(message.Uris, message.Added, message.Removed);
1019 var account = Accounts.FirstOrDefault(acc => acc.AccountKey == message.Account.AccountKey);
1020 if (account != null)
1022 this._pollAgent.SetSelectivePaths(account, message.Added, message.Removed);
1029 private bool _pollStarted;
1030 private Sparkle _sparkle;
1031 private bool _manualUpgradeCheck;
1033 //SMELL: Doing so much work for notifications in the shell is wrong
1034 //The notifications should be moved to their own view/viewmodel pair
1035 //and different templates should be used for different message types
1036 //This will also allow the addition of extra functionality, eg. actions
1038 public void Handle(Notification notification)
1042 if (!Settings.ShowDesktopNotifications)
1045 if (notification is PollNotification)
1047 _pollStarted = true;
1050 if (notification is CloudNotification)
1054 _pollStarted= false;
1055 notification.Title = "Pithos+";
1056 notification.Message = "Start Synchronisation";
1059 var deleteNotification = notification as CloudDeleteNotification;
1060 if (deleteNotification != null)
1062 StatusMessage = String.Format("Deleted {0}", deleteNotification.Data.Name);
1066 var progress = notification as ProgressNotification;
1069 if (progress != null)
1071 StatusMessage = String.Format("{0} {1:p2} of {2} - {3}",
1073 progress.Block/(double)progress.TotalBlocks,
1074 progress.FileSize.ToByteSize(),
1079 var info = notification as StatusNotification;
1082 StatusMessage = info.Title;
1085 if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title))
1088 if (notification.Level <= TraceLevel.Warning)
1089 ShowBalloonFor(notification);
1092 private void ShowBalloonFor(Notification notification)
1094 Contract.Requires(notification!=null);
1096 if (!Settings.ShowDesktopNotifications)
1100 switch (notification.Level)
1102 case TraceLevel.Verbose:
1104 case TraceLevel.Info:
1105 icon = BalloonIcon.Info;
1107 case TraceLevel.Error:
1108 icon = BalloonIcon.Error;
1110 case TraceLevel.Warning:
1111 icon = BalloonIcon.Warning;
1117 var tv = (ShellView) GetView();
1118 System.Action clickAction = null;
1119 if (notification is ExpirationNotification)
1121 clickAction = () => ShowPreferences("AccountTab");
1123 var balloon = new PithosBalloon
1125 Title = notification.Title,
1126 Message = notification.Message,
1128 ClickAction = clickAction
1130 tv.TaskbarView.ShowCustomBalloon(balloon, PopupAnimation.Fade, 4000);
1135 public void Handle(ShowFilePropertiesEvent message)
1137 if (message == null)
1138 throw new ArgumentNullException("message");
1139 if (String.IsNullOrWhiteSpace(message.FileName) )
1140 throw new ArgumentException("message");
1141 Contract.EndContractBlock();
1143 var fileName = message.FileName;
1144 //TODO: Display file properties for non-container folders
1145 if (File.Exists(fileName))
1146 //Retrieve the full name with exact casing. Pithos names are case sensitive
1147 ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
1148 else if (Directory.Exists(fileName))
1149 //Retrieve the full name with exact casing. Pithos names are case sensitive
1151 var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
1152 if (IsContainer(path))
1153 ShowContainerProperties(path);
1155 ShowFileProperties(path);
1159 private bool IsContainer(string path)
1161 var matchingFolders = from account in _accounts
1162 from rootFolder in Directory.GetDirectories(account.AccountPath)
1163 where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
1165 return matchingFolders.Any();
1168 public FileStatus GetFileStatus(string localFileName)
1170 if (String.IsNullOrWhiteSpace(localFileName))
1171 throw new ArgumentNullException("localFileName");
1172 Contract.EndContractBlock();
1174 var statusKeeper = IoC.Get<IStatusKeeper>();
1175 var status=statusKeeper.GetFileStatus(localFileName);
1179 public void RemoveAccountFromDatabase(AccountSettings account)
1181 var statusKeeper = IoC.Get<IStatusKeeper>();
1182 statusKeeper.ClearFolderStatus(account.RootPath);