RFC3489ViewModel.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using Dns.Net.Abstractions;
  2. using JetBrains.Annotations;
  3. using Microsoft;
  4. using NatTypeTester.Models;
  5. using ReactiveUI;
  6. using STUN;
  7. using STUN.Client;
  8. using STUN.Proxy;
  9. using STUN.StunResult;
  10. using System;
  11. using System.Net;
  12. using System.Reactive;
  13. using System.Reactive.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace NatTypeTester.ViewModels
  17. {
  18. [UsedImplicitly]
  19. public class RFC3489ViewModel : ViewModelBase, IRoutableViewModel
  20. {
  21. public string UrlPathSegment => @"RFC3489";
  22. public IScreen HostScreen => LazyServiceProvider.LazyGetRequiredService<IScreen>();
  23. private Config Config => LazyServiceProvider.LazyGetRequiredService<Config>();
  24. private IDnsClient DnsClient => LazyServiceProvider.LazyGetRequiredService<IDnsClient>();
  25. public ClassicStunResult Result3489 { get; set; }
  26. public ReactiveCommand<Unit, Unit> TestClassicNatType { get; }
  27. public RFC3489ViewModel()
  28. {
  29. Result3489 = new ClassicStunResult { LocalEndPoint = new IPEndPoint(IPAddress.Any, 0) };
  30. TestClassicNatType = ReactiveCommand.CreateFromTask(TestClassicNatTypeImpl);
  31. }
  32. private async Task TestClassicNatTypeImpl(CancellationToken token)
  33. {
  34. Verify.Operation(StunServer.TryParse(Config.StunServer, out var server), @"Wrong STUN Server!");
  35. using var proxy = ProxyFactory.CreateProxy(
  36. Config.ProxyType,
  37. Result3489.LocalEndPoint,
  38. IPEndPoint.Parse(Config.ProxyServer),
  39. Config.ProxyUser, Config.ProxyPassword
  40. );
  41. using var client = new StunClient3489(DnsClient, server.Hostname, server.Port, Result3489.LocalEndPoint, proxy);
  42. Result3489 = client.Status;
  43. using (Observable.Interval(TimeSpan.FromSeconds(0.1))
  44. .ObserveOn(RxApp.MainThreadScheduler)
  45. .Subscribe(_ => this.RaisePropertyChanged(nameof(Result3489))))
  46. {
  47. await client.Query3489Async();
  48. }
  49. Result3489.LocalEndPoint = client.LocalEndPoint;
  50. this.RaisePropertyChanged(nameof(Result3489));
  51. }
  52. }
  53. }