ConnectManager.cs 6.3 KB

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