ConnectManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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.Entities;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.Security;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Net;
  11. using MediaBrowser.Model.Serialization;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Globalization;
  15. using System.IO;
  16. using System.Net;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Server.Implementations.Connect
  21. {
  22. public class ConnectManager : IConnectManager
  23. {
  24. private readonly ILogger _logger;
  25. private readonly IApplicationPaths _appPaths;
  26. private readonly IJsonSerializer _json;
  27. private readonly IEncryptionManager _encryption;
  28. private readonly IHttpClient _httpClient;
  29. private readonly IServerApplicationHost _appHost;
  30. private readonly IServerConfigurationManager _config;
  31. private readonly IUserManager _userManager;
  32. private ConnectData _data = new ConnectData();
  33. public string ConnectServerId
  34. {
  35. get { return _data.ServerId; }
  36. }
  37. public string ConnectAccessKey
  38. {
  39. get { return _data.AccessKey; }
  40. }
  41. public string DiscoveredWanIpAddress { get; private set; }
  42. public string WanIpAddress
  43. {
  44. get
  45. {
  46. var address = _config.Configuration.WanDdns;
  47. if (string.IsNullOrWhiteSpace(address))
  48. {
  49. address = DiscoveredWanIpAddress;
  50. }
  51. return address;
  52. }
  53. }
  54. public string WanApiAddress
  55. {
  56. get
  57. {
  58. var ip = WanIpAddress;
  59. if (!string.IsNullOrEmpty(ip))
  60. {
  61. if (!ip.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
  62. !ip.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  63. {
  64. ip = "http://" + ip;
  65. }
  66. return ip + ":" + _config.Configuration.HttpServerPortNumber.ToString(CultureInfo.InvariantCulture);
  67. }
  68. return null;
  69. }
  70. }
  71. public ConnectManager(ILogger logger,
  72. IApplicationPaths appPaths,
  73. IJsonSerializer json,
  74. IEncryptionManager encryption,
  75. IHttpClient httpClient,
  76. IServerApplicationHost appHost,
  77. IServerConfigurationManager config, IUserManager userManager)
  78. {
  79. _logger = logger;
  80. _appPaths = appPaths;
  81. _json = json;
  82. _encryption = encryption;
  83. _httpClient = httpClient;
  84. _appHost = appHost;
  85. _config = config;
  86. _userManager = userManager;
  87. LoadCachedData();
  88. }
  89. internal void OnWanAddressResolved(string address)
  90. {
  91. DiscoveredWanIpAddress = address;
  92. UpdateConnectInfo();
  93. }
  94. private async void UpdateConnectInfo()
  95. {
  96. var wanApiAddress = WanApiAddress;
  97. if (string.IsNullOrWhiteSpace(wanApiAddress))
  98. {
  99. _logger.Warn("Cannot update Media Browser Connect information without a WanApiAddress");
  100. return;
  101. }
  102. try
  103. {
  104. var hasExistingRecord = !string.IsNullOrWhiteSpace(ConnectServerId) &&
  105. !string.IsNullOrWhiteSpace(ConnectAccessKey);
  106. var createNewRegistration = !hasExistingRecord;
  107. if (hasExistingRecord)
  108. {
  109. try
  110. {
  111. await UpdateServerRegistration(wanApiAddress).ConfigureAwait(false);
  112. }
  113. catch (HttpException ex)
  114. {
  115. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound || ex.StatusCode.Value != HttpStatusCode.Unauthorized)
  116. {
  117. throw;
  118. }
  119. createNewRegistration = true;
  120. }
  121. }
  122. if (createNewRegistration)
  123. {
  124. await CreateServerRegistration(wanApiAddress).ConfigureAwait(false);
  125. }
  126. }
  127. catch (Exception ex)
  128. {
  129. _logger.ErrorException("Error registering with Connect", ex);
  130. }
  131. }
  132. private async Task CreateServerRegistration(string wanApiAddress)
  133. {
  134. var url = "Servers";
  135. url = GetConnectUrl(url);
  136. var postData = new Dictionary<string, string>
  137. {
  138. {"name", _appHost.FriendlyName},
  139. {"url", wanApiAddress},
  140. {"systemid", _appHost.SystemId}
  141. };
  142. using (var stream = await _httpClient.Post(url, postData, CancellationToken.None).ConfigureAwait(false))
  143. {
  144. var data = _json.DeserializeFromStream<ServerRegistrationResponse>(stream);
  145. _data.ServerId = data.Id;
  146. _data.AccessKey = data.AccessKey;
  147. CacheData();
  148. }
  149. }
  150. private async Task UpdateServerRegistration(string wanApiAddress)
  151. {
  152. var url = "Servers";
  153. url = GetConnectUrl(url);
  154. url += "?id=" + ConnectServerId;
  155. var options = new HttpRequestOptions
  156. {
  157. Url = url,
  158. CancellationToken = CancellationToken.None
  159. };
  160. options.SetPostData(new Dictionary<string, string>
  161. {
  162. {"name", _appHost.FriendlyName},
  163. {"url", wanApiAddress},
  164. {"systemid", _appHost.SystemId}
  165. });
  166. SetServerAccessToken(options);
  167. // No need to examine the response
  168. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  169. {
  170. }
  171. }
  172. private string CacheFilePath
  173. {
  174. get { return Path.Combine(_appPaths.DataPath, "connect.txt"); }
  175. }
  176. private void CacheData()
  177. {
  178. var path = CacheFilePath;
  179. try
  180. {
  181. Directory.CreateDirectory(Path.GetDirectoryName(path));
  182. var json = _json.SerializeToString(_data);
  183. var encrypted = _encryption.EncryptString(json);
  184. File.WriteAllText(path, encrypted, Encoding.UTF8);
  185. }
  186. catch (Exception ex)
  187. {
  188. _logger.ErrorException("Error saving data", ex);
  189. }
  190. }
  191. private void LoadCachedData()
  192. {
  193. var path = CacheFilePath;
  194. try
  195. {
  196. var encrypted = File.ReadAllText(path, Encoding.UTF8);
  197. var json = _encryption.DecryptString(encrypted);
  198. _data = _json.DeserializeFromString<ConnectData>(json);
  199. }
  200. catch (IOException)
  201. {
  202. // File isn't there. no biggie
  203. }
  204. catch (Exception ex)
  205. {
  206. _logger.ErrorException("Error loading data", ex);
  207. }
  208. }
  209. private User GetUser(string id)
  210. {
  211. var user = _userManager.GetUserById(id);
  212. if (user == null)
  213. {
  214. throw new ArgumentException("User not found.");
  215. }
  216. return user;
  217. }
  218. public ConnectUserLink GetUserInfo(string userId)
  219. {
  220. var user = GetUser(userId);
  221. return new ConnectUserLink
  222. {
  223. LocalUserId = user.Id.ToString("N"),
  224. Username = user.ConnectUserName,
  225. UserId = user.ConnectUserId
  226. };
  227. }
  228. private string GetConnectUrl(string handler)
  229. {
  230. return "https://connect.mediabrowser.tv/service/" + handler;
  231. }
  232. public async Task LinkUser(string userId, string connectUsername)
  233. {
  234. if (string.IsNullOrWhiteSpace(connectUsername))
  235. {
  236. throw new ArgumentNullException("connectUsername");
  237. }
  238. var connectUser = await GetConnectUser(new ConnectUserQuery
  239. {
  240. Name = connectUsername
  241. }, CancellationToken.None).ConfigureAwait(false);
  242. var user = GetUser(userId);
  243. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  244. {
  245. await RemoveLink(user, connectUser).ConfigureAwait(false);
  246. }
  247. var url = GetConnectUrl("ServerAuthorizations");
  248. var options = new HttpRequestOptions
  249. {
  250. Url = url,
  251. CancellationToken = CancellationToken.None
  252. };
  253. var accessToken = Guid.NewGuid().ToString("N");
  254. var postData = new Dictionary<string, string>
  255. {
  256. {"serverId", ConnectServerId},
  257. {"userId", connectUser.Id},
  258. {"userType", "Linked"},
  259. {"accessToken", accessToken}
  260. };
  261. options.SetPostData(postData);
  262. SetServerAccessToken(options);
  263. // No need to examine the response
  264. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  265. {
  266. }
  267. user.ConnectAccessKey = accessToken;
  268. user.ConnectUserName = connectUser.Name;
  269. user.ConnectUserId = connectUser.Id;
  270. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  271. }
  272. public async Task RemoveLink(string userId)
  273. {
  274. var user = GetUser(userId);
  275. var connectUser = await GetConnectUser(new ConnectUserQuery
  276. {
  277. Name = user.ConnectUserId
  278. }, CancellationToken.None).ConfigureAwait(false);
  279. await RemoveLink(user, connectUser).ConfigureAwait(false);
  280. }
  281. public async Task RemoveLink(User user, ConnectUser connectUser)
  282. {
  283. var url = GetConnectUrl("ServerAuthorizations");
  284. var options = new HttpRequestOptions
  285. {
  286. Url = url,
  287. CancellationToken = CancellationToken.None
  288. };
  289. var postData = new Dictionary<string, string>
  290. {
  291. {"serverId", ConnectServerId},
  292. {"userId", connectUser.Id}
  293. };
  294. options.SetPostData(postData);
  295. SetServerAccessToken(options);
  296. // No need to examine the response
  297. using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
  298. {
  299. }
  300. user.ConnectAccessKey = null;
  301. user.ConnectUserName = null;
  302. user.ConnectUserId = null;
  303. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  304. }
  305. private async Task<ConnectUser> GetConnectUser(ConnectUserQuery query, CancellationToken cancellationToken)
  306. {
  307. var url = GetConnectUrl("user");
  308. if (!string.IsNullOrWhiteSpace(query.Id))
  309. {
  310. url = url + "?id=" + WebUtility.UrlEncode(query.Id);
  311. }
  312. else if (!string.IsNullOrWhiteSpace(query.Name))
  313. {
  314. url = url + "?name=" + WebUtility.UrlEncode(query.Name);
  315. }
  316. else if (!string.IsNullOrWhiteSpace(query.Email))
  317. {
  318. url = url + "?email=" + WebUtility.UrlEncode(query.Email);
  319. }
  320. var options = new HttpRequestOptions
  321. {
  322. CancellationToken = cancellationToken,
  323. Url = url
  324. };
  325. SetServerAccessToken(options);
  326. using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
  327. {
  328. var response = _json.DeserializeFromStream<GetConnectUserResponse>(stream);
  329. return new ConnectUser
  330. {
  331. Email = response.Email,
  332. Id = response.Id,
  333. Name = response.Name
  334. };
  335. }
  336. }
  337. private void SetServerAccessToken(HttpRequestOptions options)
  338. {
  339. options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey);
  340. }
  341. }
  342. }