2
0

ConnectEntryPoint.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Connect;
  5. using MediaBrowser.Controller.Plugins;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Net;
  8. using System;
  9. using System.IO;
  10. using System.Net;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using CommonIO;
  15. using MediaBrowser.Common.IO;
  16. using MediaBrowser.Common.Threading;
  17. namespace MediaBrowser.Server.Implementations.Connect
  18. {
  19. public class ConnectEntryPoint : IServerEntryPoint
  20. {
  21. private PeriodicTimer _timer;
  22. private readonly IHttpClient _httpClient;
  23. private readonly IApplicationPaths _appPaths;
  24. private readonly ILogger _logger;
  25. private readonly IConnectManager _connectManager;
  26. private readonly INetworkManager _networkManager;
  27. private readonly IApplicationHost _appHost;
  28. private readonly IFileSystem _fileSystem;
  29. public ConnectEntryPoint(IHttpClient httpClient, IApplicationPaths appPaths, ILogger logger, INetworkManager networkManager, IConnectManager connectManager, IApplicationHost appHost, IFileSystem fileSystem)
  30. {
  31. _httpClient = httpClient;
  32. _appPaths = appPaths;
  33. _logger = logger;
  34. _networkManager = networkManager;
  35. _connectManager = connectManager;
  36. _appHost = appHost;
  37. _fileSystem = fileSystem;
  38. }
  39. public void Run()
  40. {
  41. Task.Run(() => LoadCachedAddress());
  42. _timer = new PeriodicTimer(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromHours(3));
  43. }
  44. private readonly string[] _ipLookups = { "http://bot.whatismyipaddress.com", "https://connect.emby.media/service/ip" };
  45. private async void TimerCallback(object state)
  46. {
  47. var index = 0;
  48. foreach (var ipLookupUrl in _ipLookups)
  49. {
  50. try
  51. {
  52. // Sometimes whatismyipaddress might fail, but it won't do us any good having users raise alarms over it.
  53. var logErrors = index > 0;
  54. #if DEBUG
  55. logErrors = true;
  56. #endif
  57. using (var stream = await _httpClient.Get(new HttpRequestOptions
  58. {
  59. Url = ipLookupUrl,
  60. UserAgent = "Emby/" + _appHost.ApplicationVersion,
  61. LogErrors = logErrors,
  62. // Seeing block length errors with our server
  63. EnableHttpCompression = false
  64. }).ConfigureAwait(false))
  65. {
  66. using (var reader = new StreamReader(stream))
  67. {
  68. var address = await reader.ReadToEndAsync().ConfigureAwait(false);
  69. if (IsValid(address, ipLookupUrl))
  70. {
  71. ((ConnectManager)_connectManager).OnWanAddressResolved(address);
  72. CacheAddress(address);
  73. return;
  74. }
  75. }
  76. }
  77. }
  78. catch (HttpException)
  79. {
  80. }
  81. catch (Exception ex)
  82. {
  83. _logger.ErrorException("Error getting connection info", ex);
  84. }
  85. index++;
  86. }
  87. }
  88. private string CacheFilePath
  89. {
  90. get { return Path.Combine(_appPaths.DataPath, "wan.txt"); }
  91. }
  92. private void CacheAddress(string address)
  93. {
  94. var path = CacheFilePath;
  95. try
  96. {
  97. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  98. _fileSystem.WriteAllText(path, address, Encoding.UTF8);
  99. }
  100. catch (Exception ex)
  101. {
  102. _logger.ErrorException("Error saving data", ex);
  103. }
  104. }
  105. private void LoadCachedAddress()
  106. {
  107. var path = CacheFilePath;
  108. try
  109. {
  110. var endpoint = _fileSystem.ReadAllText(path, Encoding.UTF8);
  111. if (IsValid(endpoint, "cache"))
  112. {
  113. ((ConnectManager)_connectManager).OnWanAddressResolved(endpoint);
  114. }
  115. }
  116. catch (IOException)
  117. {
  118. // File isn't there. no biggie
  119. }
  120. catch (Exception ex)
  121. {
  122. _logger.ErrorException("Error loading data", ex);
  123. }
  124. }
  125. private bool IsValid(string address, string source)
  126. {
  127. IPAddress ipAddress;
  128. var valid = IPAddress.TryParse(address, out ipAddress);
  129. if (!valid)
  130. {
  131. _logger.Error("{0} is not a valid ip address. Source: {1}", address, source);
  132. }
  133. return valid;
  134. }
  135. public void Dispose()
  136. {
  137. if (_timer != null)
  138. {
  139. _timer.Dispose();
  140. _timer = null;
  141. }
  142. }
  143. }
  144. }