SyncPlayManager.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using Jellyfin.Data.Enums;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.Session;
  8. using MediaBrowser.Controller.SyncPlay;
  9. using MediaBrowser.Model.SyncPlay;
  10. using Microsoft.Extensions.Logging;
  11. namespace Emby.Server.Implementations.SyncPlay
  12. {
  13. /// <summary>
  14. /// Class SyncPlayManager.
  15. /// </summary>
  16. public class SyncPlayManager : ISyncPlayManager, IDisposable
  17. {
  18. /// <summary>
  19. /// The logger.
  20. /// </summary>
  21. private readonly ILogger<SyncPlayManager> _logger;
  22. /// <summary>
  23. /// The logger factory.
  24. /// </summary>
  25. private readonly ILoggerFactory _loggerFactory;
  26. /// <summary>
  27. /// The user manager.
  28. /// </summary>
  29. private readonly IUserManager _userManager;
  30. /// <summary>
  31. /// The session manager.
  32. /// </summary>
  33. private readonly ISessionManager _sessionManager;
  34. /// <summary>
  35. /// The library manager.
  36. /// </summary>
  37. private readonly ILibraryManager _libraryManager;
  38. /// <summary>
  39. /// The map between sessions and groups.
  40. /// </summary>
  41. private readonly Dictionary<string, IGroupController> _sessionToGroupMap =
  42. new Dictionary<string, IGroupController>(StringComparer.OrdinalIgnoreCase);
  43. /// <summary>
  44. /// The groups.
  45. /// </summary>
  46. private readonly Dictionary<Guid, IGroupController> _groups =
  47. new Dictionary<Guid, IGroupController>();
  48. /// <summary>
  49. /// Lock used for accessing any group.
  50. /// </summary>
  51. private readonly object _groupsLock = new object();
  52. /// <summary>
  53. /// Lock used for accessing the session-to-group map.
  54. /// </summary>
  55. private readonly object _mapsLock = new object();
  56. private bool _disposed = false;
  57. /// <summary>
  58. /// Initializes a new instance of the <see cref="SyncPlayManager" /> class.
  59. /// </summary>
  60. /// <param name="loggerFactory">The logger factory.</param>
  61. /// <param name="userManager">The user manager.</param>
  62. /// <param name="sessionManager">The session manager.</param>
  63. /// <param name="libraryManager">The library manager.</param>
  64. public SyncPlayManager(
  65. ILoggerFactory loggerFactory,
  66. IUserManager userManager,
  67. ISessionManager sessionManager,
  68. ILibraryManager libraryManager)
  69. {
  70. _loggerFactory = loggerFactory;
  71. _userManager = userManager;
  72. _sessionManager = sessionManager;
  73. _libraryManager = libraryManager;
  74. _logger = loggerFactory.CreateLogger<SyncPlayManager>();
  75. _sessionManager.SessionStarted += OnSessionManagerSessionStarted;
  76. }
  77. /// <inheritdoc />
  78. public void Dispose()
  79. {
  80. Dispose(true);
  81. GC.SuppressFinalize(this);
  82. }
  83. /// <inheritdoc />
  84. public void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken)
  85. {
  86. // TODO: create abstract class for GroupRequests to avoid explicit request type here.
  87. if (!IsRequestValid(session, GroupRequestType.NewGroup, request))
  88. {
  89. return;
  90. }
  91. // Locking required to access list of groups.
  92. lock (_groupsLock)
  93. {
  94. // Locking required as session-to-group map will be edited.
  95. // Locking the group is not required as it is not visible yet.
  96. lock (_mapsLock)
  97. {
  98. if (IsSessionInGroup(session))
  99. {
  100. LeaveGroup(session, cancellationToken);
  101. }
  102. var group = new GroupController(_loggerFactory, _userManager, _sessionManager, _libraryManager);
  103. _groups[group.GroupId] = group;
  104. AddSessionToGroup(session, group);
  105. group.CreateGroup(session, request, cancellationToken);
  106. }
  107. }
  108. }
  109. /// <inheritdoc />
  110. public void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequest request, CancellationToken cancellationToken)
  111. {
  112. // TODO: create abstract class for GroupRequests to avoid explicit request type here.
  113. if (!IsRequestValid(session, GroupRequestType.JoinGroup, request))
  114. {
  115. return;
  116. }
  117. var user = _userManager.GetUserById(session.UserId);
  118. // Locking required to access list of groups.
  119. lock (_groupsLock)
  120. {
  121. _groups.TryGetValue(groupId, out IGroupController group);
  122. if (group == null)
  123. {
  124. _logger.LogWarning("Session {SessionId} tried to join group {GroupId} that does not exist.", session.Id, groupId);
  125. var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.GroupDoesNotExist, string.Empty);
  126. _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
  127. return;
  128. }
  129. // Locking required as session-to-group map will be edited.
  130. lock (_mapsLock)
  131. {
  132. // Group lock required to let other requests end first.
  133. lock (group)
  134. {
  135. if (!group.HasAccessToPlayQueue(user))
  136. {
  137. _logger.LogWarning("Session {SessionId} tried to join group {GroupId} but does not have access to some content of the playing queue.", session.Id, group.GroupId.ToString());
  138. var error = new GroupUpdate<string>(group.GroupId, GroupUpdateType.LibraryAccessDenied, string.Empty);
  139. _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
  140. return;
  141. }
  142. if (IsSessionInGroup(session))
  143. {
  144. if (FindJoinedGroupId(session).Equals(groupId))
  145. {
  146. group.SessionRestore(session, request, cancellationToken);
  147. return;
  148. }
  149. LeaveGroup(session, cancellationToken);
  150. }
  151. AddSessionToGroup(session, group);
  152. group.SessionJoin(session, request, cancellationToken);
  153. }
  154. }
  155. }
  156. }
  157. /// <inheritdoc />
  158. public void LeaveGroup(SessionInfo session, CancellationToken cancellationToken)
  159. {
  160. // TODO: create abstract class for GroupRequests to avoid explicit request type here.
  161. if (!IsRequestValid(session, GroupRequestType.LeaveGroup))
  162. {
  163. return;
  164. }
  165. // Locking required to access list of groups.
  166. lock (_groupsLock)
  167. {
  168. // Locking required as session-to-group map will be edited.
  169. lock (_mapsLock)
  170. {
  171. var group = FindJoinedGroup(session);
  172. if (group == null)
  173. {
  174. _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id);
  175. var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty);
  176. _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
  177. return;
  178. }
  179. // Group lock required to let other requests end first.
  180. lock (group)
  181. {
  182. RemoveSessionFromGroup(session, group);
  183. group.SessionLeave(session, cancellationToken);
  184. if (group.IsGroupEmpty())
  185. {
  186. _logger.LogInformation("Group {GroupId} is empty, removing it.", group.GroupId);
  187. _groups.Remove(group.GroupId, out _);
  188. }
  189. }
  190. }
  191. }
  192. }
  193. /// <inheritdoc />
  194. public List<GroupInfoDto> ListGroups(SessionInfo session)
  195. {
  196. // TODO: create abstract class for GroupRequests to avoid explicit request type here.
  197. if (!IsRequestValid(session, GroupRequestType.ListGroups))
  198. {
  199. return new List<GroupInfoDto>();
  200. }
  201. var user = _userManager.GetUserById(session.UserId);
  202. List<GroupInfoDto> list = new List<GroupInfoDto>();
  203. // Locking required to access list of groups.
  204. lock (_groupsLock)
  205. {
  206. foreach (var group in _groups.Values)
  207. {
  208. // Locking required as group is not thread-safe.
  209. lock (group)
  210. {
  211. if (group.HasAccessToPlayQueue(user))
  212. {
  213. list.Add(group.GetInfo());
  214. }
  215. }
  216. }
  217. }
  218. return list;
  219. }
  220. /// <inheritdoc />
  221. public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken)
  222. {
  223. // TODO: create abstract class for GroupRequests to avoid explicit request type here.
  224. if (!IsRequestValid(session, GroupRequestType.Playback, request))
  225. {
  226. return;
  227. }
  228. var group = FindJoinedGroup(session);
  229. if (group == null)
  230. {
  231. _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id);
  232. var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty);
  233. _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
  234. return;
  235. }
  236. // Group lock required as GroupController is not thread-safe.
  237. lock (group)
  238. {
  239. group.HandleRequest(session, request, cancellationToken);
  240. }
  241. }
  242. /// <summary>
  243. /// Releases unmanaged and optionally managed resources.
  244. /// </summary>
  245. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  246. protected virtual void Dispose(bool disposing)
  247. {
  248. if (_disposed)
  249. {
  250. return;
  251. }
  252. _sessionManager.SessionStarted -= OnSessionManagerSessionStarted;
  253. _disposed = true;
  254. }
  255. private void OnSessionManagerSessionStarted(object sender, SessionEventArgs e)
  256. {
  257. var session = e.SessionInfo;
  258. Guid groupId = FindJoinedGroupId(session);
  259. if (groupId.Equals(Guid.Empty))
  260. {
  261. return;
  262. }
  263. var request = new JoinGroupRequest(groupId);
  264. JoinGroup(session, groupId, request, CancellationToken.None);
  265. }
  266. /// <summary>
  267. /// Checks if a given session has joined a group.
  268. /// </summary>
  269. /// <param name="session">The session.</param>
  270. /// <returns><c>true</c> if the session has joined a group, <c>false</c> otherwise.</returns>
  271. private bool IsSessionInGroup(SessionInfo session)
  272. {
  273. lock (_mapsLock)
  274. {
  275. return _sessionToGroupMap.ContainsKey(session.Id);
  276. }
  277. }
  278. /// <summary>
  279. /// Gets the group joined by the given session, if any.
  280. /// </summary>
  281. /// <param name="session">The session.</param>
  282. /// <returns>The group.</returns>
  283. private IGroupController FindJoinedGroup(SessionInfo session)
  284. {
  285. lock (_mapsLock)
  286. {
  287. _sessionToGroupMap.TryGetValue(session.Id, out var group);
  288. return group;
  289. }
  290. }
  291. /// <summary>
  292. /// Gets the group identifier joined by the given session, if any.
  293. /// </summary>
  294. /// <param name="session">The session.</param>
  295. /// <returns>The group identifier if the session has joined a group, an empty identifier otherwise.</returns>
  296. private Guid FindJoinedGroupId(SessionInfo session)
  297. {
  298. return FindJoinedGroup(session)?.GroupId ?? Guid.Empty;
  299. }
  300. /// <summary>
  301. /// Maps a session to a group.
  302. /// </summary>
  303. /// <param name="session">The session.</param>
  304. /// <param name="group">The group.</param>
  305. /// <exception cref="InvalidOperationException">Thrown when the user is in another group already.</exception>
  306. private void AddSessionToGroup(SessionInfo session, IGroupController group)
  307. {
  308. if (session == null)
  309. {
  310. throw new InvalidOperationException("Session is null!");
  311. }
  312. lock (_mapsLock)
  313. {
  314. if (IsSessionInGroup(session))
  315. {
  316. throw new InvalidOperationException("Session in other group already!");
  317. }
  318. _sessionToGroupMap[session.Id] = group ?? throw new InvalidOperationException("Group is null!");
  319. }
  320. }
  321. /// <summary>
  322. /// Unmaps a session from a group.
  323. /// </summary>
  324. /// <param name="session">The session.</param>
  325. /// <param name="group">The group.</param>
  326. /// <exception cref="InvalidOperationException">Thrown when the user is not found in the specified group.</exception>
  327. private void RemoveSessionFromGroup(SessionInfo session, IGroupController group)
  328. {
  329. if (session == null)
  330. {
  331. throw new InvalidOperationException("Session is null!");
  332. }
  333. if (group == null)
  334. {
  335. throw new InvalidOperationException("Group is null!");
  336. }
  337. lock (_mapsLock)
  338. {
  339. if (!IsSessionInGroup(session))
  340. {
  341. throw new InvalidOperationException("Session not in any group!");
  342. }
  343. _sessionToGroupMap.Remove(session.Id, out var tempGroup);
  344. if (!tempGroup.GroupId.Equals(group.GroupId))
  345. {
  346. throw new InvalidOperationException("Session was in wrong group!");
  347. }
  348. }
  349. }
  350. /// <summary>
  351. /// Checks if a given session is allowed to make a given request.
  352. /// </summary>
  353. /// <param name="session">The session.</param>
  354. /// <param name="requestType">The request type.</param>
  355. /// <param name="request">The request.</param>
  356. /// <param name="checkRequest">Whether to check if request is null.</param>
  357. /// <returns><c>true</c> if the request is valid, <c>false</c> otherwise. Will return <c>false</c> also when session is null.</returns>
  358. private bool IsRequestValid<T>(SessionInfo session, GroupRequestType requestType, T request, bool checkRequest = true)
  359. {
  360. if (session == null || (request == null && checkRequest))
  361. {
  362. return false;
  363. }
  364. var user = _userManager.GetUserById(session.UserId);
  365. if (user.SyncPlayAccess == SyncPlayAccess.None)
  366. {
  367. _logger.LogWarning("Session {SessionId} requested {RequestType} but does not have access to SyncPlay.", session.Id, requestType);
  368. // TODO: rename to a more generic error. Next PR will fix this.
  369. var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.JoinGroupDenied, string.Empty);
  370. _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
  371. return false;
  372. }
  373. if (requestType.Equals(GroupRequestType.NewGroup) && user.SyncPlayAccess != SyncPlayAccess.CreateAndJoinGroups)
  374. {
  375. _logger.LogWarning("Session {SessionId} does not have permission to create groups.", session.Id);
  376. var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.CreateGroupDenied, string.Empty);
  377. _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
  378. return false;
  379. }
  380. return true;
  381. }
  382. /// <summary>
  383. /// Checks if a given session is allowed to make a given type of request.
  384. /// </summary>
  385. /// <param name="session">The session.</param>
  386. /// <param name="requestType">The request type.</param>
  387. /// <returns><c>true</c> if the request is valid, <c>false</c> otherwise. Will return <c>false</c> also when session is null.</returns>
  388. private bool IsRequestValid(SessionInfo session, GroupRequestType requestType)
  389. {
  390. return IsRequestValid(session, requestType, session, false);
  391. }
  392. }
  393. }