ConnectManager.cs 43 KB

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