MainWindowViewModel.cs 1.6 KB

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