ConnectManager.cs 41 KB

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