MainWindowViewModel.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. @"stun.hot-chilli.net",
  21. @"stunserver.stunprotocol.org",
  22. @"stun.syncthing.net",
  23. @"stun.qq.com",
  24. @"stun.miwifi.com"
  25. };
  26. private SourceList<string> List { get; } = new();
  27. public readonly IObservableCollection<string> StunServers = new ObservableCollectionExtended<string>();
  28. public MainWindowViewModel()
  29. {
  30. List.Connect()
  31. .DistinctValues(x => x)
  32. .ObserveOn(RxApp.MainThreadScheduler)
  33. .Bind(StunServers)
  34. .Subscribe();
  35. }
  36. public void LoadStunServer()
  37. {
  38. foreach (string? server in _defaultServers)
  39. {
  40. List.Add(server);
  41. }
  42. Config.StunServer = _defaultServers.First();
  43. Task.Run(() =>
  44. {
  45. const string path = @"stun.txt";
  46. if (!File.Exists(path))
  47. {
  48. return;
  49. }
  50. foreach (string? line in File.ReadLines(path))
  51. {
  52. if (!string.IsNullOrWhiteSpace(line) && StunServer.TryParse(line, out StunServer? stun))
  53. {
  54. List.Add(stun.ToString());
  55. }
  56. }
  57. }).Forget();
  58. }
  59. }