ConnectManager.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  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(userId))
  337. {
  338. throw new ArgumentNullException("userId");
  339. }
  340. if (string.IsNullOrWhiteSpace(connectUsername))
  341. {
  342. throw new ArgumentNullException("connectUsername");
  343. }
  344. if (string.IsNullOrWhiteSpace(ConnectServerId))
  345. {
  346. await UpdateConnectInfo().ConfigureAwait(false);
  347. }
  348. await _operationLock.WaitAsync().ConfigureAwait(false);
  349. try
  350. {
  351. return await LinkUserInternal(userId, connectUsername).ConfigureAwait(false);
  352. }
  353. finally
  354. {
  355. _operationLock.Release();
  356. }
  357. }
  358. private async Task<UserLinkResult> LinkUserInternal(string userId, string 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 existingUser = _userManager.Users.FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUser.Id) && !string.IsNullOrWhiteSpace(i.ConnectAccessKey));
  373. if (existingUser != null)
  374. {
  375. throw new InvalidOperationException("This connect user is already linked to local user " + existingUser.Name);
  376. }
  377. var user = GetUser(userId);
  378. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  379. {
  380. await RemoveConnect(user, user.ConnectUserId).ConfigureAwait(false);
  381. }
  382. var url = GetConnectUrl("ServerAuthorizations");
  383. var options = new HttpRequestOptions
  384. {
  385. Url = url,
  386. CancellationToken = CancellationToken.None
  387. };
  388. var accessToken = Guid.NewGuid().ToString("N");
  389. var postData = new Dictionary<string, string>
  390. {
  391. {"serverId", ConnectServerId},
  392. {"userId", connectUser.Id},
  393. {"userType", "Linked"},
  394. {"accessToken", accessToken}
  395. };
  396. options.SetPostData(postData);
  397. SetServerAccessToken(options);
  398. SetApplicationHeader(options);
  399. var result = new UserLinkResult();
  400. // No need to examine the response
  401. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  402. {
  403. var response = _json.DeserializeFromStream<ServerUserAuthorizationResponse>(stream);
  404. result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase);
  405. }
  406. user.ConnectAccessKey = accessToken;
  407. user.ConnectUserName = connectUser.Name;
  408. user.ConnectUserId = connectUser.Id;
  409. user.ConnectLinkType = UserLinkType.LinkedUser;
  410. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  411. await _userManager.UpdateConfiguration(user.Id.ToString("N"), user.Configuration);
  412. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  413. return result;
  414. }
  415. public async Task<UserLinkResult> InviteUser(ConnectAuthorizationRequest request)
  416. {
  417. if (string.IsNullOrWhiteSpace(ConnectServerId))
  418. {
  419. await UpdateConnectInfo().ConfigureAwait(false);
  420. }
  421. await _operationLock.WaitAsync().ConfigureAwait(false);
  422. try
  423. {
  424. return await InviteUserInternal(request).ConfigureAwait(false);
  425. }
  426. finally
  427. {
  428. _operationLock.Release();
  429. }
  430. }
  431. private async Task<UserLinkResult> InviteUserInternal(ConnectAuthorizationRequest request)
  432. {
  433. var connectUsername = request.ConnectUserName;
  434. var sendingUserId = request.SendingUserId;
  435. if (string.IsNullOrWhiteSpace(connectUsername))
  436. {
  437. throw new ArgumentNullException("connectUsername");
  438. }
  439. if (string.IsNullOrWhiteSpace(ConnectServerId))
  440. {
  441. throw new ArgumentNullException("ConnectServerId");
  442. }
  443. var sendingUser = GetUser(sendingUserId);
  444. var requesterUserName = sendingUser.ConnectUserName;
  445. if (string.IsNullOrWhiteSpace(requesterUserName))
  446. {
  447. throw new ArgumentException("A Connect account is required in order to send invitations.");
  448. }
  449. string connectUserId = null;
  450. var result = new UserLinkResult();
  451. try
  452. {
  453. var connectUser = await GetConnectUser(new ConnectUserQuery
  454. {
  455. NameOrEmail = connectUsername
  456. }, CancellationToken.None).ConfigureAwait(false);
  457. if (!connectUser.IsActive)
  458. {
  459. throw new ArgumentException("The Emby account is not active. Please ensure the account has been activated by following the instructions within the email confirmation.");
  460. }
  461. connectUserId = connectUser.Id;
  462. result.GuestDisplayName = connectUser.Name;
  463. }
  464. catch (HttpException ex)
  465. {
  466. if (!ex.StatusCode.HasValue)
  467. {
  468. throw;
  469. }
  470. // If they entered a username, then whatever the error is just throw it, for example, user not found
  471. if (!Validator.EmailIsValid(connectUsername))
  472. {
  473. if (ex.StatusCode.Value == HttpStatusCode.NotFound)
  474. {
  475. throw new ResourceNotFoundException();
  476. }
  477. throw;
  478. }
  479. if (ex.StatusCode.Value != HttpStatusCode.NotFound)
  480. {
  481. throw;
  482. }
  483. }
  484. if (string.IsNullOrWhiteSpace(connectUserId))
  485. {
  486. return await SendNewUserInvitation(requesterUserName, connectUsername).ConfigureAwait(false);
  487. }
  488. var url = GetConnectUrl("ServerAuthorizations");
  489. var options = new HttpRequestOptions
  490. {
  491. Url = url,
  492. CancellationToken = CancellationToken.None
  493. };
  494. var accessToken = Guid.NewGuid().ToString("N");
  495. var postData = new Dictionary<string, string>
  496. {
  497. {"serverId", ConnectServerId},
  498. {"userId", connectUserId},
  499. {"userType", "Guest"},
  500. {"accessToken", accessToken},
  501. {"requesterUserName", requesterUserName}
  502. };
  503. options.SetPostData(postData);
  504. SetServerAccessToken(options);
  505. SetApplicationHeader(options);
  506. // No need to examine the response
  507. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  508. {
  509. var response = _json.DeserializeFromStream<ServerUserAuthorizationResponse>(stream);
  510. result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase);
  511. _data.PendingAuthorizations.Add(new ConnectAuthorizationInternal
  512. {
  513. ConnectUserId = response.UserId,
  514. Id = response.Id,
  515. ImageUrl = response.UserImageUrl,
  516. UserName = response.UserName,
  517. EnabledLibraries = request.EnabledLibraries,
  518. EnabledChannels = request.EnabledChannels,
  519. EnableLiveTv = request.EnableLiveTv,
  520. AccessToken = accessToken
  521. });
  522. CacheData();
  523. }
  524. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  525. return result;
  526. }
  527. private async Task<UserLinkResult> SendNewUserInvitation(string fromName, string email)
  528. {
  529. var url = GetConnectUrl("users/invite");
  530. var options = new HttpRequestOptions
  531. {
  532. Url = url,
  533. CancellationToken = CancellationToken.None
  534. };
  535. var postData = new Dictionary<string, string>
  536. {
  537. {"email", email},
  538. {"requesterUserName", fromName}
  539. };
  540. options.SetPostData(postData);
  541. SetApplicationHeader(options);
  542. // No need to examine the response
  543. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  544. {
  545. }
  546. return new UserLinkResult
  547. {
  548. IsNewUserInvitation = true,
  549. GuestDisplayName = email
  550. };
  551. }
  552. public Task RemoveConnect(string userId)
  553. {
  554. var user = GetUser(userId);
  555. return RemoveConnect(user, user.ConnectUserId);
  556. }
  557. private async Task RemoveConnect(User user, string connectUserId)
  558. {
  559. if (!string.IsNullOrWhiteSpace(connectUserId))
  560. {
  561. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  562. }
  563. user.ConnectAccessKey = null;
  564. user.ConnectUserName = null;
  565. user.ConnectUserId = null;
  566. user.ConnectLinkType = null;
  567. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  568. }
  569. private async Task<ConnectUser> GetConnectUser(ConnectUserQuery query, CancellationToken cancellationToken)
  570. {
  571. var url = GetConnectUrl("user");
  572. if (!string.IsNullOrWhiteSpace(query.Id))
  573. {
  574. url = url + "?id=" + WebUtility.UrlEncode(query.Id);
  575. }
  576. else if (!string.IsNullOrWhiteSpace(query.NameOrEmail))
  577. {
  578. url = url + "?nameOrEmail=" + WebUtility.UrlEncode(query.NameOrEmail);
  579. }
  580. else if (!string.IsNullOrWhiteSpace(query.Name))
  581. {
  582. url = url + "?name=" + WebUtility.UrlEncode(query.Name);
  583. }
  584. else if (!string.IsNullOrWhiteSpace(query.Email))
  585. {
  586. url = url + "?name=" + WebUtility.UrlEncode(query.Email);
  587. }
  588. else
  589. {
  590. throw new ArgumentException("Empty ConnectUserQuery supplied");
  591. }
  592. var options = new HttpRequestOptions
  593. {
  594. CancellationToken = cancellationToken,
  595. Url = url
  596. };
  597. SetServerAccessToken(options);
  598. SetApplicationHeader(options);
  599. using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
  600. {
  601. var response = _json.DeserializeFromStream<GetConnectUserResponse>(stream);
  602. return new ConnectUser
  603. {
  604. Email = response.Email,
  605. Id = response.Id,
  606. Name = response.Name,
  607. IsActive = response.IsActive,
  608. ImageUrl = response.ImageUrl
  609. };
  610. }
  611. }
  612. private void SetApplicationHeader(HttpRequestOptions options)
  613. {
  614. options.RequestHeaders.Add("X-Application", XApplicationValue);
  615. }
  616. private void SetServerAccessToken(HttpRequestOptions options)
  617. {
  618. if (string.IsNullOrWhiteSpace(ConnectAccessKey))
  619. {
  620. throw new ArgumentNullException("ConnectAccessKey");
  621. }
  622. options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey);
  623. }
  624. public async Task RefreshAuthorizations(CancellationToken cancellationToken)
  625. {
  626. await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  627. try
  628. {
  629. await RefreshAuthorizationsInternal(true, cancellationToken).ConfigureAwait(false);
  630. }
  631. finally
  632. {
  633. _operationLock.Release();
  634. }
  635. }
  636. private async Task RefreshAuthorizationsInternal(bool refreshImages, CancellationToken cancellationToken)
  637. {
  638. if (string.IsNullOrWhiteSpace(ConnectServerId))
  639. {
  640. throw new ArgumentNullException("ConnectServerId");
  641. }
  642. var url = GetConnectUrl("ServerAuthorizations");
  643. url += "?serverId=" + ConnectServerId;
  644. var options = new HttpRequestOptions
  645. {
  646. Url = url,
  647. CancellationToken = cancellationToken
  648. };
  649. SetServerAccessToken(options);
  650. SetApplicationHeader(options);
  651. try
  652. {
  653. using (var stream = (await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)).Content)
  654. {
  655. var list = _json.DeserializeFromStream<List<ServerUserAuthorizationResponse>>(stream);
  656. await RefreshAuthorizations(list, refreshImages).ConfigureAwait(false);
  657. }
  658. }
  659. catch (Exception ex)
  660. {
  661. _logger.ErrorException("Error refreshing server authorizations.", ex);
  662. }
  663. }
  664. private readonly SemaphoreSlim _connectImageSemaphore = new SemaphoreSlim(5, 5);
  665. private async Task RefreshAuthorizations(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  666. {
  667. var users = _userManager.Users.ToList();
  668. // Handle existing authorizations that were removed by the Connect server
  669. // Handle existing authorizations whose status may have been updated
  670. foreach (var user in users)
  671. {
  672. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  673. {
  674. var connectEntry = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.OrdinalIgnoreCase));
  675. if (connectEntry == null)
  676. {
  677. var deleteUser = user.ConnectLinkType.HasValue &&
  678. user.ConnectLinkType.Value == UserLinkType.Guest;
  679. user.ConnectUserId = null;
  680. user.ConnectAccessKey = null;
  681. user.ConnectUserName = null;
  682. user.ConnectLinkType = null;
  683. await _userManager.UpdateUser(user).ConfigureAwait(false);
  684. if (deleteUser)
  685. {
  686. _logger.Debug("Deleting guest user {0}", user.Name);
  687. await _userManager.DeleteUser(user).ConfigureAwait(false);
  688. }
  689. }
  690. else
  691. {
  692. var changed = !string.Equals(user.ConnectAccessKey, connectEntry.AccessToken, StringComparison.OrdinalIgnoreCase);
  693. if (changed)
  694. {
  695. user.ConnectUserId = connectEntry.UserId;
  696. user.ConnectAccessKey = connectEntry.AccessToken;
  697. await _userManager.UpdateUser(user).ConfigureAwait(false);
  698. }
  699. }
  700. }
  701. }
  702. var currentPendingList = _data.PendingAuthorizations.ToList();
  703. var newPendingList = new List<ConnectAuthorizationInternal>();
  704. foreach (var connectEntry in list)
  705. {
  706. if (string.Equals(connectEntry.UserType, "guest", StringComparison.OrdinalIgnoreCase))
  707. {
  708. var currentPendingEntry = currentPendingList.FirstOrDefault(i => string.Equals(i.Id, connectEntry.Id, StringComparison.OrdinalIgnoreCase));
  709. if (string.Equals(connectEntry.AcceptStatus, "accepted", StringComparison.OrdinalIgnoreCase))
  710. {
  711. var user = _userManager.Users
  712. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectEntry.UserId, StringComparison.OrdinalIgnoreCase));
  713. if (user == null)
  714. {
  715. // Add user
  716. user = await _userManager.CreateUser(_userManager.MakeValidUsername(connectEntry.UserName)).ConfigureAwait(false);
  717. user.ConnectUserName = connectEntry.UserName;
  718. user.ConnectUserId = connectEntry.UserId;
  719. user.ConnectLinkType = UserLinkType.Guest;
  720. user.ConnectAccessKey = connectEntry.AccessToken;
  721. await _userManager.UpdateUser(user).ConfigureAwait(false);
  722. user.Policy.IsHidden = true;
  723. user.Policy.EnableLiveTvManagement = false;
  724. user.Policy.EnableContentDeletion = false;
  725. user.Policy.EnableRemoteControlOfOtherUsers = false;
  726. user.Policy.EnableSharedDeviceControl = false;
  727. user.Policy.IsAdministrator = false;
  728. if (currentPendingEntry != null)
  729. {
  730. user.Policy.EnabledFolders = currentPendingEntry.EnabledLibraries;
  731. user.Policy.EnableAllFolders = false;
  732. user.Policy.EnabledChannels = currentPendingEntry.EnabledChannels;
  733. user.Policy.EnableAllChannels = false;
  734. user.Policy.EnableLiveTvAccess = currentPendingEntry.EnableLiveTv;
  735. }
  736. await _userManager.UpdateConfiguration(user.Id.ToString("N"), user.Configuration);
  737. }
  738. }
  739. else if (string.Equals(connectEntry.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase))
  740. {
  741. currentPendingEntry = currentPendingEntry ?? new ConnectAuthorizationInternal();
  742. currentPendingEntry.ConnectUserId = connectEntry.UserId;
  743. currentPendingEntry.ImageUrl = connectEntry.UserImageUrl;
  744. currentPendingEntry.UserName = connectEntry.UserName;
  745. currentPendingEntry.Id = connectEntry.Id;
  746. currentPendingEntry.AccessToken = connectEntry.AccessToken;
  747. newPendingList.Add(currentPendingEntry);
  748. }
  749. }
  750. }
  751. _data.PendingAuthorizations = newPendingList;
  752. CacheData();
  753. await RefreshGuestNames(list, refreshImages).ConfigureAwait(false);
  754. }
  755. private async Task RefreshGuestNames(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  756. {
  757. var users = _userManager.Users
  758. .Where(i => !string.IsNullOrEmpty(i.ConnectUserId) && i.ConnectLinkType.HasValue && i.ConnectLinkType.Value == UserLinkType.Guest)
  759. .ToList();
  760. foreach (var user in users)
  761. {
  762. var authorization = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.Ordinal));
  763. if (authorization == null)
  764. {
  765. _logger.Warn("Unable to find connect authorization record for user {0}", user.Name);
  766. continue;
  767. }
  768. var syncConnectName = true;
  769. var syncConnectImage = true;
  770. if (syncConnectName)
  771. {
  772. var changed = !string.Equals(authorization.UserName, user.Name, StringComparison.OrdinalIgnoreCase);
  773. if (changed)
  774. {
  775. await user.Rename(authorization.UserName).ConfigureAwait(false);
  776. }
  777. }
  778. if (syncConnectImage)
  779. {
  780. var imageUrl = authorization.UserImageUrl;
  781. if (!string.IsNullOrWhiteSpace(imageUrl))
  782. {
  783. var changed = false;
  784. if (!user.HasImage(ImageType.Primary))
  785. {
  786. changed = true;
  787. }
  788. else if (refreshImages)
  789. {
  790. using (var response = await _httpClient.SendAsync(new HttpRequestOptions
  791. {
  792. Url = imageUrl,
  793. BufferContent = false
  794. }, "HEAD").ConfigureAwait(false))
  795. {
  796. var length = response.ContentLength;
  797. if (length != _fileSystem.GetFileInfo(user.GetImageInfo(ImageType.Primary, 0).Path).Length)
  798. {
  799. changed = true;
  800. }
  801. }
  802. }
  803. if (changed)
  804. {
  805. await _providerManager.SaveImage(user, imageUrl, _connectImageSemaphore, ImageType.Primary, null, CancellationToken.None).ConfigureAwait(false);
  806. await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem)
  807. {
  808. ForceSave = true,
  809. }, CancellationToken.None).ConfigureAwait(false);
  810. }
  811. }
  812. }
  813. }
  814. }
  815. public async Task<List<ConnectAuthorization>> GetPendingGuests()
  816. {
  817. var time = DateTime.UtcNow - _data.LastAuthorizationsRefresh;
  818. if (time.TotalMinutes >= 5)
  819. {
  820. await _operationLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  821. try
  822. {
  823. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  824. _data.LastAuthorizationsRefresh = DateTime.UtcNow;
  825. CacheData();
  826. }
  827. catch (Exception ex)
  828. {
  829. _logger.ErrorException("Error refreshing authorization", ex);
  830. }
  831. finally
  832. {
  833. _operationLock.Release();
  834. }
  835. }
  836. return _data.PendingAuthorizations.Select(i => new ConnectAuthorization
  837. {
  838. ConnectUserId = i.ConnectUserId,
  839. EnableLiveTv = i.EnableLiveTv,
  840. EnabledChannels = i.EnabledChannels,
  841. EnabledLibraries = i.EnabledLibraries,
  842. Id = i.Id,
  843. ImageUrl = i.ImageUrl,
  844. UserName = i.UserName
  845. }).ToList();
  846. }
  847. public async Task CancelAuthorization(string id)
  848. {
  849. await _operationLock.WaitAsync().ConfigureAwait(false);
  850. try
  851. {
  852. await CancelAuthorizationInternal(id).ConfigureAwait(false);
  853. }
  854. finally
  855. {
  856. _operationLock.Release();
  857. }
  858. }
  859. private async Task CancelAuthorizationInternal(string id)
  860. {
  861. var connectUserId = _data.PendingAuthorizations
  862. .First(i => string.Equals(i.Id, id, StringComparison.Ordinal))
  863. .ConnectUserId;
  864. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  865. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  866. }
  867. private async Task CancelAuthorizationByConnectUserId(string connectUserId)
  868. {
  869. if (string.IsNullOrWhiteSpace(connectUserId))
  870. {
  871. throw new ArgumentNullException("connectUserId");
  872. }
  873. if (string.IsNullOrWhiteSpace(ConnectServerId))
  874. {
  875. throw new ArgumentNullException("ConnectServerId");
  876. }
  877. var url = GetConnectUrl("ServerAuthorizations");
  878. var options = new HttpRequestOptions
  879. {
  880. Url = url,
  881. CancellationToken = CancellationToken.None
  882. };
  883. var postData = new Dictionary<string, string>
  884. {
  885. {"serverId", ConnectServerId},
  886. {"userId", connectUserId}
  887. };
  888. options.SetPostData(postData);
  889. SetServerAccessToken(options);
  890. SetApplicationHeader(options);
  891. try
  892. {
  893. // No need to examine the response
  894. using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
  895. {
  896. }
  897. }
  898. catch (HttpException ex)
  899. {
  900. // If connect says the auth doesn't exist, we can handle that gracefully since this is a remove operation
  901. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  902. {
  903. throw;
  904. }
  905. _logger.Debug("Connect returned a 404 when removing a user auth link. Handling it.");
  906. }
  907. }
  908. public async Task Authenticate(string username, string passwordMd5)
  909. {
  910. if (string.IsNullOrWhiteSpace(username))
  911. {
  912. throw new ArgumentNullException("username");
  913. }
  914. if (string.IsNullOrWhiteSpace(passwordMd5))
  915. {
  916. throw new ArgumentNullException("passwordMd5");
  917. }
  918. var options = new HttpRequestOptions
  919. {
  920. Url = GetConnectUrl("user/authenticate")
  921. };
  922. options.SetPostData(new Dictionary<string, string>
  923. {
  924. {"userName",username},
  925. {"password",passwordMd5}
  926. });
  927. SetApplicationHeader(options);
  928. // No need to examine the response
  929. using (var response = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
  930. {
  931. }
  932. }
  933. public async Task<User> GetLocalUser(string connectUserId)
  934. {
  935. var user = _userManager.Users
  936. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUserId, StringComparison.OrdinalIgnoreCase));
  937. if (user == null)
  938. {
  939. await RefreshAuthorizations(CancellationToken.None).ConfigureAwait(false);
  940. }
  941. return _userManager.Users
  942. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUserId, StringComparison.OrdinalIgnoreCase));
  943. }
  944. public User GetUserFromExchangeToken(string token)
  945. {
  946. if (string.IsNullOrWhiteSpace(token))
  947. {
  948. throw new ArgumentNullException("token");
  949. }
  950. return _userManager.Users.FirstOrDefault(u => string.Equals(token, u.ConnectAccessKey, StringComparison.OrdinalIgnoreCase));
  951. }
  952. public bool IsAuthorizationTokenValid(string token)
  953. {
  954. if (string.IsNullOrWhiteSpace(token))
  955. {
  956. throw new ArgumentNullException("token");
  957. }
  958. return _userManager.Users.Any(u => string.Equals(token, u.ConnectAccessKey, StringComparison.OrdinalIgnoreCase)) ||
  959. _data.PendingAuthorizations.Select(i => i.AccessToken).Contains(token, StringComparer.OrdinalIgnoreCase);
  960. }
  961. }
  962. }