ConnectManager.cs 36 KB

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