ConnectManager.cs 39 KB

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