root / trunk / Pithos.Client.WPF / Shell / ShellViewModel.cs @ 43dd02a8
History | View | Annotate | Download (36.5 kB)
1 |
#region |
---|---|
2 |
/* ----------------------------------------------------------------------- |
3 |
* <copyright file="ShellViewModel.cs" company="GRNet"> |
4 |
* |
5 |
* Copyright 2011-2012 GRNET S.A. All rights reserved. |
6 |
* |
7 |
* Redistribution and use in source and binary forms, with or |
8 |
* without modification, are permitted provided that the following |
9 |
* conditions are met: |
10 |
* |
11 |
* 1. Redistributions of source code must retain the above |
12 |
* copyright notice, this list of conditions and the following |
13 |
* disclaimer. |
14 |
* |
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. |
19 |
* |
20 |
* |
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. |
33 |
* |
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. |
38 |
* </copyright> |
39 |
* ----------------------------------------------------------------------- |
40 |
*/ |
41 |
#endregion |
42 |
using System.Collections.Concurrent; |
43 |
using System.Diagnostics; |
44 |
using System.Diagnostics.Contracts; |
45 |
using System.IO; |
46 |
using System.Net; |
47 |
using System.Reflection; |
48 |
using System.Runtime.InteropServices; |
49 |
using System.ServiceModel; |
50 |
using System.Threading.Tasks; |
51 |
using System.Windows; |
52 |
using System.Windows.Controls.Primitives; |
53 |
using AppLimit.NetSparkle; |
54 |
using Caliburn.Micro; |
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; |
62 |
using Pithos.Core; |
63 |
using Pithos.Core.Agents; |
64 |
using Pithos.Interfaces; |
65 |
using System; |
66 |
using System.Collections.Generic; |
67 |
using System.Linq; |
68 |
using Pithos.Network; |
69 |
using StatusService = Pithos.Client.WPF.Services.StatusService; |
70 |
|
71 |
namespace Pithos.Client.WPF { |
72 |
using System.ComponentModel.Composition; |
73 |
|
74 |
|
75 |
///<summary> |
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 |
78 |
///</summary> |
79 |
///<remarks> |
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 |
85 |
///</remarks> |
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> |
90 |
{ |
91 |
|
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; |
96 |
|
97 |
public PithosSettings Settings { get; private set; } |
98 |
|
99 |
|
100 |
private readonly ConcurrentDictionary<Uri, PithosMonitor> _monitors = new ConcurrentDictionary<Uri, PithosMonitor>(); |
101 |
///<summary> |
102 |
/// Dictionary of account monitors, keyed by account |
103 |
///</summary> |
104 |
///<remarks> |
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 |
107 |
///</remarks> |
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 |
111 |
{ |
112 |
get { return _monitors; } |
113 |
} |
114 |
|
115 |
|
116 |
///<summary> |
117 |
/// The status service is used by Shell extensions to retrieve file status information |
118 |
///</summary> |
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; |
121 |
|
122 |
//Logging in the Pithos client is provided by log4net |
123 |
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); |
124 |
|
125 |
private readonly PollAgent _pollAgent; |
126 |
private readonly NetworkAgent _networkAgent; |
127 |
|
128 |
[Import] |
129 |
public Selectives Selectives { get; set; } |
130 |
|
131 |
private MiniStatusViewModel _miniStatus; |
132 |
|
133 |
[Import] |
134 |
public MiniStatusViewModel MiniStatus |
135 |
{ |
136 |
get { return _miniStatus; } |
137 |
set |
138 |
{ |
139 |
_miniStatus = value; |
140 |
_miniStatus.Shell = this; |
141 |
_miniStatus.Deactivated += (sender, arg) => |
142 |
{ |
143 |
_statusVisible = false; |
144 |
NotifyOfPropertyChange(()=>MiniStatusCaption); |
145 |
}; |
146 |
} |
147 |
} |
148 |
|
149 |
///<summary> |
150 |
/// The Shell depends on MEF to provide implementations for windowManager, events, the status checker service and the settings |
151 |
///</summary> |
152 |
///<remarks> |
153 |
/// The PithosSettings class encapsulates the app's settings to abstract their storage mechanism (App settings, a database or registry) |
154 |
///</remarks> |
155 |
[ImportingConstructor] |
156 |
public ShellViewModel(IWindowManager windowManager, IEventAggregator events, IStatusChecker statusChecker, PithosSettings settings,PollAgent pollAgent,NetworkAgent networkAgent) |
157 |
{ |
158 |
try |
159 |
{ |
160 |
|
161 |
_windowManager = windowManager; |
162 |
//CHECK: Caliburn doesn't need explicit command construction |
163 |
//OpenPithosFolderCommand = new PithosCommand(OpenPithosFolder); |
164 |
_statusChecker = statusChecker; |
165 |
//The event subst |
166 |
_events = events; |
167 |
_events.Subscribe(this); |
168 |
|
169 |
_pollAgent = pollAgent; |
170 |
_networkAgent = networkAgent; |
171 |
Settings = settings; |
172 |
|
173 |
Proxy.SetFromSettings(settings); |
174 |
|
175 |
StatusMessage = Settings.Accounts.Count==0 |
176 |
? "No Accounts added\r\nPlease add an account" |
177 |
: "Starting"; |
178 |
|
179 |
_accounts.CollectionChanged += (sender, e) => |
180 |
{ |
181 |
NotifyOfPropertyChange(() => OpenFolderCaption); |
182 |
NotifyOfPropertyChange(() => HasAccounts); |
183 |
}; |
184 |
|
185 |
SetVersionMessage(); |
186 |
} |
187 |
catch (Exception exc) |
188 |
{ |
189 |
Log.Error("Error while starting the ShellViewModel",exc); |
190 |
throw; |
191 |
} |
192 |
|
193 |
} |
194 |
|
195 |
private void SetVersionMessage() |
196 |
{ |
197 |
Assembly assembly = Assembly.GetExecutingAssembly(); |
198 |
var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location); |
199 |
VersionMessage = String.Format("Pithos+ {0}", fileVersion.FileVersion); |
200 |
} |
201 |
|
202 |
public void CurrentSyncStatus() |
203 |
{ |
204 |
if (Accounts.Count == 0) |
205 |
{ |
206 |
ShowPreferences("AccountTab"); |
207 |
} |
208 |
else |
209 |
{ |
210 |
if (!_statusVisible) |
211 |
_windowManager.ShowWindow(MiniStatus); |
212 |
else |
213 |
{ |
214 |
if (MiniStatus.IsActive) |
215 |
MiniStatus.TryClose(); |
216 |
} |
217 |
_statusVisible = !_statusVisible; |
218 |
|
219 |
NotifyOfPropertyChange(() => MiniStatusCaption); |
220 |
} |
221 |
} |
222 |
|
223 |
protected override void OnActivate() |
224 |
{ |
225 |
base.OnActivate(); |
226 |
|
227 |
InitializeSparkle(); |
228 |
|
229 |
//Must delay opening the upgrade window |
230 |
//to avoid Windows Messages sent by the TaskbarIcon |
231 |
TaskEx.Delay(5000).ContinueWith(_=> |
232 |
Execute.OnUIThread(()=> _sparkle.StartLoop(true,Settings.UpdateForceCheck,Settings.UpdateCheckInterval))); |
233 |
|
234 |
|
235 |
StartMonitoring(); |
236 |
} |
237 |
|
238 |
|
239 |
private void OnCheckFinished(object sender, bool updaterequired) |
240 |
{ |
241 |
|
242 |
Log.InfoFormat("Upgrade check finished. Need Upgrade: {0}", updaterequired); |
243 |
if (_manualUpgradeCheck) |
244 |
{ |
245 |
_manualUpgradeCheck = false; |
246 |
if (!updaterequired) |
247 |
//Sparkle raises events on a background thread |
248 |
Execute.OnUIThread(()=> |
249 |
ShowBalloonFor(new Notification{Title="Pithos+ is up to date",Message="You have the latest Pithos+ version. No update is required"})); |
250 |
} |
251 |
} |
252 |
|
253 |
private void OnUpgradeDetected(object sender, UpdateDetectedEventArgs e) |
254 |
{ |
255 |
Log.InfoFormat("Update detected {0}",e.LatestVersion); |
256 |
} |
257 |
|
258 |
public void CheckForUpgrade() |
259 |
{ |
260 |
ShowBalloonFor(new Notification{Title="Checking for upgrades",Message="Contacting the server to retrieve the latest Pithos+ version."}); |
261 |
_sparkle.StopLoop(); |
262 |
_sparkle.updateDetected -= OnUpgradeDetected; |
263 |
_sparkle.checkLoopFinished -= OnCheckFinished; |
264 |
_sparkle.Dispose(); |
265 |
|
266 |
_manualUpgradeCheck = true; |
267 |
InitializeSparkle(); |
268 |
_sparkle.StartLoop(true,true,Settings.UpdateCheckInterval); |
269 |
} |
270 |
|
271 |
private void InitializeSparkle() |
272 |
{ |
273 |
_sparkle = new Sparkle(Settings.UpdateUrl); |
274 |
_sparkle.updateDetected += OnUpgradeDetected; |
275 |
_sparkle.checkLoopFinished += OnCheckFinished; |
276 |
_sparkle.ShowDiagnosticWindow = Settings.UpdateDiagnostics; |
277 |
} |
278 |
|
279 |
private async void StartMonitoring() |
280 |
{ |
281 |
try |
282 |
{ |
283 |
if (Settings.IgnoreCertificateErrors) |
284 |
{ |
285 |
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; |
286 |
} |
287 |
|
288 |
var accounts = Settings.Accounts.Select(MonitorAccount); |
289 |
await TaskEx.WhenAll(accounts); |
290 |
_statusService = StatusService.Start(); |
291 |
|
292 |
} |
293 |
catch (AggregateException exc) |
294 |
{ |
295 |
exc.Handle(e => |
296 |
{ |
297 |
Log.Error("Error while starting monitoring", e); |
298 |
return true; |
299 |
}); |
300 |
throw; |
301 |
} |
302 |
} |
303 |
|
304 |
protected override void OnDeactivate(bool close) |
305 |
{ |
306 |
base.OnDeactivate(close); |
307 |
if (close) |
308 |
{ |
309 |
StatusService.Stop(_statusService); |
310 |
_statusService = null; |
311 |
} |
312 |
} |
313 |
|
314 |
public Task MonitorAccount(AccountSettings account) |
315 |
{ |
316 |
return Task.Factory.StartNew(() => |
317 |
{ |
318 |
PithosMonitor monitor; |
319 |
var accountName = account.AccountName; |
320 |
|
321 |
MigrateFolders(account); |
322 |
|
323 |
Selectives.SetIsSelectiveEnabled(account.AccountKey, account.SelectiveSyncEnabled); |
324 |
|
325 |
if (Monitors.TryGetValue(account.AccountKey, out monitor)) |
326 |
{ |
327 |
//If the account is active |
328 |
if (account.IsActive) |
329 |
{ |
330 |
//The Api Key may have changed throuth the Preferences dialog |
331 |
monitor.ApiKey = account.ApiKey; |
332 |
Debug.Assert(monitor.StatusNotification == this,"An existing monitor should already have a StatusNotification service object"); |
333 |
monitor.RootPath = account.RootPath; |
334 |
//Start the monitor. It's OK to start an already started monitor, |
335 |
//it will just ignore the call |
336 |
StartMonitor(monitor).Wait(); |
337 |
} |
338 |
else |
339 |
{ |
340 |
//If the account is inactive |
341 |
//Stop and remove the monitor |
342 |
RemoveMonitor(account.ServerUrl,accountName); |
343 |
} |
344 |
return; |
345 |
} |
346 |
|
347 |
|
348 |
//Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors |
349 |
monitor = new PithosMonitor |
350 |
{ |
351 |
UserName = accountName, |
352 |
ApiKey = account.ApiKey, |
353 |
StatusNotification = this, |
354 |
RootPath = account.RootPath |
355 |
}; |
356 |
//PithosMonitor uses MEF so we need to resolve it |
357 |
IoC.BuildUp(monitor); |
358 |
|
359 |
monitor.AuthenticationUrl = account.ServerUrl; |
360 |
|
361 |
Monitors[account.AccountKey] = monitor; |
362 |
|
363 |
if (account.IsActive) |
364 |
{ |
365 |
//Don't start a monitor if it doesn't have an account and ApiKey |
366 |
if (String.IsNullOrWhiteSpace(monitor.UserName) || |
367 |
String.IsNullOrWhiteSpace(monitor.ApiKey)) |
368 |
return; |
369 |
StartMonitor(monitor); |
370 |
} |
371 |
}); |
372 |
} |
373 |
|
374 |
private void MigrateFolders(AccountSettings account) |
375 |
{ |
376 |
var oldOthersFolder=Path.Combine(account.RootPath, FolderConstants.OldOthersFolder); |
377 |
var newOthersFolder = Path.Combine(account.RootPath, FolderConstants.OthersFolder); |
378 |
var oldFolder = new DirectoryInfo(oldOthersFolder); |
379 |
var newFolder = new DirectoryInfo(newOthersFolder); |
380 |
|
381 |
if (oldFolder.Exists && !newFolder.Exists) |
382 |
{ |
383 |
oldFolder.MoveTo(newOthersFolder); |
384 |
} |
385 |
} |
386 |
|
387 |
|
388 |
protected override void OnViewLoaded(object view) |
389 |
{ |
390 |
UpdateStatus(); |
391 |
var window = (Window)view; |
392 |
TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide)); |
393 |
base.OnViewLoaded(view); |
394 |
} |
395 |
|
396 |
|
397 |
#region Status Properties |
398 |
|
399 |
private string _statusMessage; |
400 |
public string StatusMessage |
401 |
{ |
402 |
get { return _statusMessage; } |
403 |
set |
404 |
{ |
405 |
_statusMessage = value; |
406 |
NotifyOfPropertyChange(() => StatusMessage); |
407 |
NotifyOfPropertyChange(() => TooltipMessage); |
408 |
} |
409 |
} |
410 |
|
411 |
public string VersionMessage { get; set; } |
412 |
|
413 |
public string TooltipMessage |
414 |
{ |
415 |
get |
416 |
{ |
417 |
return String.Format("{0}\r\n{1}",VersionMessage,StatusMessage); |
418 |
} |
419 |
} |
420 |
|
421 |
public string TooltipMiniStatus |
422 |
{ |
423 |
get |
424 |
{ |
425 |
return String.Format("{0}\r\n{1}", "Status Window", "Enable / Dissable the stuatus window"); |
426 |
} |
427 |
} |
428 |
|
429 |
public string ToggleStatusWindowMessage |
430 |
{ |
431 |
get |
432 |
{ |
433 |
return String.Format("{0}" + Environment.NewLine + "{1} Toggle Mini Status"); |
434 |
} |
435 |
} |
436 |
|
437 |
private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>(); |
438 |
public ObservableConcurrentCollection<AccountInfo> Accounts |
439 |
{ |
440 |
get { return _accounts; } |
441 |
} |
442 |
|
443 |
public bool HasAccounts |
444 |
{ |
445 |
get { return _accounts.Count > 0; } |
446 |
} |
447 |
|
448 |
|
449 |
public string OpenFolderCaption |
450 |
{ |
451 |
get |
452 |
{ |
453 |
return (_accounts.Count == 0) |
454 |
? "No Accounts Defined" |
455 |
: "Open Pithos Folder"; |
456 |
} |
457 |
} |
458 |
|
459 |
private string _pauseSyncCaption="Pause Synching"; |
460 |
public string PauseSyncCaption |
461 |
{ |
462 |
get { return _pauseSyncCaption; } |
463 |
set |
464 |
{ |
465 |
_pauseSyncCaption = value; |
466 |
NotifyOfPropertyChange(() => PauseSyncCaption); |
467 |
} |
468 |
} |
469 |
|
470 |
private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>(); |
471 |
public ObservableConcurrentCollection<FileEntry> RecentFiles |
472 |
{ |
473 |
get { return _recentFiles; } |
474 |
} |
475 |
|
476 |
|
477 |
private string _statusIcon="../Images/Pithos.ico"; |
478 |
public string StatusIcon |
479 |
{ |
480 |
get { return _statusIcon; } |
481 |
set |
482 |
{ |
483 |
//TODO: Ensure all status icons use the Pithos logo |
484 |
_statusIcon = value; |
485 |
NotifyOfPropertyChange(() => StatusIcon); |
486 |
} |
487 |
} |
488 |
|
489 |
#endregion |
490 |
|
491 |
#region Commands |
492 |
|
493 |
public void CancelCurrentOperation() |
494 |
{ |
495 |
_networkAgent.CancelCurrentOperation(); |
496 |
} |
497 |
|
498 |
public void ShowPreferences() |
499 |
{ |
500 |
ShowPreferences(null); |
501 |
} |
502 |
|
503 |
public void ShowPreferences(string currentTab) |
504 |
{ |
505 |
//Settings.Reload(); |
506 |
var preferences = new PreferencesViewModel(_windowManager, _events, this, Settings,currentTab); |
507 |
_windowManager.ShowDialog(preferences); |
508 |
|
509 |
} |
510 |
|
511 |
public void AboutPithos() |
512 |
{ |
513 |
var about = IoC.Get<AboutViewModel>(); |
514 |
about.LatestVersion=_sparkle.LatestVersion; |
515 |
_windowManager.ShowWindow(about); |
516 |
} |
517 |
|
518 |
public void SendFeedback() |
519 |
{ |
520 |
var feedBack = IoC.Get<FeedbackViewModel>(); |
521 |
_windowManager.ShowWindow(feedBack); |
522 |
} |
523 |
|
524 |
//public PithosCommand OpenPithosFolderCommand { get; private set; } |
525 |
|
526 |
public void OpenPithosFolder() |
527 |
{ |
528 |
var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive); |
529 |
if (account == null) |
530 |
return; |
531 |
Process.Start(account.RootPath); |
532 |
} |
533 |
|
534 |
public void OpenPithosFolder(AccountInfo account) |
535 |
{ |
536 |
Process.Start(account.AccountPath); |
537 |
} |
538 |
|
539 |
|
540 |
|
541 |
public void GoToSite() |
542 |
{ |
543 |
var site = Properties.Settings.Default.ProductionServer; |
544 |
Process.Start(site); |
545 |
} |
546 |
|
547 |
|
548 |
public void GoToSite(AccountInfo account) |
549 |
{ |
550 |
var uri = account.SiteUri.Replace("http://","https://"); |
551 |
Process.Start(uri); |
552 |
} |
553 |
|
554 |
private bool _statusVisible; |
555 |
|
556 |
public string MiniStatusCaption |
557 |
{ |
558 |
get |
559 |
{ |
560 |
return _statusVisible ? "Hide Status Window" : "Show Status Window"; |
561 |
} |
562 |
} |
563 |
|
564 |
public bool HasConflicts |
565 |
{ |
566 |
get { return true; } |
567 |
} |
568 |
public void ShowConflicts() |
569 |
{ |
570 |
_windowManager.ShowWindow(IoC.Get<ConflictsViewModel>()); |
571 |
} |
572 |
|
573 |
/// <summary> |
574 |
/// Open an explorer window to the target path's directory |
575 |
/// and select the file |
576 |
/// </summary> |
577 |
/// <param name="entry"></param> |
578 |
public void GoToFile(FileEntry entry) |
579 |
{ |
580 |
var fullPath = entry.FullPath; |
581 |
if (!File.Exists(fullPath) && !Directory.Exists(fullPath)) |
582 |
return; |
583 |
Process.Start("explorer.exe","/select, " + fullPath); |
584 |
} |
585 |
|
586 |
public void OpenLogPath() |
587 |
{ |
588 |
var pithosDataPath = PithosSettings.PithosDataPath; |
589 |
|
590 |
Process.Start(pithosDataPath); |
591 |
} |
592 |
|
593 |
public void ShowFileProperties() |
594 |
{ |
595 |
var account = Settings.Accounts.First(acc => acc.IsActive); |
596 |
var dir = new DirectoryInfo(account.RootPath + @"\pithos"); |
597 |
var files=dir.GetFiles(); |
598 |
var r=new Random(); |
599 |
var idx=r.Next(0, files.Length); |
600 |
ShowFileProperties(files[idx].FullName); |
601 |
} |
602 |
|
603 |
public void ShowFileProperties(string filePath) |
604 |
{ |
605 |
if (String.IsNullOrWhiteSpace(filePath)) |
606 |
throw new ArgumentNullException("filePath"); |
607 |
if (!File.Exists(filePath) && !Directory.Exists(filePath)) |
608 |
throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath"); |
609 |
Contract.EndContractBlock(); |
610 |
|
611 |
var pair=(from monitor in Monitors |
612 |
where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase) |
613 |
select monitor).FirstOrDefault(); |
614 |
var accountMonitor = pair.Value; |
615 |
|
616 |
if (accountMonitor == null) |
617 |
return; |
618 |
|
619 |
var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath)); |
620 |
|
621 |
|
622 |
|
623 |
var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath); |
624 |
_windowManager.ShowWindow(fileProperties); |
625 |
} |
626 |
|
627 |
public void ShowContainerProperties() |
628 |
{ |
629 |
var account = Settings.Accounts.First(acc => acc.IsActive); |
630 |
var dir = new DirectoryInfo(account.RootPath); |
631 |
var fullName = (from folder in dir.EnumerateDirectories() |
632 |
where (folder.Attributes & FileAttributes.Hidden) == 0 |
633 |
select folder.FullName).First(); |
634 |
ShowContainerProperties(fullName); |
635 |
} |
636 |
|
637 |
public void ShowContainerProperties(string filePath) |
638 |
{ |
639 |
if (String.IsNullOrWhiteSpace(filePath)) |
640 |
throw new ArgumentNullException("filePath"); |
641 |
if (!Directory.Exists(filePath)) |
642 |
throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath"); |
643 |
Contract.EndContractBlock(); |
644 |
|
645 |
var pair=(from monitor in Monitors |
646 |
where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase) |
647 |
select monitor).FirstOrDefault(); |
648 |
var accountMonitor = pair.Value; |
649 |
var info = accountMonitor.GetContainerInfo(filePath); |
650 |
|
651 |
|
652 |
|
653 |
var containerProperties = new ContainerPropertiesViewModel(this, info,filePath); |
654 |
_windowManager.ShowWindow(containerProperties); |
655 |
} |
656 |
|
657 |
public void SynchNow() |
658 |
{ |
659 |
_pollAgent.SynchNow(); |
660 |
} |
661 |
|
662 |
public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo) |
663 |
{ |
664 |
if (currentInfo==null) |
665 |
throw new ArgumentNullException("currentInfo"); |
666 |
Contract.EndContractBlock(); |
667 |
var monitor = Monitors[currentInfo.AccountKey]; |
668 |
var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name); |
669 |
return newInfo; |
670 |
} |
671 |
|
672 |
public ContainerInfo RefreshContainerInfo(ContainerInfo container) |
673 |
{ |
674 |
if (container == null) |
675 |
throw new ArgumentNullException("container"); |
676 |
Contract.EndContractBlock(); |
677 |
|
678 |
var monitor = Monitors[container.AccountKey]; |
679 |
var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name); |
680 |
return newInfo; |
681 |
} |
682 |
|
683 |
private bool _isPaused; |
684 |
public bool IsPaused |
685 |
{ |
686 |
get { return _isPaused; } |
687 |
set |
688 |
{ |
689 |
_isPaused = value; |
690 |
PauseSyncCaption = IsPaused ? "Resume syncing" : "Pause syncing"; |
691 |
var iconKey = IsPaused ? "TraySyncPaused" : "TrayInSynch"; |
692 |
StatusIcon = String.Format(@"../Images/{0}.ico", iconKey); |
693 |
|
694 |
NotifyOfPropertyChange(() => IsPaused); |
695 |
} |
696 |
} |
697 |
|
698 |
public void ToggleSynching() |
699 |
{ |
700 |
IsPaused=!IsPaused; |
701 |
foreach (var monitor in Monitors.Values) |
702 |
{ |
703 |
monitor.Pause = IsPaused ; |
704 |
} |
705 |
_pollAgent.Pause = IsPaused; |
706 |
_networkAgent.Pause = IsPaused; |
707 |
|
708 |
|
709 |
} |
710 |
|
711 |
public void ExitPithos() |
712 |
{ |
713 |
try |
714 |
{ |
715 |
|
716 |
foreach (var monitor in Monitors.Select(pair => pair.Value)) |
717 |
{ |
718 |
monitor.Stop(); |
719 |
} |
720 |
|
721 |
var view = GetView() as Window; |
722 |
if (view != null) |
723 |
view.Close(); |
724 |
} |
725 |
catch (Exception exc) |
726 |
{ |
727 |
Log.Info("Exception while exiting", exc); |
728 |
} |
729 |
finally |
730 |
{ |
731 |
Application.Current.Shutdown(); |
732 |
} |
733 |
} |
734 |
|
735 |
#endregion |
736 |
|
737 |
|
738 |
private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo> |
739 |
{ |
740 |
new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"), |
741 |
new StatusInfo(PithosStatus.PollSyncing, "Polling Files", "TraySynching"), |
742 |
new StatusInfo(PithosStatus.LocalSyncing, "Syncing Files", "TraySynching"), |
743 |
new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused") |
744 |
}.ToDictionary(s => s.Status); |
745 |
|
746 |
readonly IWindowManager _windowManager; |
747 |
|
748 |
//private int _syncCount=0; |
749 |
|
750 |
|
751 |
private PithosStatus _pithosStatus = PithosStatus.Disconnected; |
752 |
|
753 |
public void SetPithosStatus(PithosStatus status) |
754 |
{ |
755 |
if (_pithosStatus == PithosStatus.LocalSyncing && status == PithosStatus.PollComplete) |
756 |
return; |
757 |
if (_pithosStatus == PithosStatus.PollSyncing && status == PithosStatus.LocalComplete) |
758 |
return; |
759 |
if (status == PithosStatus.LocalComplete || status == PithosStatus.PollComplete) |
760 |
_pithosStatus = PithosStatus.InSynch; |
761 |
else |
762 |
_pithosStatus = status; |
763 |
UpdateStatus(); |
764 |
} |
765 |
|
766 |
public void SetPithosStatus(PithosStatus status,string message) |
767 |
{ |
768 |
StatusMessage = message; |
769 |
SetPithosStatus(status); |
770 |
} |
771 |
|
772 |
/* public Notifier GetNotifier(Notification startNotification, Notification endNotification) |
773 |
{ |
774 |
return new Notifier(this, startNotification, endNotification); |
775 |
}*/ |
776 |
|
777 |
public Notifier GetNotifier(string startMessage, string endMessage, params object[] args) |
778 |
{ |
779 |
return new Notifier(this, |
780 |
new StatusNotification(String.Format(startMessage,args)), |
781 |
new StatusNotification(String.Format(endMessage,args))); |
782 |
} |
783 |
|
784 |
|
785 |
///<summary> |
786 |
/// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat |
787 |
///</summary> |
788 |
public void UpdateStatus() |
789 |
{ |
790 |
|
791 |
if (_iconNames.ContainsKey(_pithosStatus)) |
792 |
{ |
793 |
var info = _iconNames[_pithosStatus]; |
794 |
StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName); |
795 |
} |
796 |
|
797 |
if (_pithosStatus == PithosStatus.InSynch) |
798 |
StatusMessage = "All files up to date"; |
799 |
} |
800 |
|
801 |
|
802 |
|
803 |
private Task StartMonitor(PithosMonitor monitor,int retries=0) |
804 |
{ |
805 |
return Task.Factory.StartNew(() => |
806 |
{ |
807 |
using (log4net.ThreadContext.Stacks["Monitor"].Push("Start")) |
808 |
{ |
809 |
try |
810 |
{ |
811 |
Log.InfoFormat("Start Monitoring {0}", monitor.UserName); |
812 |
|
813 |
monitor.Start(); |
814 |
} |
815 |
catch (WebException exc) |
816 |
{ |
817 |
if (AbandonRetry(monitor, retries)) |
818 |
return; |
819 |
|
820 |
HttpStatusCode statusCode =HttpStatusCode.OK; |
821 |
var response = exc.Response as HttpWebResponse; |
822 |
if(response!=null) |
823 |
statusCode = response.StatusCode; |
824 |
|
825 |
switch (statusCode) |
826 |
{ |
827 |
case HttpStatusCode.Unauthorized: |
828 |
var message = String.Format("API Key Expired for {0}. Starting Renewal", |
829 |
monitor.UserName); |
830 |
Log.Error(message, exc); |
831 |
var account = Settings.Accounts.Find(acc => acc.AccountKey == new Uri(new Uri(monitor.AuthenticationUrl), monitor.UserName)); |
832 |
account.IsExpired = true; |
833 |
Notify(new ExpirationNotification(account)); |
834 |
//TryAuthorize(monitor.UserName, retries).Wait(); |
835 |
break; |
836 |
case HttpStatusCode.ProxyAuthenticationRequired: |
837 |
TryAuthenticateProxy(monitor,retries); |
838 |
break; |
839 |
default: |
840 |
TryLater(monitor, exc, retries); |
841 |
break; |
842 |
} |
843 |
} |
844 |
catch (Exception exc) |
845 |
{ |
846 |
if (AbandonRetry(monitor, retries)) |
847 |
return; |
848 |
|
849 |
TryLater(monitor,exc,retries); |
850 |
} |
851 |
} |
852 |
}); |
853 |
} |
854 |
|
855 |
private void TryAuthenticateProxy(PithosMonitor monitor,int retries) |
856 |
{ |
857 |
Execute.OnUIThread(() => |
858 |
{ |
859 |
var proxyAccount = IoC.Get<ProxyAccountViewModel>(); |
860 |
proxyAccount.Settings = Settings; |
861 |
if (true != _windowManager.ShowDialog(proxyAccount)) |
862 |
return; |
863 |
StartMonitor(monitor, retries); |
864 |
NotifyOfPropertyChange(() => Accounts); |
865 |
}); |
866 |
} |
867 |
|
868 |
private bool AbandonRetry(PithosMonitor monitor, int retries) |
869 |
{ |
870 |
if (retries > 1) |
871 |
{ |
872 |
var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry", |
873 |
monitor.UserName); |
874 |
_events.Publish(new Notification |
875 |
{Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error}); |
876 |
return true; |
877 |
} |
878 |
return false; |
879 |
} |
880 |
|
881 |
|
882 |
private void TryLater(PithosMonitor monitor, Exception exc,int retries) |
883 |
{ |
884 |
var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds"); |
885 |
Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1)); |
886 |
_events.Publish(new Notification |
887 |
{Title = "Error", Message = message, Level = TraceLevel.Error}); |
888 |
Log.Error(message, exc); |
889 |
} |
890 |
|
891 |
|
892 |
public void NotifyChange(string status, TraceLevel level=TraceLevel.Info) |
893 |
{ |
894 |
StatusMessage = status; |
895 |
|
896 |
_events.Publish(new Notification { Title = "Pithos+", Message = status, Level = level }); |
897 |
} |
898 |
|
899 |
public void NotifyChangedFile(string filePath) |
900 |
{ |
901 |
if (RecentFiles.Any(e => e.FullPath == filePath)) |
902 |
return; |
903 |
|
904 |
IProducerConsumerCollection<FileEntry> files=RecentFiles; |
905 |
FileEntry popped; |
906 |
while (files.Count > 5) |
907 |
files.TryTake(out popped); |
908 |
var entry = new FileEntry { FullPath = filePath }; |
909 |
files.TryAdd(entry); |
910 |
} |
911 |
|
912 |
public void NotifyAccount(AccountInfo account) |
913 |
{ |
914 |
if (account== null) |
915 |
return; |
916 |
//TODO: What happens to an existing account whose Token has changed? |
917 |
account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}", |
918 |
account.SiteUri, Uri.EscapeDataString(account.Token), |
919 |
Uri.EscapeDataString(account.UserName)); |
920 |
|
921 |
if (!Accounts.Any(item => item.UserName == account.UserName && item.SiteUri == account.SiteUri)) |
922 |
Accounts.TryAdd(account); |
923 |
|
924 |
} |
925 |
|
926 |
public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message) |
927 |
{ |
928 |
if (conflictFiles == null) |
929 |
return; |
930 |
//Convert to list to avoid multiple iterations |
931 |
var files = conflictFiles.ToList(); |
932 |
if (files.Count==0) |
933 |
return; |
934 |
|
935 |
UpdateStatus(); |
936 |
//TODO: Create a more specific message. For now, just show a warning |
937 |
NotifyForFiles(files,message,TraceLevel.Warning); |
938 |
|
939 |
} |
940 |
|
941 |
public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info) |
942 |
{ |
943 |
if (files == null) |
944 |
return; |
945 |
if (!files.Any()) |
946 |
return; |
947 |
|
948 |
StatusMessage = message; |
949 |
|
950 |
_events.Publish(new Notification { Title = "Pithos+", Message = message, Level = level}); |
951 |
} |
952 |
|
953 |
public void Notify(Notification notification) |
954 |
{ |
955 |
_events.Publish(notification); |
956 |
} |
957 |
|
958 |
|
959 |
public void RemoveMonitor(string serverUrl,string accountName) |
960 |
{ |
961 |
if (String.IsNullOrWhiteSpace(accountName)) |
962 |
return; |
963 |
|
964 |
var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName && account.StorageUri.ToString().StartsWith(serverUrl)); |
965 |
if (accountInfo != null) |
966 |
{ |
967 |
_accounts.TryRemove(accountInfo); |
968 |
_pollAgent.RemoveAccount(accountInfo); |
969 |
} |
970 |
|
971 |
var accountKey = new Uri(new Uri(serverUrl),accountName); |
972 |
PithosMonitor monitor; |
973 |
if (Monitors.TryRemove(accountKey, out monitor)) |
974 |
{ |
975 |
monitor.Stop(); |
976 |
//TODO: Also remove any pending actions for this account |
977 |
//from the network queue |
978 |
} |
979 |
} |
980 |
|
981 |
public void RefreshOverlays() |
982 |
{ |
983 |
foreach (var pair in Monitors) |
984 |
{ |
985 |
var monitor = pair.Value; |
986 |
|
987 |
var path = monitor.RootPath; |
988 |
|
989 |
if (String.IsNullOrWhiteSpace(path)) |
990 |
continue; |
991 |
|
992 |
if (!Directory.Exists(path) && !File.Exists(path)) |
993 |
continue; |
994 |
|
995 |
IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path); |
996 |
|
997 |
try |
998 |
{ |
999 |
NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM, |
1000 |
HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT, |
1001 |
pathPointer, IntPtr.Zero); |
1002 |
} |
1003 |
finally |
1004 |
{ |
1005 |
Marshal.FreeHGlobal(pathPointer); |
1006 |
} |
1007 |
} |
1008 |
} |
1009 |
|
1010 |
#region Event Handlers |
1011 |
|
1012 |
public void Handle(SelectiveSynchChanges message) |
1013 |
{ |
1014 |
TaskEx.Run(() => |
1015 |
{ |
1016 |
PithosMonitor monitor; |
1017 |
if (Monitors.TryGetValue(message.Account.AccountKey, out monitor)) |
1018 |
{ |
1019 |
Selectives.SetIsSelectiveEnabled(message.Account.AccountKey, message.Enabled); |
1020 |
monitor.SetSelectivePaths(message.Uris, message.Added, message.Removed); |
1021 |
} |
1022 |
|
1023 |
var account = Accounts.FirstOrDefault(acc => acc.AccountKey == message.Account.AccountKey); |
1024 |
if (account != null) |
1025 |
{ |
1026 |
this._pollAgent.SetSelectivePaths(account, message.Added, message.Removed); |
1027 |
} |
1028 |
}); |
1029 |
|
1030 |
} |
1031 |
|
1032 |
|
1033 |
private bool _pollStarted; |
1034 |
private Sparkle _sparkle; |
1035 |
private bool _manualUpgradeCheck; |
1036 |
|
1037 |
//SMELL: Doing so much work for notifications in the shell is wrong |
1038 |
//The notifications should be moved to their own view/viewmodel pair |
1039 |
//and different templates should be used for different message types |
1040 |
//This will also allow the addition of extra functionality, eg. actions |
1041 |
// |
1042 |
public void Handle(Notification notification) |
1043 |
{ |
1044 |
UpdateStatus(); |
1045 |
|
1046 |
if (!Settings.ShowDesktopNotifications) |
1047 |
return; |
1048 |
|
1049 |
if (notification is PollNotification) |
1050 |
{ |
1051 |
_pollStarted = true; |
1052 |
return; |
1053 |
} |
1054 |
if (notification is CloudNotification) |
1055 |
{ |
1056 |
if (!_pollStarted) |
1057 |
return; |
1058 |
_pollStarted= false; |
1059 |
notification.Title = "Pithos+"; |
1060 |
notification.Message = "Start Synchronisation"; |
1061 |
} |
1062 |
|
1063 |
var deleteNotification = notification as CloudDeleteNotification; |
1064 |
if (deleteNotification != null) |
1065 |
{ |
1066 |
StatusMessage = String.Format("Deleted {0}", deleteNotification.Data.Name); |
1067 |
return; |
1068 |
} |
1069 |
|
1070 |
var progress = notification as ProgressNotification; |
1071 |
|
1072 |
|
1073 |
if (progress != null) |
1074 |
{ |
1075 |
StatusMessage = String.Format("{0} {1:p2} of {2} - {3}", |
1076 |
progress.Action, |
1077 |
progress.Block/(double)progress.TotalBlocks, |
1078 |
progress.FileSize.ToByteSize(), |
1079 |
progress.FileName); |
1080 |
return; |
1081 |
} |
1082 |
|
1083 |
var info = notification as StatusNotification; |
1084 |
if (info != null) |
1085 |
{ |
1086 |
StatusMessage = info.Title; |
1087 |
return; |
1088 |
} |
1089 |
if (String.IsNullOrWhiteSpace(notification.Message) && String.IsNullOrWhiteSpace(notification.Title)) |
1090 |
return; |
1091 |
|
1092 |
if (notification.Level <= TraceLevel.Warning) |
1093 |
ShowBalloonFor(notification); |
1094 |
} |
1095 |
|
1096 |
private void ShowBalloonFor(Notification notification) |
1097 |
{ |
1098 |
Contract.Requires(notification!=null); |
1099 |
|
1100 |
if (!Settings.ShowDesktopNotifications) |
1101 |
return; |
1102 |
|
1103 |
BalloonIcon icon; |
1104 |
switch (notification.Level) |
1105 |
{ |
1106 |
case TraceLevel.Verbose: |
1107 |
return; |
1108 |
case TraceLevel.Info: |
1109 |
icon = BalloonIcon.Info; |
1110 |
break; |
1111 |
case TraceLevel.Error: |
1112 |
icon = BalloonIcon.Error; |
1113 |
break; |
1114 |
case TraceLevel.Warning: |
1115 |
icon = BalloonIcon.Warning; |
1116 |
break; |
1117 |
default: |
1118 |
return; |
1119 |
} |
1120 |
|
1121 |
var tv = (ShellView) GetView(); |
1122 |
System.Action clickAction = null; |
1123 |
if (notification is ExpirationNotification) |
1124 |
{ |
1125 |
clickAction = () => ShowPreferences("AccountTab"); |
1126 |
} |
1127 |
var balloon = new PithosBalloon |
1128 |
{ |
1129 |
Title = notification.Title, |
1130 |
Message = notification.Message, |
1131 |
Icon = icon, |
1132 |
ClickAction = clickAction |
1133 |
}; |
1134 |
tv.TaskbarView.ShowCustomBalloon(balloon, PopupAnimation.Fade, 4000); |
1135 |
} |
1136 |
|
1137 |
#endregion |
1138 |
|
1139 |
public void Handle(ShowFilePropertiesEvent message) |
1140 |
{ |
1141 |
if (message == null) |
1142 |
throw new ArgumentNullException("message"); |
1143 |
if (String.IsNullOrWhiteSpace(message.FileName) ) |
1144 |
throw new ArgumentException("message"); |
1145 |
Contract.EndContractBlock(); |
1146 |
|
1147 |
var fileName = message.FileName; |
1148 |
//TODO: Display file properties for non-container folders |
1149 |
if (File.Exists(fileName)) |
1150 |
//Retrieve the full name with exact casing. Pithos names are case sensitive |
1151 |
ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName)); |
1152 |
else if (Directory.Exists(fileName)) |
1153 |
//Retrieve the full name with exact casing. Pithos names are case sensitive |
1154 |
{ |
1155 |
var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName); |
1156 |
if (IsContainer(path)) |
1157 |
ShowContainerProperties(path); |
1158 |
else |
1159 |
ShowFileProperties(path); |
1160 |
} |
1161 |
} |
1162 |
|
1163 |
private bool IsContainer(string path) |
1164 |
{ |
1165 |
var matchingFolders = from account in _accounts |
1166 |
from rootFolder in Directory.GetDirectories(account.AccountPath) |
1167 |
where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase) |
1168 |
select rootFolder; |
1169 |
return matchingFolders.Any(); |
1170 |
} |
1171 |
|
1172 |
public FileStatus GetFileStatus(string localFileName) |
1173 |
{ |
1174 |
if (String.IsNullOrWhiteSpace(localFileName)) |
1175 |
throw new ArgumentNullException("localFileName"); |
1176 |
Contract.EndContractBlock(); |
1177 |
|
1178 |
var statusKeeper = IoC.Get<IStatusKeeper>(); |
1179 |
var status=statusKeeper.GetFileStatus(localFileName); |
1180 |
return status; |
1181 |
} |
1182 |
|
1183 |
public void RemoveAccountFromDatabase(AccountSettings account) |
1184 |
{ |
1185 |
var statusKeeper = IoC.Get<IStatusKeeper>(); |
1186 |
statusKeeper.ClearFolderStatus(account.RootPath); |
1187 |
} |
1188 |
} |
1189 |
} |