ConnectManager.cs 41 KB

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