MainWindowViewModel.cs 1.5 KB

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