MainWindowViewModel.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using DynamicData;
  2. using DynamicData.Binding;
  3. using Microsoft.VisualStudio.Threading;
  4. using NatTypeTester.Models;
  5. using ReactiveUI;
  6. using STUN;
  7. using System.Reactive.Linq;
  8. using Volo.Abp.DependencyInjection;
  9. namespace NatTypeTester.ViewModels;
  10. [ExposeServices(
  11. typeof(MainWindowViewModel),
  12. typeof(IScreen)
  13. )]
  14. public class MainWindowViewModel : ViewModelBase, IScreen
  15. {
  16. public RoutingState Router => LazyServiceProvider.LazyGetRequiredService<RoutingState>();
  17. public Config Config => LazyServiceProvider.LazyGetRequiredService<Config>();
  18. private readonly IEnumerable<string> _defaultServers = new HashSet<string>
  19. {
  20. @"stunserver.stunprotocol.org",
  21. @"stun.fitauto.ru",
  22. @"stun.hot-chilli.net",
  23. @"stun.syncthing.net",
  24. @"stun.qq.com",
  25. @"stun.miwifi.com"
  26. };
  27. private SourceList<string> List { get; } = new();
  28. public readonly IObservableCollection<string> StunServers = new ObservableCollectionExtended<string>();
  29. public MainWindowViewModel()
  30. {
  31. List.Connect()
  32. .DistinctValues(x => x)
  33. .ObserveOn(RxApp.MainThreadScheduler)
  34. .Bind(StunServers)
  35. .Subscribe();
  36. }
  37. public void LoadStunServer()
  38. {
  39. foreach (string? server in _defaultServers)
  40. {
  41. List.Add(server);
  42. }
  43. Config.StunServer = _defaultServers.First();
  44. Task.Run(() =>
  45. {
  46. const string path = @"stun.txt";
  47. if (!File.Exists(path))
  48. {
  49. return;
  50. }
  51. foreach (string? line in File.ReadLines(path))
  52. {
  53. if (!string.IsNullOrWhiteSpace(line) && StunServer.TryParse(line, out StunServer? stun))
  54. {
  55. List.Add(stun.ToString());
  56. }
  57. }
  58. }).Forget();
  59. }
  60. }