ConnectEntryPoint.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. namespace MediaBrowser.Server.Implementations.Connect
  17. {
  18. public class ConnectEntryPoint : IServerEntryPoint
  19. {
  20. private Timer _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 Timer(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromHours(3));
  42. }
  43. private readonly string[] _ipLookups = { "http://bot.whatismyipaddress.com", "https://connect.emby.media/service/ip" };
  44. private async void TimerCallback(object state)
  45. {
  46. var index = 0;
  47. foreach (var ipLookupUrl in _ipLookups)
  48. {
  49. try
  50. {
  51. // Sometimes whatismyipaddress might fail, but it won't do us any good having users raise alarms over it.
  52. var logErrors = index > 0;
  53. #if DEBUG
  54. logErrors = true;
  55. #endif
  56. using (var stream = await _httpClient.Get(new HttpRequestOptions
  57. {
  58. Url = ipLookupUrl,
  59. UserAgent = "Emby/" + _appHost.ApplicationVersion,
  60. LogErrors = logErrors,
  61. // Seeing block length errors with our server
  62. EnableHttpCompression = false
  63. }).ConfigureAwait(false))
  64. {
  65. using (var reader = new StreamReader(stream))
  66. {
  67. var address = await reader.ReadToEndAsync().ConfigureAwait(false);
  68. if (IsValid(address, ipLookupUrl))
  69. {
  70. ((ConnectManager)_connectManager).OnWanAddressResolved(address);
  71. CacheAddress(address);
  72. return;
  73. }
  74. }
  75. }
  76. }
  77. catch (HttpException)
  78. {
  79. }
  80. catch (Exception ex)
  81. {
  82. _logger.ErrorException("Error getting connection info", ex);
  83. }
  84. index++;
  85. }
  86. }
  87. private string CacheFilePath
  88. {
  89. get { return Path.Combine(_appPaths.DataPath, "wan.txt"); }
  90. }
  91. private void CacheAddress(string address)
  92. {
  93. var path = CacheFilePath;
  94. try
  95. {
  96. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  97. _fileSystem.WriteAllText(path, address, Encoding.UTF8);
  98. }
  99. catch (Exception ex)
  100. {
  101. _logger.ErrorException("Error saving data", ex);
  102. }
  103. }
  104. private void LoadCachedAddress()
  105. {
  106. var path = CacheFilePath;
  107. try
  108. {
  109. var endpoint = _fileSystem.ReadAllText(path, Encoding.UTF8);
  110. if (IsValid(endpoint, "cache"))
  111. {
  112. ((ConnectManager)_connectManager).OnWanAddressResolved(endpoint);
  113. }
  114. }
  115. catch (IOException)
  116. {
  117. // File isn't there. no biggie
  118. }
  119. catch (Exception ex)
  120. {
  121. _logger.ErrorException("Error loading data", ex);
  122. }
  123. }
  124. private bool IsValid(string address, string source)
  125. {
  126. IPAddress ipAddress;
  127. var valid = IPAddress.TryParse(address, out ipAddress);
  128. if (!valid)
  129. {
  130. _logger.Error("{0} is not a valid ip address. Source: {1}", address, source);
  131. }
  132. return valid;
  133. }
  134. public void Dispose()
  135. {
  136. if (_timer != null)
  137. {
  138. _timer.Dispose();
  139. _timer = null;
  140. }
  141. }
  142. }
  143. }