ConnectManager.cs 40 KB

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