ConnectManager.cs 43 KB

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