SyncPlayManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using Jellyfin.Data.Enums;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Session;
  7. using MediaBrowser.Controller.SyncPlay;
  8. using MediaBrowser.Controller.SyncPlay.Requests;
  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, Group> _sessionToGroupMap =
  42. new Dictionary<string, Group>(StringComparer.OrdinalIgnoreCase);
  43. /// <summary>
  44. /// The groups.
  45. /// </summary>
  46. private readonly Dictionary<Guid, Group> _groups =
  47. new Dictionary<Guid, Group>();
  48. /// <summary>
  49. /// Lock used for accessing any group.
  50. /// </summary>
  51. /// <remarks>
  52. /// Always lock before <see cref="_mapsLock"/> and before locking on any <see cref="Group"/>.
  53. /// </remarks>
  54. private readonly object _groupsLock = new object();
  55. /// <summary>
  56. /// Lock used for accessing the session-to-group map.
  57. /// </summary>
  58. /// <remarks>
  59. /// Always lock after <see cref="_groupsLock"/> and before locking on any <see cref="Group"/>.
  60. /// </remarks>
  61. private readonly object _mapsLock = new object();
  62. private bool _disposed = false;
  63. /// <summary>
  64. /// Initializes a new instance of the <see cref="SyncPlayManager" /> class.
  65. /// </summary>
  66. /// <param name="loggerFactory">The logger factory.</param>
  67. /// <param name="userManager">The user manager.</param>
  68. /// <param name="sessionManager">The session manager.</param>
  69. /// <param name="libraryManager">The library manager.</param>
  70. public SyncPlayManager(
  71. ILoggerFactory loggerFactory,
  72. IUserManager userManager,
  73. ISessionManager sessionManager,
  74. ILibraryManager libraryManager)
  75. {
  76. _loggerFactory = loggerFactory;
  77. _userManager = userManager;
  78. _sessionManager = sessionManager;
  79. _libraryManager = libraryManager;
  80. _logger = loggerFactory.CreateLogger<SyncPlayManager>();
  81. _sessionManager.SessionStarted += OnSessionManagerSessionStarted;
  82. }
  83. /// <inheritdoc />
  84. public void Dispose()
  85. {
  86. Dispose(true);
  87. GC.SuppressFinalize(this);
  88. }
  89. /// <inheritdoc />
  90. public void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken)
  91. {
  92. // Locking required to access list of groups.
  93. lock (_groupsLock)
  94. {
  95. // Locking required as session-to-group map will be edited.
  96. // Locking the group is not required as it is not visible yet.
  97. lock (_mapsLock)
  98. {
  99. if (IsSessionInGroup(session))
  100. {
  101. var leaveGroupRequest = new LeaveGroupRequest();
  102. LeaveGroup(session, leaveGroupRequest, cancellationToken);
  103. }
  104. var group = new Group(_loggerFactory, _userManager, _sessionManager, _libraryManager);
  105. _groups[group.GroupId] = group;
  106. AddSessionToGroup(session, group);
  107. group.CreateGroup(session, request, cancellationToken);
  108. }
  109. }
  110. }
  111. /// <inheritdoc />
  112. public void JoinGroup(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken)
  113. {
  114. var user = _userManager.GetUserById(session.UserId);
  115. // Locking required to access list of groups.
  116. lock (_groupsLock)
  117. {
  118. _groups.TryGetValue(request.GroupId, out Group group);
  119. if (group == null)
  120. {
  121. _logger.LogWarning("Session {SessionId} tried to join group {GroupId} that does not exist.", session.Id, request.GroupId);
  122. var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.GroupDoesNotExist, string.Empty);
  123. _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
  124. return;
  125. }
  126. // Locking required as session-to-group map will be edited.
  127. lock (_mapsLock)
  128. {
  129. // Group lock required to let other requests end first.
  130. lock (group)
  131. {
  132. if (!group.HasAccessToPlayQueue(user))
  133. {
  134. _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());
  135. var error = new GroupUpdate<string>(group.GroupId, GroupUpdateType.LibraryAccessDenied, string.Empty);
  136. _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
  137. return;
  138. }
  139. if (IsSessionInGroup(session))
  140. {
  141. if (FindJoinedGroupId(session).Equals(request.GroupId))
  142. {
  143. // Restore session.
  144. group.SessionJoin(session, request, cancellationToken);
  145. return;
  146. }
  147. var leaveGroupRequest = new LeaveGroupRequest();
  148. LeaveGroup(session, leaveGroupRequest, cancellationToken);
  149. }
  150. AddSessionToGroup(session, group);
  151. group.SessionJoin(session, request, cancellationToken);
  152. }
  153. }
  154. }
  155. }
  156. /// <inheritdoc />
  157. public void LeaveGroup(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken)
  158. {
  159. // Locking required to access list of groups.
  160. lock (_groupsLock)
  161. {
  162. // Locking required as session-to-group map will be edited.
  163. lock (_mapsLock)
  164. {
  165. var group = FindJoinedGroup(session);
  166. if (group == null)
  167. {
  168. _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id);
  169. var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty);
  170. _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
  171. return;
  172. }
  173. // Group lock required to let other requests end first.
  174. lock (group)
  175. {
  176. RemoveSessionFromGroup(session, group);
  177. group.SessionLeave(session, request, cancellationToken);
  178. if (group.IsGroupEmpty())
  179. {
  180. _logger.LogInformation("Group {GroupId} is empty, removing it.", group.GroupId);
  181. _groups.Remove(group.GroupId, out _);
  182. }
  183. }
  184. }
  185. }
  186. }
  187. /// <inheritdoc />
  188. public List<GroupInfoDto> ListGroups(SessionInfo session, ListGroupsRequest request)
  189. {
  190. var user = _userManager.GetUserById(session.UserId);
  191. List<GroupInfoDto> list = new List<GroupInfoDto>();
  192. // Locking required to access list of groups.
  193. lock (_groupsLock)
  194. {
  195. foreach (var group in _groups.Values)
  196. {
  197. // Locking required as group is not thread-safe.
  198. lock (group)
  199. {
  200. if (group.HasAccessToPlayQueue(user))
  201. {
  202. list.Add(group.GetInfo());
  203. }
  204. }
  205. }
  206. }
  207. return list;
  208. }
  209. /// <inheritdoc />
  210. public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken)
  211. {
  212. Group group;
  213. lock (_mapsLock)
  214. {
  215. group = FindJoinedGroup(session);
  216. }
  217. if (group == null)
  218. {
  219. _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id);
  220. var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty);
  221. _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
  222. return;
  223. }
  224. // Group lock required as Group is not thread-safe.
  225. lock (group)
  226. {
  227. group.HandleRequest(session, request, cancellationToken);
  228. }
  229. }
  230. /// <summary>
  231. /// Releases unmanaged and optionally managed resources.
  232. /// </summary>
  233. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  234. protected virtual void Dispose(bool disposing)
  235. {
  236. if (_disposed)
  237. {
  238. return;
  239. }
  240. _sessionManager.SessionStarted -= OnSessionManagerSessionStarted;
  241. _disposed = true;
  242. }
  243. private void OnSessionManagerSessionStarted(object sender, SessionEventArgs e)
  244. {
  245. var session = e.SessionInfo;
  246. Guid groupId = Guid.Empty;
  247. lock (_mapsLock)
  248. {
  249. groupId = FindJoinedGroupId(session);
  250. }
  251. if (groupId.Equals(Guid.Empty))
  252. {
  253. return;
  254. }
  255. var request = new JoinGroupRequest(groupId);
  256. JoinGroup(session, request, CancellationToken.None);
  257. }
  258. /// <summary>
  259. /// Checks if a given session has joined a group.
  260. /// </summary>
  261. /// <remarks>
  262. /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required.
  263. /// </remarks>
  264. /// <param name="session">The session.</param>
  265. /// <returns><c>true</c> if the session has joined a group, <c>false</c> otherwise.</returns>
  266. private bool IsSessionInGroup(SessionInfo session)
  267. {
  268. return _sessionToGroupMap.ContainsKey(session.Id);
  269. }
  270. /// <summary>
  271. /// Gets the group joined by the given session, if any.
  272. /// </summary>
  273. /// <remarks>
  274. /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required.
  275. /// </remarks>
  276. /// <param name="session">The session.</param>
  277. /// <returns>The group.</returns>
  278. private Group FindJoinedGroup(SessionInfo session)
  279. {
  280. _sessionToGroupMap.TryGetValue(session.Id, out var group);
  281. return group;
  282. }
  283. /// <summary>
  284. /// Gets the group identifier joined by the given session, if any.
  285. /// </summary>
  286. /// <remarks>
  287. /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required.
  288. /// </remarks>
  289. /// <param name="session">The session.</param>
  290. /// <returns>The group identifier if the session has joined a group, an empty identifier otherwise.</returns>
  291. private Guid FindJoinedGroupId(SessionInfo session)
  292. {
  293. return FindJoinedGroup(session)?.GroupId ?? Guid.Empty;
  294. }
  295. /// <summary>
  296. /// Maps a session to a group.
  297. /// </summary>
  298. /// <remarks>
  299. /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required.
  300. /// </remarks>
  301. /// <param name="session">The session.</param>
  302. /// <param name="group">The group.</param>
  303. /// <exception cref="InvalidOperationException">Thrown when the user is in another group already.</exception>
  304. private void AddSessionToGroup(SessionInfo session, Group group)
  305. {
  306. if (session == null)
  307. {
  308. throw new InvalidOperationException("Session is null!");
  309. }
  310. if (IsSessionInGroup(session))
  311. {
  312. throw new InvalidOperationException("Session in other group already!");
  313. }
  314. _sessionToGroupMap[session.Id] = group ?? throw new InvalidOperationException("Group is null!");
  315. }
  316. /// <summary>
  317. /// Unmaps a session from a group.
  318. /// </summary>
  319. /// <remarks>
  320. /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required.
  321. /// </remarks>
  322. /// <param name="session">The session.</param>
  323. /// <param name="group">The group.</param>
  324. /// <exception cref="InvalidOperationException">Thrown when the user is not found in the specified group.</exception>
  325. private void RemoveSessionFromGroup(SessionInfo session, Group group)
  326. {
  327. if (session == null)
  328. {
  329. throw new InvalidOperationException("Session is null!");
  330. }
  331. if (group == null)
  332. {
  333. throw new InvalidOperationException("Group is null!");
  334. }
  335. if (!IsSessionInGroup(session))
  336. {
  337. throw new InvalidOperationException("Session not in any group!");
  338. }
  339. _sessionToGroupMap.Remove(session.Id, out var tempGroup);
  340. if (!tempGroup.GroupId.Equals(group.GroupId))
  341. {
  342. throw new InvalidOperationException("Session was in wrong group!");
  343. }
  344. }
  345. }
  346. }