ConnectManager.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Connect;
  6. using MediaBrowser.Controller.Security;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.Net;
  9. using MediaBrowser.Model.Serialization;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Net;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Server.Implementations.Connect
  19. {
  20. public class ConnectManager : IConnectManager
  21. {
  22. private readonly ILogger _logger;
  23. private readonly IApplicationPaths _appPaths;
  24. private readonly IJsonSerializer _json;
  25. private readonly IEncryptionManager _encryption;
  26. private readonly IHttpClient _httpClient;
  27. private readonly IServerApplicationHost _appHost;
  28. private readonly IServerConfigurationManager _config;
  29. public string ConnectServerId { get; set; }
  30. public string ConnectAccessKey { get; set; }
  31. public string WanIpAddress { get; private set; }
  32. public string WanApiAddress
  33. {
  34. get
  35. {
  36. var ip = WanIpAddress;
  37. if (!string.IsNullOrEmpty(ip))
  38. {
  39. if (!ip.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
  40. !ip.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  41. {
  42. ip = "http://" + ip;
  43. }
  44. return ip + ":" + _config.Configuration.HttpServerPortNumber.ToString(CultureInfo.InvariantCulture);
  45. }
  46. return null;
  47. }
  48. }
  49. public ConnectManager(ILogger logger,
  50. IApplicationPaths appPaths,
  51. IJsonSerializer json,
  52. IEncryptionManager encryption,
  53. IHttpClient httpClient,
  54. IServerApplicationHost appHost,
  55. IServerConfigurationManager config)
  56. {
  57. _logger = logger;
  58. _appPaths = appPaths;
  59. _json = json;
  60. _encryption = encryption;
  61. _httpClient = httpClient;
  62. _appHost = appHost;
  63. _config = config;
  64. LoadCachedData();
  65. }
  66. internal void OnWanAddressResolved(string address)
  67. {
  68. WanIpAddress = address;
  69. //UpdateConnectInfo();
  70. }
  71. private async void UpdateConnectInfo()
  72. {
  73. var wanApiAddress = WanApiAddress;
  74. if (string.IsNullOrWhiteSpace(wanApiAddress))
  75. {
  76. _logger.Warn("Cannot update Media Browser Connect information without a WanApiAddress");
  77. return;
  78. }
  79. try
  80. {
  81. var hasExistingRecord = !string.IsNullOrWhiteSpace(ConnectServerId) &&
  82. !string.IsNullOrWhiteSpace(ConnectAccessKey);
  83. var createNewRegistration = !hasExistingRecord;
  84. if (hasExistingRecord)
  85. {
  86. try
  87. {
  88. await UpdateServerRegistration(wanApiAddress).ConfigureAwait(false);
  89. }
  90. catch (HttpException ex)
  91. {
  92. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound || ex.StatusCode.Value != HttpStatusCode.Unauthorized)
  93. {
  94. throw;
  95. }
  96. createNewRegistration = true;
  97. }
  98. }
  99. if (createNewRegistration)
  100. {
  101. await CreateServerRegistration(wanApiAddress).ConfigureAwait(false);
  102. }
  103. }
  104. catch (Exception ex)
  105. {
  106. _logger.ErrorException("Error registering with Connect", ex);
  107. }
  108. }
  109. private async Task CreateServerRegistration(string wanApiAddress)
  110. {
  111. var url = "Servers";
  112. url = GetConnectUrl(url);
  113. var postData = new Dictionary<string, string>
  114. {
  115. {"name", _appHost.FriendlyName},
  116. {"url", wanApiAddress}
  117. };
  118. using (var stream = await _httpClient.Post(url, postData, CancellationToken.None).ConfigureAwait(false))
  119. {
  120. var data = _json.DeserializeFromStream<ServerRegistrationResponse>(stream);
  121. ConnectServerId = data.Id;
  122. ConnectAccessKey = data.AccessKey;
  123. CacheData();
  124. }
  125. }
  126. private async Task UpdateServerRegistration(string wanApiAddress)
  127. {
  128. var url = "Servers";
  129. url = GetConnectUrl(url);
  130. url += "?id=" + ConnectServerId;
  131. var options = new HttpRequestOptions
  132. {
  133. Url = url,
  134. CancellationToken = CancellationToken.None
  135. };
  136. options.SetPostData(new Dictionary<string, string>
  137. {
  138. {"name", _appHost.FriendlyName},
  139. {"url", wanApiAddress}
  140. });
  141. options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey);
  142. // No need to examine the response
  143. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  144. {
  145. }
  146. }
  147. private string CacheFilePath
  148. {
  149. get { return Path.Combine(_appPaths.DataPath, "connect.txt"); }
  150. }
  151. private void CacheData()
  152. {
  153. var path = CacheFilePath;
  154. try
  155. {
  156. Directory.CreateDirectory(Path.GetDirectoryName(path));
  157. var json = _json.SerializeToString(new ConnectData
  158. {
  159. AccessKey = ConnectAccessKey,
  160. ServerId = ConnectServerId
  161. });
  162. var encrypted = _encryption.EncryptString(json);
  163. File.WriteAllText(path, encrypted, Encoding.UTF8);
  164. }
  165. catch (Exception ex)
  166. {
  167. _logger.ErrorException("Error saving data", ex);
  168. }
  169. }
  170. private void LoadCachedData()
  171. {
  172. var path = CacheFilePath;
  173. try
  174. {
  175. var encrypted = File.ReadAllText(path, Encoding.UTF8);
  176. var json = _encryption.DecryptString(encrypted);
  177. var data = _json.DeserializeFromString<ConnectData>(json);
  178. ConnectAccessKey = data.AccessKey;
  179. ConnectServerId = data.ServerId;
  180. }
  181. catch (IOException)
  182. {
  183. // File isn't there. no biggie
  184. }
  185. catch (Exception ex)
  186. {
  187. _logger.ErrorException("Error loading data", ex);
  188. }
  189. }
  190. private string GetConnectUrl(string handler)
  191. {
  192. return "http://mb3admin.com/test/connect/" + handler;
  193. }
  194. }
  195. }