RFC3489ViewModel.cs 1.9 KB

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