ConnectManager.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  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 || ex.IsTimedOut)
  469. {
  470. throw new Exception("Unable to invite guest, " + ex.Message, ex);
  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 async Task RefreshAuthorizations(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  671. {
  672. var users = _userManager.Users.ToList();
  673. // Handle existing authorizations that were removed by the Connect server
  674. // Handle existing authorizations whose status may have been updated
  675. foreach (var user in users)
  676. {
  677. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  678. {
  679. var connectEntry = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.OrdinalIgnoreCase));
  680. if (connectEntry == null)
  681. {
  682. var deleteUser = user.ConnectLinkType.HasValue &&
  683. user.ConnectLinkType.Value == UserLinkType.Guest;
  684. user.ConnectUserId = null;
  685. user.ConnectAccessKey = null;
  686. user.ConnectUserName = null;
  687. user.ConnectLinkType = null;
  688. await _userManager.UpdateUser(user).ConfigureAwait(false);
  689. if (deleteUser)
  690. {
  691. _logger.Debug("Deleting guest user {0}", user.Name);
  692. await _userManager.DeleteUser(user).ConfigureAwait(false);
  693. }
  694. }
  695. else
  696. {
  697. var changed = !string.Equals(user.ConnectAccessKey, connectEntry.AccessToken, StringComparison.OrdinalIgnoreCase);
  698. if (changed)
  699. {
  700. user.ConnectUserId = connectEntry.UserId;
  701. user.ConnectAccessKey = connectEntry.AccessToken;
  702. await _userManager.UpdateUser(user).ConfigureAwait(false);
  703. }
  704. }
  705. }
  706. }
  707. var currentPendingList = _data.PendingAuthorizations.ToList();
  708. var newPendingList = new List<ConnectAuthorizationInternal>();
  709. foreach (var connectEntry in list)
  710. {
  711. if (string.Equals(connectEntry.UserType, "guest", StringComparison.OrdinalIgnoreCase))
  712. {
  713. var currentPendingEntry = currentPendingList.FirstOrDefault(i => string.Equals(i.Id, connectEntry.Id, StringComparison.OrdinalIgnoreCase));
  714. if (string.Equals(connectEntry.AcceptStatus, "accepted", StringComparison.OrdinalIgnoreCase))
  715. {
  716. var user = _userManager.Users
  717. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectEntry.UserId, StringComparison.OrdinalIgnoreCase));
  718. if (user == null)
  719. {
  720. // Add user
  721. user = await _userManager.CreateUser(_userManager.MakeValidUsername(connectEntry.UserName)).ConfigureAwait(false);
  722. user.ConnectUserName = connectEntry.UserName;
  723. user.ConnectUserId = connectEntry.UserId;
  724. user.ConnectLinkType = UserLinkType.Guest;
  725. user.ConnectAccessKey = connectEntry.AccessToken;
  726. await _userManager.UpdateUser(user).ConfigureAwait(false);
  727. user.Policy.IsHidden = true;
  728. user.Policy.EnableLiveTvManagement = false;
  729. user.Policy.EnableContentDeletion = false;
  730. user.Policy.EnableRemoteControlOfOtherUsers = false;
  731. user.Policy.EnableSharedDeviceControl = false;
  732. user.Policy.IsAdministrator = false;
  733. if (currentPendingEntry != null)
  734. {
  735. user.Policy.EnabledFolders = currentPendingEntry.EnabledLibraries;
  736. user.Policy.EnableAllFolders = false;
  737. user.Policy.EnabledChannels = currentPendingEntry.EnabledChannels;
  738. user.Policy.EnableAllChannels = false;
  739. user.Policy.EnableLiveTvAccess = currentPendingEntry.EnableLiveTv;
  740. }
  741. await _userManager.UpdateConfiguration(user.Id.ToString("N"), user.Configuration);
  742. }
  743. }
  744. else if (string.Equals(connectEntry.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase))
  745. {
  746. currentPendingEntry = currentPendingEntry ?? new ConnectAuthorizationInternal();
  747. currentPendingEntry.ConnectUserId = connectEntry.UserId;
  748. currentPendingEntry.ImageUrl = connectEntry.UserImageUrl;
  749. currentPendingEntry.UserName = connectEntry.UserName;
  750. currentPendingEntry.Id = connectEntry.Id;
  751. currentPendingEntry.AccessToken = connectEntry.AccessToken;
  752. newPendingList.Add(currentPendingEntry);
  753. }
  754. }
  755. }
  756. _data.PendingAuthorizations = newPendingList;
  757. CacheData();
  758. await RefreshGuestNames(list, refreshImages).ConfigureAwait(false);
  759. }
  760. private async Task RefreshGuestNames(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  761. {
  762. var users = _userManager.Users
  763. .Where(i => !string.IsNullOrEmpty(i.ConnectUserId) && i.ConnectLinkType.HasValue && i.ConnectLinkType.Value == UserLinkType.Guest)
  764. .ToList();
  765. foreach (var user in users)
  766. {
  767. var authorization = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.Ordinal));
  768. if (authorization == null)
  769. {
  770. _logger.Warn("Unable to find connect authorization record for user {0}", user.Name);
  771. continue;
  772. }
  773. var syncConnectName = true;
  774. var syncConnectImage = true;
  775. if (syncConnectName)
  776. {
  777. var changed = !string.Equals(authorization.UserName, user.Name, StringComparison.OrdinalIgnoreCase);
  778. if (changed)
  779. {
  780. await user.Rename(authorization.UserName).ConfigureAwait(false);
  781. }
  782. }
  783. if (syncConnectImage)
  784. {
  785. var imageUrl = authorization.UserImageUrl;
  786. if (!string.IsNullOrWhiteSpace(imageUrl))
  787. {
  788. var changed = false;
  789. if (!user.HasImage(ImageType.Primary))
  790. {
  791. changed = true;
  792. }
  793. else if (refreshImages)
  794. {
  795. using (var response = await _httpClient.SendAsync(new HttpRequestOptions
  796. {
  797. Url = imageUrl,
  798. BufferContent = false
  799. }, "HEAD").ConfigureAwait(false))
  800. {
  801. var length = response.ContentLength;
  802. if (length != _fileSystem.GetFileInfo(user.GetImageInfo(ImageType.Primary, 0).Path).Length)
  803. {
  804. changed = true;
  805. }
  806. }
  807. }
  808. if (changed)
  809. {
  810. await _providerManager.SaveImage(user, imageUrl, null, ImageType.Primary, null, CancellationToken.None).ConfigureAwait(false);
  811. await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem)
  812. {
  813. ForceSave = true,
  814. }, CancellationToken.None).ConfigureAwait(false);
  815. }
  816. }
  817. }
  818. }
  819. }
  820. public async Task<List<ConnectAuthorization>> GetPendingGuests()
  821. {
  822. var time = DateTime.UtcNow - _data.LastAuthorizationsRefresh;
  823. if (time.TotalMinutes >= 5)
  824. {
  825. await _operationLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  826. try
  827. {
  828. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  829. _data.LastAuthorizationsRefresh = DateTime.UtcNow;
  830. CacheData();
  831. }
  832. catch (Exception ex)
  833. {
  834. _logger.ErrorException("Error refreshing authorization", ex);
  835. }
  836. finally
  837. {
  838. _operationLock.Release();
  839. }
  840. }
  841. return _data.PendingAuthorizations.Select(i => new ConnectAuthorization
  842. {
  843. ConnectUserId = i.ConnectUserId,
  844. EnableLiveTv = i.EnableLiveTv,
  845. EnabledChannels = i.EnabledChannels,
  846. EnabledLibraries = i.EnabledLibraries,
  847. Id = i.Id,
  848. ImageUrl = i.ImageUrl,
  849. UserName = i.UserName
  850. }).ToList();
  851. }
  852. public async Task CancelAuthorization(string id)
  853. {
  854. await _operationLock.WaitAsync().ConfigureAwait(false);
  855. try
  856. {
  857. await CancelAuthorizationInternal(id).ConfigureAwait(false);
  858. }
  859. finally
  860. {
  861. _operationLock.Release();
  862. }
  863. }
  864. private async Task CancelAuthorizationInternal(string id)
  865. {
  866. var connectUserId = _data.PendingAuthorizations
  867. .First(i => string.Equals(i.Id, id, StringComparison.Ordinal))
  868. .ConnectUserId;
  869. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  870. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  871. }
  872. private async Task CancelAuthorizationByConnectUserId(string connectUserId)
  873. {
  874. if (string.IsNullOrWhiteSpace(connectUserId))
  875. {
  876. throw new ArgumentNullException("connectUserId");
  877. }
  878. if (string.IsNullOrWhiteSpace(ConnectServerId))
  879. {
  880. throw new ArgumentNullException("ConnectServerId");
  881. }
  882. var url = GetConnectUrl("ServerAuthorizations");
  883. var options = new HttpRequestOptions
  884. {
  885. Url = url,
  886. CancellationToken = CancellationToken.None,
  887. BufferContent = false
  888. };
  889. var postData = new Dictionary<string, string>
  890. {
  891. {"serverId", ConnectServerId},
  892. {"userId", connectUserId}
  893. };
  894. options.SetPostData(postData);
  895. SetServerAccessToken(options);
  896. SetApplicationHeader(options);
  897. try
  898. {
  899. // No need to examine the response
  900. using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
  901. {
  902. }
  903. }
  904. catch (HttpException ex)
  905. {
  906. // If connect says the auth doesn't exist, we can handle that gracefully since this is a remove operation
  907. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  908. {
  909. throw;
  910. }
  911. _logger.Debug("Connect returned a 404 when removing a user auth link. Handling it.");
  912. }
  913. }
  914. public async Task Authenticate(string username, string passwordMd5)
  915. {
  916. if (string.IsNullOrWhiteSpace(username))
  917. {
  918. throw new ArgumentNullException("username");
  919. }
  920. if (string.IsNullOrWhiteSpace(passwordMd5))
  921. {
  922. throw new ArgumentNullException("passwordMd5");
  923. }
  924. var options = new HttpRequestOptions
  925. {
  926. Url = GetConnectUrl("user/authenticate"),
  927. BufferContent = false
  928. };
  929. options.SetPostData(new Dictionary<string, string>
  930. {
  931. {"userName",username},
  932. {"password",passwordMd5}
  933. });
  934. SetApplicationHeader(options);
  935. // No need to examine the response
  936. using (var response = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
  937. {
  938. }
  939. }
  940. public async Task<User> GetLocalUser(string connectUserId)
  941. {
  942. var user = _userManager.Users
  943. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUserId, StringComparison.OrdinalIgnoreCase));
  944. if (user == null)
  945. {
  946. await RefreshAuthorizations(CancellationToken.None).ConfigureAwait(false);
  947. }
  948. return _userManager.Users
  949. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUserId, StringComparison.OrdinalIgnoreCase));
  950. }
  951. public User GetUserFromExchangeToken(string token)
  952. {
  953. if (string.IsNullOrWhiteSpace(token))
  954. {
  955. throw new ArgumentNullException("token");
  956. }
  957. return _userManager.Users.FirstOrDefault(u => string.Equals(token, u.ConnectAccessKey, StringComparison.OrdinalIgnoreCase));
  958. }
  959. public bool IsAuthorizationTokenValid(string token)
  960. {
  961. if (string.IsNullOrWhiteSpace(token))
  962. {
  963. throw new ArgumentNullException("token");
  964. }
  965. return _userManager.Users.Any(u => string.Equals(token, u.ConnectAccessKey, StringComparison.OrdinalIgnoreCase)) ||
  966. _data.PendingAuthorizations.Select(i => i.AccessToken).Contains(token, StringComparer.OrdinalIgnoreCase);
  967. }
  968. }
  969. }