ConnectManager.cs 39 KB

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