ConnectManager.cs 40 KB

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