ConnectEntryPoint.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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.Net.Sockets;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. using CommonIO;
  15. using MediaBrowser.Common.Threading;
  16. namespace MediaBrowser.Server.Implementations.Connect
  17. {
  18. public class ConnectEntryPoint : IServerEntryPoint
  19. {
  20. private PeriodicTimer _timer;
  21. private readonly IHttpClient _httpClient;
  22. private readonly IApplicationPaths _appPaths;
  23. private readonly ILogger _logger;
  24. private readonly IConnectManager _connectManager;
  25. private readonly INetworkManager _networkManager;
  26. private readonly IApplicationHost _appHost;
  27. private readonly IFileSystem _fileSystem;
  28. public ConnectEntryPoint(IHttpClient httpClient, IApplicationPaths appPaths, ILogger logger, INetworkManager networkManager, IConnectManager connectManager, IApplicationHost appHost, IFileSystem fileSystem)
  29. {
  30. _httpClient = httpClient;
  31. _appPaths = appPaths;
  32. _logger = logger;
  33. _networkManager = networkManager;
  34. _connectManager = connectManager;
  35. _appHost = appHost;
  36. _fileSystem = fileSystem;
  37. }
  38. public void Run()
  39. {
  40. Task.Run(() => LoadCachedAddress());
  41. _timer = new PeriodicTimer(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromHours(3));
  42. }
  43. private readonly string[] _ipLookups =
  44. {
  45. "http://bot.whatismyipaddress.com",
  46. "https://connect.emby.media/service/ip"
  47. };
  48. private async void TimerCallback(object state)
  49. {
  50. IPAddress validIpAddress = null;
  51. foreach (var ipLookupUrl in _ipLookups)
  52. {
  53. try
  54. {
  55. validIpAddress = await GetIpAddress(ipLookupUrl).ConfigureAwait(false);
  56. // Try to find the ipv4 address, if present
  57. if (validIpAddress.AddressFamily == AddressFamily.InterNetwork)
  58. {
  59. break;
  60. }
  61. }
  62. catch (HttpException)
  63. {
  64. }
  65. catch (Exception ex)
  66. {
  67. _logger.ErrorException("Error getting connection info", ex);
  68. }
  69. }
  70. // If this produced an ipv6 address, try again
  71. if (validIpAddress == null || validIpAddress.AddressFamily == AddressFamily.InterNetworkV6)
  72. {
  73. foreach (var ipLookupUrl in _ipLookups)
  74. {
  75. try
  76. {
  77. validIpAddress = await GetIpAddress(ipLookupUrl, true).ConfigureAwait(false);
  78. // Try to find the ipv4 address, if present
  79. if (validIpAddress.AddressFamily == AddressFamily.InterNetwork)
  80. {
  81. break;
  82. }
  83. }
  84. catch (HttpException)
  85. {
  86. }
  87. catch (Exception ex)
  88. {
  89. _logger.ErrorException("Error getting connection info", ex);
  90. }
  91. }
  92. }
  93. if (validIpAddress != null)
  94. {
  95. ((ConnectManager)_connectManager).OnWanAddressResolved(validIpAddress);
  96. CacheAddress(validIpAddress);
  97. }
  98. }
  99. private async Task<IPAddress> GetIpAddress(string lookupUrl, bool preferIpv4 = false)
  100. {
  101. // Sometimes whatismyipaddress might fail, but it won't do us any good having users raise alarms over it.
  102. var logErrors = false;
  103. #if DEBUG
  104. logErrors = true;
  105. #endif
  106. using (var stream = await _httpClient.Get(new HttpRequestOptions
  107. {
  108. Url = lookupUrl,
  109. UserAgent = "Emby/" + _appHost.ApplicationVersion,
  110. LogErrors = logErrors,
  111. // Seeing block length errors with our server
  112. EnableHttpCompression = false,
  113. PreferIpv4 = preferIpv4
  114. }).ConfigureAwait(false))
  115. {
  116. using (var reader = new StreamReader(stream))
  117. {
  118. var addressString = await reader.ReadToEndAsync().ConfigureAwait(false);
  119. return IPAddress.Parse(addressString);
  120. }
  121. }
  122. }
  123. private string CacheFilePath
  124. {
  125. get { return Path.Combine(_appPaths.DataPath, "wan.txt"); }
  126. }
  127. private void CacheAddress(IPAddress address)
  128. {
  129. var path = CacheFilePath;
  130. try
  131. {
  132. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  133. _fileSystem.WriteAllText(path, address.ToString(), Encoding.UTF8);
  134. }
  135. catch (Exception ex)
  136. {
  137. _logger.ErrorException("Error saving data", ex);
  138. }
  139. }
  140. private void LoadCachedAddress()
  141. {
  142. var path = CacheFilePath;
  143. try
  144. {
  145. var endpoint = _fileSystem.ReadAllText(path, Encoding.UTF8);
  146. IPAddress ipAddress;
  147. if (IPAddress.TryParse(endpoint, out ipAddress))
  148. {
  149. ((ConnectManager)_connectManager).OnWanAddressResolved(ipAddress);
  150. }
  151. }
  152. catch (IOException)
  153. {
  154. // File isn't there. no biggie
  155. }
  156. catch (Exception ex)
  157. {
  158. _logger.ErrorException("Error loading data", ex);
  159. }
  160. }
  161. public void Dispose()
  162. {
  163. if (_timer != null)
  164. {
  165. _timer.Dispose();
  166. _timer = null;
  167. }
  168. }
  169. }
  170. }