ConnectManager.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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.Providers;
  9. using MediaBrowser.Controller.Security;
  10. using MediaBrowser.Model.Connect;
  11. using MediaBrowser.Model.Entities;
  12. using MediaBrowser.Model.Logging;
  13. using MediaBrowser.Model.Net;
  14. using MediaBrowser.Model.Serialization;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Globalization;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Net;
  21. using System.Text;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. namespace MediaBrowser.Server.Implementations.Connect
  25. {
  26. public class ConnectManager : IConnectManager
  27. {
  28. private readonly SemaphoreSlim _operationLock = new SemaphoreSlim(1, 1);
  29. private readonly ILogger _logger;
  30. private readonly IApplicationPaths _appPaths;
  31. private readonly IJsonSerializer _json;
  32. private readonly IEncryptionManager _encryption;
  33. private readonly IHttpClient _httpClient;
  34. private readonly IServerApplicationHost _appHost;
  35. private readonly IServerConfigurationManager _config;
  36. private readonly IUserManager _userManager;
  37. private readonly IProviderManager _providerManager;
  38. private ConnectData _data = new ConnectData();
  39. public string ConnectServerId
  40. {
  41. get { return _data.ServerId; }
  42. }
  43. public string ConnectAccessKey
  44. {
  45. get { return _data.AccessKey; }
  46. }
  47. public string DiscoveredWanIpAddress { get; private set; }
  48. public string WanIpAddress
  49. {
  50. get
  51. {
  52. var address = _config.Configuration.WanDdns;
  53. if (string.IsNullOrWhiteSpace(address))
  54. {
  55. address = DiscoveredWanIpAddress;
  56. }
  57. return address;
  58. }
  59. }
  60. public string WanApiAddress
  61. {
  62. get
  63. {
  64. var ip = WanIpAddress;
  65. if (!string.IsNullOrEmpty(ip))
  66. {
  67. if (!ip.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
  68. !ip.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  69. {
  70. ip = "http://" + ip;
  71. }
  72. return ip + ":" + _config.Configuration.PublicPort.ToString(CultureInfo.InvariantCulture);
  73. }
  74. return null;
  75. }
  76. }
  77. public ConnectManager(ILogger logger,
  78. IApplicationPaths appPaths,
  79. IJsonSerializer json,
  80. IEncryptionManager encryption,
  81. IHttpClient httpClient,
  82. IServerApplicationHost appHost,
  83. IServerConfigurationManager config, IUserManager userManager, IProviderManager providerManager)
  84. {
  85. _logger = logger;
  86. _appPaths = appPaths;
  87. _json = json;
  88. _encryption = encryption;
  89. _httpClient = httpClient;
  90. _appHost = appHost;
  91. _config = config;
  92. _userManager = userManager;
  93. _providerManager = providerManager;
  94. LoadCachedData();
  95. }
  96. internal void OnWanAddressResolved(string address)
  97. {
  98. DiscoveredWanIpAddress = address;
  99. UpdateConnectInfo();
  100. }
  101. private async void UpdateConnectInfo()
  102. {
  103. await _operationLock.WaitAsync().ConfigureAwait(false);
  104. try
  105. {
  106. await UpdateConnectInfoInternal().ConfigureAwait(false);
  107. }
  108. finally
  109. {
  110. _operationLock.Release();
  111. }
  112. }
  113. private async Task UpdateConnectInfoInternal()
  114. {
  115. var wanApiAddress = WanApiAddress;
  116. if (string.IsNullOrWhiteSpace(wanApiAddress))
  117. {
  118. _logger.Warn("Cannot update Media Browser Connect information without a WanApiAddress");
  119. return;
  120. }
  121. try
  122. {
  123. var localAddress = _appHost.GetSystemInfo().LocalAddress;
  124. var hasExistingRecord = !string.IsNullOrWhiteSpace(ConnectServerId) &&
  125. !string.IsNullOrWhiteSpace(ConnectAccessKey);
  126. var createNewRegistration = !hasExistingRecord;
  127. if (hasExistingRecord)
  128. {
  129. try
  130. {
  131. await UpdateServerRegistration(wanApiAddress, localAddress).ConfigureAwait(false);
  132. }
  133. catch (HttpException ex)
  134. {
  135. if (!ex.StatusCode.HasValue ||
  136. !new[] { HttpStatusCode.NotFound, HttpStatusCode.Unauthorized }.Contains(ex.StatusCode.Value))
  137. {
  138. throw;
  139. }
  140. createNewRegistration = true;
  141. }
  142. }
  143. if (createNewRegistration)
  144. {
  145. await CreateServerRegistration(wanApiAddress, localAddress).ConfigureAwait(false);
  146. }
  147. await RefreshAuthorizationsInternal(true, CancellationToken.None).ConfigureAwait(false);
  148. }
  149. catch (Exception ex)
  150. {
  151. _logger.ErrorException("Error registering with Connect", ex);
  152. }
  153. }
  154. private async Task CreateServerRegistration(string wanApiAddress, string localAddress)
  155. {
  156. var url = "Servers";
  157. url = GetConnectUrl(url);
  158. var postData = new Dictionary<string, string>
  159. {
  160. {"name", _appHost.FriendlyName},
  161. {"url", wanApiAddress},
  162. {"systemId", _appHost.SystemId}
  163. };
  164. if (!string.IsNullOrWhiteSpace(localAddress))
  165. {
  166. postData["localAddress"] = localAddress;
  167. }
  168. using (var stream = await _httpClient.Post(url, postData, CancellationToken.None).ConfigureAwait(false))
  169. {
  170. var data = _json.DeserializeFromStream<ServerRegistrationResponse>(stream);
  171. _data.ServerId = data.Id;
  172. _data.AccessKey = data.AccessKey;
  173. CacheData();
  174. }
  175. }
  176. private async Task UpdateServerRegistration(string wanApiAddress, string localAddress)
  177. {
  178. var url = "Servers";
  179. url = GetConnectUrl(url);
  180. url += "?id=" + ConnectServerId;
  181. var postData = new Dictionary<string, string>
  182. {
  183. {"name", _appHost.FriendlyName},
  184. {"url", wanApiAddress},
  185. {"systemId", _appHost.SystemId}
  186. };
  187. if (!string.IsNullOrWhiteSpace(localAddress))
  188. {
  189. postData["localAddress"] = localAddress;
  190. }
  191. var options = new HttpRequestOptions
  192. {
  193. Url = url,
  194. CancellationToken = CancellationToken.None
  195. };
  196. options.SetPostData(postData);
  197. SetServerAccessToken(options);
  198. // No need to examine the response
  199. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  200. {
  201. }
  202. }
  203. private readonly object _dataFileLock = new object();
  204. private string CacheFilePath
  205. {
  206. get { return Path.Combine(_appPaths.DataPath, "connect.txt"); }
  207. }
  208. private void CacheData()
  209. {
  210. var path = CacheFilePath;
  211. try
  212. {
  213. Directory.CreateDirectory(Path.GetDirectoryName(path));
  214. var json = _json.SerializeToString(_data);
  215. var encrypted = _encryption.EncryptString(json);
  216. lock (_dataFileLock)
  217. {
  218. File.WriteAllText(path, encrypted, Encoding.UTF8);
  219. }
  220. }
  221. catch (Exception ex)
  222. {
  223. _logger.ErrorException("Error saving data", ex);
  224. }
  225. }
  226. private void LoadCachedData()
  227. {
  228. var path = CacheFilePath;
  229. try
  230. {
  231. lock (_dataFileLock)
  232. {
  233. var encrypted = File.ReadAllText(path, Encoding.UTF8);
  234. var json = _encryption.DecryptString(encrypted);
  235. _data = _json.DeserializeFromString<ConnectData>(json);
  236. }
  237. }
  238. catch (IOException)
  239. {
  240. // File isn't there. no biggie
  241. }
  242. catch (Exception ex)
  243. {
  244. _logger.ErrorException("Error loading data", ex);
  245. }
  246. }
  247. private User GetUser(string id)
  248. {
  249. var user = _userManager.GetUserById(id);
  250. if (user == null)
  251. {
  252. throw new ArgumentException("User not found.");
  253. }
  254. return user;
  255. }
  256. private string GetConnectUrl(string handler)
  257. {
  258. return "https://connect.mediabrowser.tv/service/" + handler;
  259. }
  260. public async Task<UserLinkResult> LinkUser(string userId, string connectUsername)
  261. {
  262. await _operationLock.WaitAsync().ConfigureAwait(false);
  263. try
  264. {
  265. return await LinkUserInternal(userId, connectUsername).ConfigureAwait(false);
  266. }
  267. finally
  268. {
  269. _operationLock.Release();
  270. }
  271. }
  272. private async Task<UserLinkResult> LinkUserInternal(string userId, string connectUsername)
  273. {
  274. if (string.IsNullOrWhiteSpace(connectUsername))
  275. {
  276. throw new ArgumentNullException("connectUsername");
  277. }
  278. var connectUser = await GetConnectUser(new ConnectUserQuery
  279. {
  280. Name = connectUsername
  281. }, CancellationToken.None).ConfigureAwait(false);
  282. if (!connectUser.IsActive)
  283. {
  284. throw new ArgumentException("The Media Browser account has been disabled.");
  285. }
  286. var user = GetUser(userId);
  287. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  288. {
  289. await RemoveConnect(user, connectUser.Id).ConfigureAwait(false);
  290. }
  291. var url = GetConnectUrl("ServerAuthorizations");
  292. var options = new HttpRequestOptions
  293. {
  294. Url = url,
  295. CancellationToken = CancellationToken.None
  296. };
  297. var accessToken = Guid.NewGuid().ToString("N");
  298. var postData = new Dictionary<string, string>
  299. {
  300. {"serverId", ConnectServerId},
  301. {"userId", connectUser.Id},
  302. {"userType", "Linked"},
  303. {"accessToken", accessToken}
  304. };
  305. options.SetPostData(postData);
  306. SetServerAccessToken(options);
  307. var result = new UserLinkResult();
  308. // No need to examine the response
  309. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  310. {
  311. var response = _json.DeserializeFromStream<ServerUserAuthorizationResponse>(stream);
  312. result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase);
  313. }
  314. user.ConnectAccessKey = accessToken;
  315. user.ConnectUserName = connectUser.Name;
  316. user.ConnectUserId = connectUser.Id;
  317. user.ConnectLinkType = UserLinkType.LinkedUser;
  318. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  319. user.Configuration.SyncConnectImage = false;
  320. user.Configuration.SyncConnectName = false;
  321. _userManager.UpdateConfiguration(user, user.Configuration);
  322. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  323. return result;
  324. }
  325. public async Task<UserLinkResult> InviteUser(string sendingUserId, string connectUsername)
  326. {
  327. await _operationLock.WaitAsync().ConfigureAwait(false);
  328. try
  329. {
  330. return await InviteUserInternal(sendingUserId, connectUsername).ConfigureAwait(false);
  331. }
  332. finally
  333. {
  334. _operationLock.Release();
  335. }
  336. }
  337. private async Task<UserLinkResult> InviteUserInternal(string sendingUserId, string connectUsername)
  338. {
  339. if (string.IsNullOrWhiteSpace(connectUsername))
  340. {
  341. throw new ArgumentNullException("connectUsername");
  342. }
  343. string connectUserId = null;
  344. var result = new UserLinkResult();
  345. try
  346. {
  347. var connectUser = await GetConnectUser(new ConnectUserQuery
  348. {
  349. Name = connectUsername
  350. }, CancellationToken.None).ConfigureAwait(false);
  351. if (!connectUser.IsActive)
  352. {
  353. throw new ArgumentException("The Media Browser account has been disabled.");
  354. }
  355. connectUserId = connectUser.Id;
  356. result.GuestDisplayName = connectUser.Name;
  357. }
  358. catch (HttpException ex)
  359. {
  360. if (!ex.StatusCode.HasValue ||
  361. ex.StatusCode.Value != HttpStatusCode.NotFound ||
  362. !Validator.EmailIsValid(connectUsername))
  363. {
  364. throw;
  365. }
  366. }
  367. var sendingUser = GetUser(sendingUserId);
  368. var requesterUserName = sendingUser.ConnectUserName;
  369. if (string.IsNullOrWhiteSpace(requesterUserName))
  370. {
  371. requesterUserName = sendingUser.Name;
  372. }
  373. if (string.IsNullOrWhiteSpace(connectUserId))
  374. {
  375. return await SendNewUserInvitation(requesterUserName, connectUsername).ConfigureAwait(false);
  376. }
  377. var url = GetConnectUrl("ServerAuthorizations");
  378. var options = new HttpRequestOptions
  379. {
  380. Url = url,
  381. CancellationToken = CancellationToken.None
  382. };
  383. var accessToken = Guid.NewGuid().ToString("N");
  384. var postData = new Dictionary<string, string>
  385. {
  386. {"serverId", ConnectServerId},
  387. {"userId", connectUserId},
  388. {"userType", "Guest"},
  389. {"accessToken", accessToken},
  390. {"requesterUserName", requesterUserName}
  391. };
  392. options.SetPostData(postData);
  393. SetServerAccessToken(options);
  394. // No need to examine the response
  395. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  396. {
  397. var response = _json.DeserializeFromStream<ServerUserAuthorizationResponse>(stream);
  398. result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase);
  399. }
  400. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  401. return result;
  402. }
  403. private async Task<UserLinkResult> SendNewUserInvitation(string fromName, string email)
  404. {
  405. var url = GetConnectUrl("users/invite");
  406. var options = new HttpRequestOptions
  407. {
  408. Url = url,
  409. CancellationToken = CancellationToken.None
  410. };
  411. var postData = new Dictionary<string, string>
  412. {
  413. {"email", email},
  414. {"requesterUserName", fromName}
  415. };
  416. options.SetPostData(postData);
  417. // No need to examine the response
  418. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  419. {
  420. }
  421. return new UserLinkResult
  422. {
  423. IsNewUserInvitation = true,
  424. GuestDisplayName = email
  425. };
  426. }
  427. public Task RemoveConnect(string userId)
  428. {
  429. var user = GetUser(userId);
  430. return RemoveConnect(user, user.ConnectUserId);
  431. }
  432. private async Task RemoveConnect(User user, string connectUserId)
  433. {
  434. if (!string.IsNullOrWhiteSpace(connectUserId))
  435. {
  436. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  437. }
  438. user.ConnectAccessKey = null;
  439. user.ConnectUserName = null;
  440. user.ConnectUserId = null;
  441. user.ConnectLinkType = null;
  442. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  443. }
  444. private async Task<ConnectUser> GetConnectUser(ConnectUserQuery query, CancellationToken cancellationToken)
  445. {
  446. var url = GetConnectUrl("user");
  447. if (!string.IsNullOrWhiteSpace(query.Id))
  448. {
  449. url = url + "?id=" + WebUtility.UrlEncode(query.Id);
  450. }
  451. else if (!string.IsNullOrWhiteSpace(query.Name))
  452. {
  453. url = url + "?name=" + WebUtility.UrlEncode(query.Name);
  454. }
  455. else if (!string.IsNullOrWhiteSpace(query.Email))
  456. {
  457. url = url + "?name=" + WebUtility.UrlEncode(query.Email);
  458. }
  459. var options = new HttpRequestOptions
  460. {
  461. CancellationToken = cancellationToken,
  462. Url = url
  463. };
  464. SetServerAccessToken(options);
  465. using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
  466. {
  467. var response = _json.DeserializeFromStream<GetConnectUserResponse>(stream);
  468. return new ConnectUser
  469. {
  470. Email = response.Email,
  471. Id = response.Id,
  472. Name = response.Name,
  473. IsActive = response.IsActive,
  474. ImageUrl = response.ImageUrl
  475. };
  476. }
  477. }
  478. private void SetServerAccessToken(HttpRequestOptions options)
  479. {
  480. options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey);
  481. }
  482. public async Task RefreshAuthorizations(CancellationToken cancellationToken)
  483. {
  484. await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  485. try
  486. {
  487. await RefreshAuthorizationsInternal(true, cancellationToken).ConfigureAwait(false);
  488. }
  489. finally
  490. {
  491. _operationLock.Release();
  492. }
  493. }
  494. private async Task RefreshAuthorizationsInternal(bool refreshImages, CancellationToken cancellationToken)
  495. {
  496. var url = GetConnectUrl("ServerAuthorizations");
  497. url += "?serverId=" + ConnectServerId;
  498. var options = new HttpRequestOptions
  499. {
  500. Url = url,
  501. CancellationToken = cancellationToken
  502. };
  503. SetServerAccessToken(options);
  504. try
  505. {
  506. using (var stream = (await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)).Content)
  507. {
  508. var list = _json.DeserializeFromStream<List<ServerUserAuthorizationResponse>>(stream);
  509. await RefreshAuthorizations(list, refreshImages).ConfigureAwait(false);
  510. }
  511. }
  512. catch (Exception ex)
  513. {
  514. _logger.ErrorException("Error refreshing server authorizations.", ex);
  515. }
  516. }
  517. private readonly SemaphoreSlim _connectImageSemaphore = new SemaphoreSlim(5, 5);
  518. private async Task RefreshAuthorizations(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  519. {
  520. var users = _userManager.Users.ToList();
  521. // Handle existing authorizations that were removed by the Connect server
  522. // Handle existing authorizations whose status may have been updated
  523. foreach (var user in users)
  524. {
  525. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  526. {
  527. var connectEntry = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.OrdinalIgnoreCase));
  528. if (connectEntry == null)
  529. {
  530. var deleteUser = user.ConnectLinkType.HasValue &&
  531. user.ConnectLinkType.Value == UserLinkType.Guest;
  532. user.ConnectUserId = null;
  533. user.ConnectAccessKey = null;
  534. user.ConnectUserName = null;
  535. user.ConnectLinkType = null;
  536. await _userManager.UpdateUser(user).ConfigureAwait(false);
  537. if (deleteUser)
  538. {
  539. _logger.Debug("Deleting guest user {0}", user.Name);
  540. await _userManager.DeleteUser(user).ConfigureAwait(false);
  541. }
  542. }
  543. else
  544. {
  545. var changed = !string.Equals(user.ConnectAccessKey, connectEntry.AccessToken, StringComparison.OrdinalIgnoreCase);
  546. if (changed)
  547. {
  548. user.ConnectUserId = connectEntry.UserId;
  549. user.ConnectAccessKey = connectEntry.AccessToken;
  550. await _userManager.UpdateUser(user).ConfigureAwait(false);
  551. }
  552. }
  553. }
  554. }
  555. var pending = new List<ConnectAuthorization>();
  556. foreach (var connectEntry in list)
  557. {
  558. if (string.Equals(connectEntry.UserType, "guest", StringComparison.OrdinalIgnoreCase))
  559. {
  560. if (string.Equals(connectEntry.AcceptStatus, "accepted", StringComparison.OrdinalIgnoreCase))
  561. {
  562. var user = _userManager.Users
  563. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectEntry.UserId, StringComparison.OrdinalIgnoreCase));
  564. if (user == null)
  565. {
  566. // Add user
  567. user = await _userManager.CreateUser(connectEntry.UserName).ConfigureAwait(false);
  568. user.ConnectUserName = connectEntry.UserName;
  569. user.ConnectUserId = connectEntry.UserId;
  570. user.ConnectLinkType = UserLinkType.Guest;
  571. user.ConnectAccessKey = connectEntry.AccessToken;
  572. await _userManager.UpdateUser(user).ConfigureAwait(false);
  573. user.Configuration.SyncConnectImage = true;
  574. user.Configuration.SyncConnectName = true;
  575. user.Configuration.IsHidden = true;
  576. user.Configuration.EnableLiveTvManagement = false;
  577. user.Configuration.IsAdministrator = false;
  578. _userManager.UpdateConfiguration(user, user.Configuration);
  579. }
  580. }
  581. else if (string.Equals(connectEntry.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase))
  582. {
  583. pending.Add(new ConnectAuthorization
  584. {
  585. ConnectUserId = connectEntry.UserId,
  586. ImageUrl = connectEntry.UserImageUrl,
  587. UserName = connectEntry.UserName,
  588. Id = connectEntry.Id
  589. });
  590. }
  591. }
  592. }
  593. _data.PendingAuthorizations = pending;
  594. CacheData();
  595. await RefreshGuestNames(list, refreshImages).ConfigureAwait(false);
  596. }
  597. private async Task RefreshGuestNames(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  598. {
  599. var users = _userManager.Users
  600. .Where(i => !string.IsNullOrEmpty(i.ConnectUserId) &&
  601. (i.Configuration.SyncConnectImage || i.Configuration.SyncConnectName))
  602. .ToList();
  603. foreach (var user in users)
  604. {
  605. var authorization = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.Ordinal));
  606. if (authorization == null)
  607. {
  608. _logger.Warn("Unable to find connect authorization record for user {0}", user.Name);
  609. continue;
  610. }
  611. if (user.Configuration.SyncConnectName)
  612. {
  613. var changed = !string.Equals(authorization.UserName, user.Name, StringComparison.OrdinalIgnoreCase);
  614. if (changed)
  615. {
  616. await user.Rename(authorization.UserName).ConfigureAwait(false);
  617. }
  618. }
  619. if (user.Configuration.SyncConnectImage)
  620. {
  621. var imageUrl = authorization.UserImageUrl;
  622. if (!string.IsNullOrWhiteSpace(imageUrl))
  623. {
  624. var changed = false;
  625. if (!user.HasImage(ImageType.Primary))
  626. {
  627. changed = true;
  628. }
  629. else if (refreshImages)
  630. {
  631. using (var response = await _httpClient.SendAsync(new HttpRequestOptions
  632. {
  633. Url = imageUrl,
  634. BufferContent = false
  635. }, "HEAD").ConfigureAwait(false))
  636. {
  637. var length = response.ContentLength;
  638. if (length != new FileInfo(user.GetImageInfo(ImageType.Primary, 0).Path).Length)
  639. {
  640. changed = true;
  641. }
  642. }
  643. }
  644. if (changed)
  645. {
  646. await _providerManager.SaveImage(user, imageUrl, _connectImageSemaphore, ImageType.Primary, null, CancellationToken.None).ConfigureAwait(false);
  647. await user.RefreshMetadata(new MetadataRefreshOptions
  648. {
  649. ForceSave = true,
  650. }, CancellationToken.None).ConfigureAwait(false);
  651. }
  652. }
  653. }
  654. }
  655. }
  656. public async Task<List<ConnectAuthorization>> GetPendingGuests()
  657. {
  658. var time = DateTime.UtcNow - _data.LastAuthorizationsRefresh;
  659. if (time.TotalMinutes >= 5)
  660. {
  661. await _operationLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  662. try
  663. {
  664. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  665. _data.LastAuthorizationsRefresh = DateTime.UtcNow;
  666. CacheData();
  667. }
  668. finally
  669. {
  670. _operationLock.Release();
  671. }
  672. }
  673. return _data.PendingAuthorizations.ToList();
  674. }
  675. public async Task CancelAuthorization(string id)
  676. {
  677. await _operationLock.WaitAsync().ConfigureAwait(false);
  678. try
  679. {
  680. await CancelAuthorizationInternal(id).ConfigureAwait(false);
  681. }
  682. finally
  683. {
  684. _operationLock.Release();
  685. }
  686. }
  687. private async Task CancelAuthorizationInternal(string id)
  688. {
  689. var connectUserId = _data.PendingAuthorizations
  690. .First(i => string.Equals(i.Id, id, StringComparison.Ordinal))
  691. .ConnectUserId;
  692. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  693. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  694. }
  695. private async Task CancelAuthorizationByConnectUserId(string connectUserId)
  696. {
  697. var url = GetConnectUrl("ServerAuthorizations");
  698. var options = new HttpRequestOptions
  699. {
  700. Url = url,
  701. CancellationToken = CancellationToken.None
  702. };
  703. var postData = new Dictionary<string, string>
  704. {
  705. {"serverId", ConnectServerId},
  706. {"userId", connectUserId}
  707. };
  708. options.SetPostData(postData);
  709. SetServerAccessToken(options);
  710. try
  711. {
  712. // No need to examine the response
  713. using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
  714. {
  715. }
  716. }
  717. catch (HttpException ex)
  718. {
  719. // If connect says the auth doesn't exist, we can handle that gracefully since this is a remove operation
  720. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  721. {
  722. throw;
  723. }
  724. _logger.Debug("Connect returned a 404 when removing a user auth link. Handling it.");
  725. }
  726. }
  727. public async Task Authenticate(string username, string passwordMd5)
  728. {
  729. var request = new HttpRequestOptions
  730. {
  731. Url = GetConnectUrl("user/authenticate")
  732. };
  733. request.SetPostData(new Dictionary<string, string>
  734. {
  735. {"userName",username},
  736. {"password",passwordMd5}
  737. });
  738. // No need to examine the response
  739. using (var stream = (await _httpClient.SendAsync(request, "POST").ConfigureAwait(false)).Content)
  740. {
  741. }
  742. }
  743. }
  744. }