ConnectManager.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. {"systemid", _appHost.SystemId}
  118. };
  119. using (var stream = await _httpClient.Post(url, postData, CancellationToken.None).ConfigureAwait(false))
  120. {
  121. var data = _json.DeserializeFromStream<ServerRegistrationResponse>(stream);
  122. ConnectServerId = data.Id;
  123. ConnectAccessKey = data.AccessKey;
  124. CacheData();
  125. }
  126. }
  127. private async Task UpdateServerRegistration(string wanApiAddress)
  128. {
  129. var url = "Servers";
  130. url = GetConnectUrl(url);
  131. url += "?id=" + ConnectServerId;
  132. var options = new HttpRequestOptions
  133. {
  134. Url = url,
  135. CancellationToken = CancellationToken.None
  136. };
  137. options.SetPostData(new Dictionary<string, string>
  138. {
  139. {"name", _appHost.FriendlyName},
  140. {"url", wanApiAddress},
  141. {"systemid", _appHost.SystemId}
  142. });
  143. options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey);
  144. // No need to examine the response
  145. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  146. {
  147. }
  148. }
  149. private string CacheFilePath
  150. {
  151. get { return Path.Combine(_appPaths.DataPath, "connect.txt"); }
  152. }
  153. private void CacheData()
  154. {
  155. var path = CacheFilePath;
  156. try
  157. {
  158. Directory.CreateDirectory(Path.GetDirectoryName(path));
  159. var json = _json.SerializeToString(new ConnectData
  160. {
  161. AccessKey = ConnectAccessKey,
  162. ServerId = ConnectServerId
  163. });
  164. var encrypted = _encryption.EncryptString(json);
  165. File.WriteAllText(path, encrypted, Encoding.UTF8);
  166. }
  167. catch (Exception ex)
  168. {
  169. _logger.ErrorException("Error saving data", ex);
  170. }
  171. }
  172. private void LoadCachedData()
  173. {
  174. var path = CacheFilePath;
  175. try
  176. {
  177. var encrypted = File.ReadAllText(path, Encoding.UTF8);
  178. var json = _encryption.DecryptString(encrypted);
  179. var data = _json.DeserializeFromString<ConnectData>(json);
  180. ConnectAccessKey = data.AccessKey;
  181. ConnectServerId = data.ServerId;
  182. }
  183. catch (IOException)
  184. {
  185. // File isn't there. no biggie
  186. }
  187. catch (Exception ex)
  188. {
  189. _logger.ErrorException("Error loading data", ex);
  190. }
  191. }
  192. private string GetConnectUrl(string handler)
  193. {
  194. return "http://mb3admin.com/test/connect/" + handler;
  195. }
  196. }
  197. }