RFC3489ViewModel.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using Dns.Net.Abstractions;
  2. using JetBrains.Annotations;
  3. using NatTypeTester.Models;
  4. using ReactiveUI;
  5. using ReactiveUI.Fody.Helpers;
  6. using STUN.Client;
  7. using STUN.Proxy;
  8. using STUN.StunResult;
  9. using STUN.Utils;
  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. [Reactive]
  26. public ClassicStunResult Result3489 { get; set; }
  27. public ReactiveCommand<Unit, Unit> TestClassicNatType { get; }
  28. public RFC3489ViewModel()
  29. {
  30. Result3489 = new ClassicStunResult { LocalEndPoint = new IPEndPoint(IPAddress.Any, 0) };
  31. TestClassicNatType = ReactiveCommand.CreateFromTask(TestClassicNatTypeImpl);
  32. }
  33. private async Task TestClassicNatTypeImpl(CancellationToken token)
  34. {
  35. var server = new StunServer();
  36. if (!server.Parse(Config.StunServer))
  37. {
  38. throw new Exception(@"Wrong STUN Server!");
  39. }
  40. using var proxy = ProxyFactory.CreateProxy(
  41. Config.ProxyType,
  42. Result3489.LocalEndPoint,
  43. IPEndPoint.Parse(Config.ProxyServer),
  44. Config.ProxyUser, Config.ProxyPassword
  45. );
  46. using var client = new StunClient3489(DnsClient, server.Hostname, server.Port, Result3489.LocalEndPoint, proxy);
  47. Result3489 = client.Status;
  48. using (Observable.Interval(TimeSpan.FromSeconds(0.1))
  49. .ObserveOn(RxApp.MainThreadScheduler)
  50. .Subscribe(_ => this.RaisePropertyChanged(nameof(Result3489))))
  51. {
  52. await client.Query3489Async();
  53. }
  54. Result3489.LocalEndPoint = client.LocalEndPoint;
  55. this.RaisePropertyChanged(nameof(Result3489));
  56. }
  57. }
  58. }