1
0

MainWindowViewModel.cs 1.7 KB

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