ConnectManager.cs 41 KB

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