RFC5780ViewModel.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 RFC5780ViewModel : ViewModelBase, IRoutableViewModel
  19. {
  20. public string UrlPathSegment => @"RFC5780";
  21. public IScreen HostScreen => LazyServiceProvider.LazyGetRequiredService<IScreen>();
  22. private Config Config => LazyServiceProvider.LazyGetRequiredService<Config>();
  23. private IDnsClient DnsClient => LazyServiceProvider.LazyGetRequiredService<IDnsClient>();
  24. public StunResult5389 Result5389 { get; set; }
  25. public ReactiveCommand<Unit, Unit> DiscoveryNatType { get; }
  26. public RFC5780ViewModel()
  27. {
  28. Result5389 = new StunResult5389 { LocalEndPoint = new IPEndPoint(IPAddress.Any, 0) };
  29. DiscoveryNatType = ReactiveCommand.CreateFromTask(DiscoveryNatTypeImpl);
  30. }
  31. private async Task DiscoveryNatTypeImpl(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. Result5389.LocalEndPoint,
  41. IPEndPoint.Parse(Config.ProxyServer),
  42. Config.ProxyUser, Config.ProxyPassword
  43. );
  44. using var client = new StunClient5389UDP(DnsClient, server.Hostname, server.Port, Result5389.LocalEndPoint, proxy);
  45. Result5389 = client.Status;
  46. using (Observable.Interval(TimeSpan.FromSeconds(0.1))
  47. .ObserveOn(RxApp.MainThreadScheduler)
  48. .Subscribe(_ => this.RaisePropertyChanged(nameof(Result5389))))
  49. {
  50. await client.QueryAsync();
  51. }
  52. var cache = new StunResult5389();
  53. cache.Clone(client.Status);
  54. cache.LocalEndPoint = client.LocalEndPoint;
  55. Result5389 = cache;
  56. this.RaisePropertyChanged(nameof(Result5389));
  57. }
  58. }
  59. }