2
0

ConnectManager.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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.emby.media/service/" + handler;
  309. }
  310. public async Task<UserLinkResult> LinkUser(string userId, string connectUsername)
  311. {
  312. if (string.IsNullOrWhiteSpace(ConnectServerId))
  313. {
  314. await UpdateConnectInfo().ConfigureAwait(false);
  315. }
  316. await _operationLock.WaitAsync().ConfigureAwait(false);
  317. try
  318. {
  319. return await LinkUserInternal(userId, connectUsername).ConfigureAwait(false);
  320. }
  321. finally
  322. {
  323. _operationLock.Release();
  324. }
  325. }
  326. private async Task<UserLinkResult> LinkUserInternal(string userId, string connectUsername)
  327. {
  328. if (string.IsNullOrWhiteSpace(userId))
  329. {
  330. throw new ArgumentNullException("userId");
  331. }
  332. if (string.IsNullOrWhiteSpace(connectUsername))
  333. {
  334. throw new ArgumentNullException("connectUsername");
  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. if (string.IsNullOrWhiteSpace(ConnectServerId))
  389. {
  390. await UpdateConnectInfo().ConfigureAwait(false);
  391. }
  392. await _operationLock.WaitAsync().ConfigureAwait(false);
  393. try
  394. {
  395. return await InviteUserInternal(request).ConfigureAwait(false);
  396. }
  397. finally
  398. {
  399. _operationLock.Release();
  400. }
  401. }
  402. private async Task<UserLinkResult> InviteUserInternal(ConnectAuthorizationRequest request)
  403. {
  404. var connectUsername = request.ConnectUserName;
  405. var sendingUserId = request.SendingUserId;
  406. if (string.IsNullOrWhiteSpace(connectUsername))
  407. {
  408. throw new ArgumentNullException("connectUsername");
  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. }