MainWindowViewModel.cs 1.6 KB

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