ConnectManager.cs 41 KB

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