ConnectManager.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  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 void 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. throw new ArgumentNullException("ConnectServerId");
  335. }
  336. var connectUser = await GetConnectUser(new ConnectUserQuery
  337. {
  338. NameOrEmail = connectUsername
  339. }, CancellationToken.None).ConfigureAwait(false);
  340. if (!connectUser.IsActive)
  341. {
  342. throw new ArgumentException("The Emby account has been disabled.");
  343. }
  344. var user = GetUser(userId);
  345. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  346. {
  347. await RemoveConnect(user, connectUser.Id).ConfigureAwait(false);
  348. }
  349. var url = GetConnectUrl("ServerAuthorizations");
  350. var options = new HttpRequestOptions
  351. {
  352. Url = url,
  353. CancellationToken = CancellationToken.None
  354. };
  355. var accessToken = Guid.NewGuid().ToString("N");
  356. var postData = new Dictionary<string, string>
  357. {
  358. {"serverId", ConnectServerId},
  359. {"userId", connectUser.Id},
  360. {"userType", "Linked"},
  361. {"accessToken", accessToken}
  362. };
  363. options.SetPostData(postData);
  364. SetServerAccessToken(options);
  365. SetApplicationHeader(options);
  366. var result = new UserLinkResult();
  367. // No need to examine the response
  368. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  369. {
  370. var response = _json.DeserializeFromStream<ServerUserAuthorizationResponse>(stream);
  371. result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase);
  372. }
  373. user.ConnectAccessKey = accessToken;
  374. user.ConnectUserName = connectUser.Name;
  375. user.ConnectUserId = connectUser.Id;
  376. user.ConnectLinkType = UserLinkType.LinkedUser;
  377. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  378. await _userManager.UpdateConfiguration(user.Id.ToString("N"), user.Configuration);
  379. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  380. return result;
  381. }
  382. public async Task<UserLinkResult> InviteUser(ConnectAuthorizationRequest request)
  383. {
  384. await _operationLock.WaitAsync().ConfigureAwait(false);
  385. try
  386. {
  387. return await InviteUserInternal(request).ConfigureAwait(false);
  388. }
  389. finally
  390. {
  391. _operationLock.Release();
  392. }
  393. }
  394. private async Task<UserLinkResult> InviteUserInternal(ConnectAuthorizationRequest request)
  395. {
  396. var connectUsername = request.ConnectUserName;
  397. var sendingUserId = request.SendingUserId;
  398. if (string.IsNullOrWhiteSpace(connectUsername))
  399. {
  400. throw new ArgumentNullException("connectUsername");
  401. }
  402. if (string.IsNullOrWhiteSpace(ConnectServerId))
  403. {
  404. throw new ArgumentNullException("ConnectServerId");
  405. }
  406. var sendingUser = GetUser(sendingUserId);
  407. var requesterUserName = sendingUser.ConnectUserName;
  408. if (string.IsNullOrWhiteSpace(requesterUserName))
  409. {
  410. throw new ArgumentException("A Connect account is required in order to send invitations.");
  411. }
  412. string connectUserId = null;
  413. var result = new UserLinkResult();
  414. try
  415. {
  416. var connectUser = await GetConnectUser(new ConnectUserQuery
  417. {
  418. NameOrEmail = connectUsername
  419. }, CancellationToken.None).ConfigureAwait(false);
  420. if (!connectUser.IsActive)
  421. {
  422. throw new ArgumentException("The Emby account has been disabled.");
  423. }
  424. connectUserId = connectUser.Id;
  425. result.GuestDisplayName = connectUser.Name;
  426. }
  427. catch (HttpException ex)
  428. {
  429. if (!ex.StatusCode.HasValue ||
  430. ex.StatusCode.Value != HttpStatusCode.NotFound ||
  431. !Validator.EmailIsValid(connectUsername))
  432. {
  433. throw;
  434. }
  435. }
  436. if (string.IsNullOrWhiteSpace(connectUserId))
  437. {
  438. return await SendNewUserInvitation(requesterUserName, connectUsername).ConfigureAwait(false);
  439. }
  440. var url = GetConnectUrl("ServerAuthorizations");
  441. var options = new HttpRequestOptions
  442. {
  443. Url = url,
  444. CancellationToken = CancellationToken.None
  445. };
  446. var accessToken = Guid.NewGuid().ToString("N");
  447. var postData = new Dictionary<string, string>
  448. {
  449. {"serverId", ConnectServerId},
  450. {"userId", connectUserId},
  451. {"userType", "Guest"},
  452. {"accessToken", accessToken},
  453. {"requesterUserName", requesterUserName}
  454. };
  455. options.SetPostData(postData);
  456. SetServerAccessToken(options);
  457. SetApplicationHeader(options);
  458. // No need to examine the response
  459. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  460. {
  461. var response = _json.DeserializeFromStream<ServerUserAuthorizationResponse>(stream);
  462. result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase);
  463. _data.PendingAuthorizations.Add(new ConnectAuthorizationInternal
  464. {
  465. ConnectUserId = response.UserId,
  466. Id = response.Id,
  467. ImageUrl = response.UserImageUrl,
  468. UserName = response.UserName,
  469. EnabledLibraries = request.EnabledLibraries,
  470. EnabledChannels = request.EnabledChannels,
  471. EnableLiveTv = request.EnableLiveTv,
  472. AccessToken = accessToken
  473. });
  474. CacheData();
  475. }
  476. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  477. return result;
  478. }
  479. private async Task<UserLinkResult> SendNewUserInvitation(string fromName, string email)
  480. {
  481. var url = GetConnectUrl("users/invite");
  482. var options = new HttpRequestOptions
  483. {
  484. Url = url,
  485. CancellationToken = CancellationToken.None
  486. };
  487. var postData = new Dictionary<string, string>
  488. {
  489. {"email", email},
  490. {"requesterUserName", fromName}
  491. };
  492. options.SetPostData(postData);
  493. SetApplicationHeader(options);
  494. // No need to examine the response
  495. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  496. {
  497. }
  498. return new UserLinkResult
  499. {
  500. IsNewUserInvitation = true,
  501. GuestDisplayName = email
  502. };
  503. }
  504. public Task RemoveConnect(string userId)
  505. {
  506. var user = GetUser(userId);
  507. return RemoveConnect(user, user.ConnectUserId);
  508. }
  509. private async Task RemoveConnect(User user, string connectUserId)
  510. {
  511. if (!string.IsNullOrWhiteSpace(connectUserId))
  512. {
  513. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  514. }
  515. user.ConnectAccessKey = null;
  516. user.ConnectUserName = null;
  517. user.ConnectUserId = null;
  518. user.ConnectLinkType = null;
  519. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  520. }
  521. private async Task<ConnectUser> GetConnectUser(ConnectUserQuery query, CancellationToken cancellationToken)
  522. {
  523. var url = GetConnectUrl("user");
  524. if (!string.IsNullOrWhiteSpace(query.Id))
  525. {
  526. url = url + "?id=" + WebUtility.UrlEncode(query.Id);
  527. }
  528. else if (!string.IsNullOrWhiteSpace(query.NameOrEmail))
  529. {
  530. url = url + "?nameOrEmail=" + WebUtility.UrlEncode(query.NameOrEmail);
  531. }
  532. else if (!string.IsNullOrWhiteSpace(query.Name))
  533. {
  534. url = url + "?name=" + WebUtility.UrlEncode(query.Name);
  535. }
  536. else if (!string.IsNullOrWhiteSpace(query.Email))
  537. {
  538. url = url + "?name=" + WebUtility.UrlEncode(query.Email);
  539. }
  540. else
  541. {
  542. throw new ArgumentException("Empty ConnectUserQuery supplied");
  543. }
  544. var options = new HttpRequestOptions
  545. {
  546. CancellationToken = cancellationToken,
  547. Url = url
  548. };
  549. SetServerAccessToken(options);
  550. SetApplicationHeader(options);
  551. using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
  552. {
  553. var response = _json.DeserializeFromStream<GetConnectUserResponse>(stream);
  554. return new ConnectUser
  555. {
  556. Email = response.Email,
  557. Id = response.Id,
  558. Name = response.Name,
  559. IsActive = response.IsActive,
  560. ImageUrl = response.ImageUrl
  561. };
  562. }
  563. }
  564. private void SetApplicationHeader(HttpRequestOptions options)
  565. {
  566. options.RequestHeaders.Add("X-Application", XApplicationValue);
  567. }
  568. private void SetServerAccessToken(HttpRequestOptions options)
  569. {
  570. if (string.IsNullOrWhiteSpace(ConnectAccessKey))
  571. {
  572. throw new ArgumentNullException("ConnectAccessKey");
  573. }
  574. options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey);
  575. }
  576. public async Task RefreshAuthorizations(CancellationToken cancellationToken)
  577. {
  578. await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  579. try
  580. {
  581. await RefreshAuthorizationsInternal(true, cancellationToken).ConfigureAwait(false);
  582. }
  583. finally
  584. {
  585. _operationLock.Release();
  586. }
  587. }
  588. private async Task RefreshAuthorizationsInternal(bool refreshImages, CancellationToken cancellationToken)
  589. {
  590. if (string.IsNullOrWhiteSpace(ConnectServerId))
  591. {
  592. throw new ArgumentNullException("ConnectServerId");
  593. }
  594. var url = GetConnectUrl("ServerAuthorizations");
  595. url += "?serverId=" + ConnectServerId;
  596. var options = new HttpRequestOptions
  597. {
  598. Url = url,
  599. CancellationToken = cancellationToken
  600. };
  601. SetServerAccessToken(options);
  602. SetApplicationHeader(options);
  603. try
  604. {
  605. using (var stream = (await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)).Content)
  606. {
  607. var list = _json.DeserializeFromStream<List<ServerUserAuthorizationResponse>>(stream);
  608. await RefreshAuthorizations(list, refreshImages).ConfigureAwait(false);
  609. }
  610. }
  611. catch (Exception ex)
  612. {
  613. _logger.ErrorException("Error refreshing server authorizations.", ex);
  614. }
  615. }
  616. private readonly SemaphoreSlim _connectImageSemaphore = new SemaphoreSlim(5, 5);
  617. private async Task RefreshAuthorizations(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  618. {
  619. var users = _userManager.Users.ToList();
  620. // Handle existing authorizations that were removed by the Connect server
  621. // Handle existing authorizations whose status may have been updated
  622. foreach (var user in users)
  623. {
  624. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  625. {
  626. var connectEntry = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.OrdinalIgnoreCase));
  627. if (connectEntry == null)
  628. {
  629. var deleteUser = user.ConnectLinkType.HasValue &&
  630. user.ConnectLinkType.Value == UserLinkType.Guest;
  631. user.ConnectUserId = null;
  632. user.ConnectAccessKey = null;
  633. user.ConnectUserName = null;
  634. user.ConnectLinkType = null;
  635. await _userManager.UpdateUser(user).ConfigureAwait(false);
  636. if (deleteUser)
  637. {
  638. _logger.Debug("Deleting guest user {0}", user.Name);
  639. await _userManager.DeleteUser(user).ConfigureAwait(false);
  640. }
  641. }
  642. else
  643. {
  644. var changed = !string.Equals(user.ConnectAccessKey, connectEntry.AccessToken, StringComparison.OrdinalIgnoreCase);
  645. if (changed)
  646. {
  647. user.ConnectUserId = connectEntry.UserId;
  648. user.ConnectAccessKey = connectEntry.AccessToken;
  649. await _userManager.UpdateUser(user).ConfigureAwait(false);
  650. }
  651. }
  652. }
  653. }
  654. var currentPendingList = _data.PendingAuthorizations.ToList();
  655. var newPendingList = new List<ConnectAuthorizationInternal>();
  656. foreach (var connectEntry in list)
  657. {
  658. if (string.Equals(connectEntry.UserType, "guest", StringComparison.OrdinalIgnoreCase))
  659. {
  660. var currentPendingEntry = currentPendingList.FirstOrDefault(i => string.Equals(i.Id, connectEntry.Id, StringComparison.OrdinalIgnoreCase));
  661. if (string.Equals(connectEntry.AcceptStatus, "accepted", StringComparison.OrdinalIgnoreCase))
  662. {
  663. var user = _userManager.Users
  664. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectEntry.UserId, StringComparison.OrdinalIgnoreCase));
  665. if (user == null)
  666. {
  667. // Add user
  668. user = await _userManager.CreateUser(_userManager.MakeValidUsername(connectEntry.UserName)).ConfigureAwait(false);
  669. user.ConnectUserName = connectEntry.UserName;
  670. user.ConnectUserId = connectEntry.UserId;
  671. user.ConnectLinkType = UserLinkType.Guest;
  672. user.ConnectAccessKey = connectEntry.AccessToken;
  673. await _userManager.UpdateUser(user).ConfigureAwait(false);
  674. user.Policy.IsHidden = true;
  675. user.Policy.EnableLiveTvManagement = false;
  676. user.Policy.EnableContentDeletion = false;
  677. user.Policy.EnableRemoteControlOfOtherUsers = false;
  678. user.Policy.EnableSharedDeviceControl = false;
  679. user.Policy.IsAdministrator = false;
  680. if (currentPendingEntry != null)
  681. {
  682. user.Policy.EnabledFolders = currentPendingEntry.EnabledLibraries;
  683. user.Policy.EnableAllFolders = false;
  684. user.Policy.EnabledChannels = currentPendingEntry.EnabledChannels;
  685. user.Policy.EnableAllChannels = false;
  686. user.Policy.EnableLiveTvAccess = currentPendingEntry.EnableLiveTv;
  687. }
  688. await _userManager.UpdateConfiguration(user.Id.ToString("N"), user.Configuration);
  689. }
  690. }
  691. else if (string.Equals(connectEntry.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase))
  692. {
  693. currentPendingEntry = currentPendingEntry ?? new ConnectAuthorizationInternal();
  694. currentPendingEntry.ConnectUserId = connectEntry.UserId;
  695. currentPendingEntry.ImageUrl = connectEntry.UserImageUrl;
  696. currentPendingEntry.UserName = connectEntry.UserName;
  697. currentPendingEntry.Id = connectEntry.Id;
  698. currentPendingEntry.AccessToken = connectEntry.AccessToken;
  699. newPendingList.Add(currentPendingEntry);
  700. }
  701. }
  702. }
  703. _data.PendingAuthorizations = newPendingList;
  704. CacheData();
  705. await RefreshGuestNames(list, refreshImages).ConfigureAwait(false);
  706. }
  707. private async Task RefreshGuestNames(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  708. {
  709. var users = _userManager.Users
  710. .Where(i => !string.IsNullOrEmpty(i.ConnectUserId) &&
  711. (i.ConnectLinkType.HasValue && i.ConnectLinkType.Value == UserLinkType.Guest))
  712. .ToList();
  713. foreach (var user in users)
  714. {
  715. var authorization = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.Ordinal));
  716. if (authorization == null)
  717. {
  718. _logger.Warn("Unable to find connect authorization record for user {0}", user.Name);
  719. continue;
  720. }
  721. var syncConnectName = true;
  722. var syncConnectImage = true;
  723. if (syncConnectName)
  724. {
  725. var changed = !string.Equals(authorization.UserName, user.Name, StringComparison.OrdinalIgnoreCase);
  726. if (changed)
  727. {
  728. await user.Rename(authorization.UserName).ConfigureAwait(false);
  729. }
  730. }
  731. if (syncConnectImage)
  732. {
  733. var imageUrl = authorization.UserImageUrl;
  734. if (!string.IsNullOrWhiteSpace(imageUrl))
  735. {
  736. var changed = false;
  737. if (!user.HasImage(ImageType.Primary))
  738. {
  739. changed = true;
  740. }
  741. else if (refreshImages)
  742. {
  743. using (var response = await _httpClient.SendAsync(new HttpRequestOptions
  744. {
  745. Url = imageUrl,
  746. BufferContent = false
  747. }, "HEAD").ConfigureAwait(false))
  748. {
  749. var length = response.ContentLength;
  750. if (length != new FileInfo(user.GetImageInfo(ImageType.Primary, 0).Path).Length)
  751. {
  752. changed = true;
  753. }
  754. }
  755. }
  756. if (changed)
  757. {
  758. await _providerManager.SaveImage(user, imageUrl, _connectImageSemaphore, ImageType.Primary, null, CancellationToken.None).ConfigureAwait(false);
  759. await user.RefreshMetadata(new MetadataRefreshOptions
  760. {
  761. ForceSave = true,
  762. }, CancellationToken.None).ConfigureAwait(false);
  763. }
  764. }
  765. }
  766. }
  767. }
  768. public async Task<List<ConnectAuthorization>> GetPendingGuests()
  769. {
  770. var time = DateTime.UtcNow - _data.LastAuthorizationsRefresh;
  771. if (time.TotalMinutes >= 5)
  772. {
  773. await _operationLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  774. try
  775. {
  776. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  777. _data.LastAuthorizationsRefresh = DateTime.UtcNow;
  778. CacheData();
  779. }
  780. catch (Exception ex)
  781. {
  782. _logger.ErrorException("Error refreshing authorization", ex);
  783. }
  784. finally
  785. {
  786. _operationLock.Release();
  787. }
  788. }
  789. return _data.PendingAuthorizations.Select(i => new ConnectAuthorization
  790. {
  791. ConnectUserId = i.ConnectUserId,
  792. EnableLiveTv = i.EnableLiveTv,
  793. EnabledChannels = i.EnabledChannels,
  794. EnabledLibraries = i.EnabledLibraries,
  795. Id = i.Id,
  796. ImageUrl = i.ImageUrl,
  797. UserName = i.UserName
  798. }).ToList();
  799. }
  800. public async Task CancelAuthorization(string id)
  801. {
  802. await _operationLock.WaitAsync().ConfigureAwait(false);
  803. try
  804. {
  805. await CancelAuthorizationInternal(id).ConfigureAwait(false);
  806. }
  807. finally
  808. {
  809. _operationLock.Release();
  810. }
  811. }
  812. private async Task CancelAuthorizationInternal(string id)
  813. {
  814. var connectUserId = _data.PendingAuthorizations
  815. .First(i => string.Equals(i.Id, id, StringComparison.Ordinal))
  816. .ConnectUserId;
  817. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  818. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  819. }
  820. private async Task CancelAuthorizationByConnectUserId(string connectUserId)
  821. {
  822. if (string.IsNullOrWhiteSpace(connectUserId))
  823. {
  824. throw new ArgumentNullException("connectUserId");
  825. }
  826. if (string.IsNullOrWhiteSpace(ConnectServerId))
  827. {
  828. throw new ArgumentNullException("ConnectServerId");
  829. }
  830. var url = GetConnectUrl("ServerAuthorizations");
  831. var options = new HttpRequestOptions
  832. {
  833. Url = url,
  834. CancellationToken = CancellationToken.None
  835. };
  836. var postData = new Dictionary<string, string>
  837. {
  838. {"serverId", ConnectServerId},
  839. {"userId", connectUserId}
  840. };
  841. options.SetPostData(postData);
  842. SetServerAccessToken(options);
  843. SetApplicationHeader(options);
  844. try
  845. {
  846. // No need to examine the response
  847. using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
  848. {
  849. }
  850. }
  851. catch (HttpException ex)
  852. {
  853. // If connect says the auth doesn't exist, we can handle that gracefully since this is a remove operation
  854. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  855. {
  856. throw;
  857. }
  858. _logger.Debug("Connect returned a 404 when removing a user auth link. Handling it.");
  859. }
  860. }
  861. public async Task<ConnectSupporterSummary> GetConnectSupporterSummary()
  862. {
  863. if (!_securityManager.IsMBSupporter)
  864. {
  865. return new ConnectSupporterSummary();
  866. }
  867. var url = GetConnectUrl("keyAssociation");
  868. url += "?serverId=" + ConnectServerId;
  869. url += "&supporterKey=" + _securityManager.SupporterKey;
  870. var options = new HttpRequestOptions
  871. {
  872. Url = url,
  873. CancellationToken = CancellationToken.None
  874. };
  875. SetServerAccessToken(options);
  876. SetApplicationHeader(options);
  877. // No need to examine the response
  878. using (var stream = (await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)).Content)
  879. {
  880. return _json.DeserializeFromStream<ConnectSupporterSummary>(stream);
  881. }
  882. }
  883. public async Task AddConnectSupporter(string id)
  884. {
  885. if (!_securityManager.IsMBSupporter)
  886. {
  887. throw new InvalidOperationException();
  888. }
  889. var url = GetConnectUrl("keyAssociation");
  890. url += "?serverId=" + ConnectServerId;
  891. url += "&supporterKey=" + _securityManager.SupporterKey;
  892. url += "&userId=" + id;
  893. var options = new HttpRequestOptions
  894. {
  895. Url = url,
  896. CancellationToken = CancellationToken.None
  897. };
  898. SetServerAccessToken(options);
  899. SetApplicationHeader(options);
  900. // No need to examine the response
  901. using (var stream = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
  902. {
  903. }
  904. }
  905. public async Task RemoveConnectSupporter(string id)
  906. {
  907. if (!_securityManager.IsMBSupporter)
  908. {
  909. throw new InvalidOperationException();
  910. }
  911. var url = GetConnectUrl("keyAssociation");
  912. url += "?serverId=" + ConnectServerId;
  913. url += "&supporterKey=" + _securityManager.SupporterKey;
  914. url += "&userId=" + id;
  915. var options = new HttpRequestOptions
  916. {
  917. Url = url,
  918. CancellationToken = CancellationToken.None
  919. };
  920. SetServerAccessToken(options);
  921. SetApplicationHeader(options);
  922. // No need to examine the response
  923. using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
  924. {
  925. }
  926. }
  927. public async Task Authenticate(string username, string passwordMd5)
  928. {
  929. if (string.IsNullOrWhiteSpace(username))
  930. {
  931. throw new ArgumentNullException("username");
  932. }
  933. if (string.IsNullOrWhiteSpace(passwordMd5))
  934. {
  935. throw new ArgumentNullException("passwordMd5");
  936. }
  937. var options = new HttpRequestOptions
  938. {
  939. Url = GetConnectUrl("user/authenticate")
  940. };
  941. options.SetPostData(new Dictionary<string, string>
  942. {
  943. {"userName",username},
  944. {"password",passwordMd5}
  945. });
  946. SetApplicationHeader(options);
  947. // No need to examine the response
  948. using (var response = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
  949. {
  950. }
  951. }
  952. async void _userManager_UserConfigurationUpdated(object sender, GenericEventArgs<User> e)
  953. {
  954. var user = e.Argument;
  955. await TryUploadUserPreferences(user, CancellationToken.None).ConfigureAwait(false);
  956. }
  957. private async Task TryUploadUserPreferences(User user, CancellationToken cancellationToken)
  958. {
  959. if (user == null)
  960. {
  961. throw new ArgumentNullException("user");
  962. }
  963. if (string.IsNullOrEmpty(user.ConnectUserId))
  964. {
  965. return;
  966. }
  967. if (string.IsNullOrEmpty(ConnectAccessKey))
  968. {
  969. return;
  970. }
  971. var url = GetConnectUrl("user/preferences");
  972. url += "?userId=" + user.ConnectUserId;
  973. url += "&key=userpreferences";
  974. var options = new HttpRequestOptions
  975. {
  976. Url = url,
  977. CancellationToken = cancellationToken
  978. };
  979. var postData = new Dictionary<string, string>();
  980. postData["data"] = _json.SerializeToString(ConnectUserPreferences.FromUserConfiguration(user.Configuration));
  981. options.SetPostData(postData);
  982. SetServerAccessToken(options);
  983. SetApplicationHeader(options);
  984. try
  985. {
  986. // No need to examine the response
  987. using (var stream = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
  988. {
  989. }
  990. }
  991. catch (Exception ex)
  992. {
  993. _logger.ErrorException("Error uploading user preferences", ex);
  994. }
  995. }
  996. private async Task DownloadUserPreferences(User user, CancellationToken cancellationToken)
  997. {
  998. }
  999. public async Task<User> GetLocalUser(string connectUserId)
  1000. {
  1001. var user = _userManager.Users
  1002. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUserId, StringComparison.OrdinalIgnoreCase));
  1003. if (user == null)
  1004. {
  1005. await RefreshAuthorizations(CancellationToken.None).ConfigureAwait(false);
  1006. }
  1007. return _userManager.Users
  1008. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUserId, StringComparison.OrdinalIgnoreCase));
  1009. }
  1010. public User GetUserFromExchangeToken(string token)
  1011. {
  1012. if (string.IsNullOrWhiteSpace(token))
  1013. {
  1014. throw new ArgumentNullException("token");
  1015. }
  1016. return _userManager.Users.FirstOrDefault(u => string.Equals(token, u.ConnectAccessKey, StringComparison.OrdinalIgnoreCase));
  1017. }
  1018. public bool IsAuthorizationTokenValid(string token)
  1019. {
  1020. if (string.IsNullOrWhiteSpace(token))
  1021. {
  1022. throw new ArgumentNullException("token");
  1023. }
  1024. return _userManager.Users.Any(u => string.Equals(token, u.ConnectAccessKey, StringComparison.OrdinalIgnoreCase)) ||
  1025. _data.PendingAuthorizations.Select(i => i.AccessToken).Contains(token, StringComparer.OrdinalIgnoreCase);
  1026. }
  1027. }
  1028. }