RFC5780ViewModel.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using JetBrains.Annotations;
  2. using NatTypeTester.Models;
  3. using ReactiveUI;
  4. using ReactiveUI.Fody.Helpers;
  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.Threading;
  13. using System.Threading.Tasks;
  14. namespace NatTypeTester.ViewModels
  15. {
  16. [UsedImplicitly]
  17. public class RFC5780ViewModel : ViewModelBase, IRoutableViewModel
  18. {
  19. public string UrlPathSegment => @"RFC5780";
  20. public IScreen HostScreen => LazyServiceProvider.LazyGetRequiredService<IScreen>();
  21. private Config Config => LazyServiceProvider.LazyGetRequiredService<Config>();
  22. [Reactive]
  23. public StunResult5389 Result5389 { get; set; }
  24. public ReactiveCommand<Unit, Unit> DiscoveryNatType { get; }
  25. public RFC5780ViewModel()
  26. {
  27. Result5389 = new StunResult5389 { LocalEndPoint = new IPEndPoint(IPAddress.Any, 0) };
  28. DiscoveryNatType = ReactiveCommand.CreateFromTask(DiscoveryNatTypeImpl);
  29. }
  30. private async Task DiscoveryNatTypeImpl(CancellationToken token)
  31. {
  32. var server = new StunServer();
  33. if (!server.Parse(Config.StunServer))
  34. {
  35. throw new Exception(@"Wrong STUN Server!");
  36. }
  37. using var proxy = ProxyFactory.CreateProxy(
  38. Config.ProxyType,
  39. Result5389.LocalEndPoint,
  40. NetUtils.ParseEndpoint(Config.ProxyServer),
  41. Config.ProxyUser, Config.ProxyPassword
  42. );
  43. using var client = new StunClient5389UDP(server.Hostname, server.Port, Result5389.LocalEndPoint, proxy);
  44. Result5389 = client.Status;
  45. await client.QueryAsync();
  46. var cache = new StunResult5389();
  47. cache.Clone(client.Status);
  48. cache.LocalEndPoint = client.LocalEndPoint;
  49. Result5389 = cache;
  50. }
  51. }
  52. }