aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs
blob: 4df8e3ba77eee60ac0fe456560cca72097635a8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Session;
using MediaBrowser.Controller.SyncPlay;
using MediaBrowser.Model.SyncPlay;
using Microsoft.Extensions.Logging;

namespace Emby.Server.Implementations.SyncPlay
{
    /// <summary>
    /// Class SyncPlayManager.
    /// </summary>
    public class SyncPlayManager : ISyncPlayManager, IDisposable
    {
        /// <summary>
        /// The logger.
        /// </summary>
        private readonly ILogger<SyncPlayManager> _logger;

        /// <summary>
        /// The logger factory.
        /// </summary>
        private readonly ILoggerFactory _loggerFactory;

        /// <summary>
        /// The user manager.
        /// </summary>
        private readonly IUserManager _userManager;

        /// <summary>
        /// The session manager.
        /// </summary>
        private readonly ISessionManager _sessionManager;

        /// <summary>
        /// The library manager.
        /// </summary>
        private readonly ILibraryManager _libraryManager;

        /// <summary>
        /// The map between sessions and groups.
        /// </summary>
        private readonly Dictionary<string, IGroupController> _sessionToGroupMap =
            new Dictionary<string, IGroupController>(StringComparer.OrdinalIgnoreCase);

        /// <summary>
        /// The groups.
        /// </summary>
        private readonly Dictionary<Guid, IGroupController> _groups =
            new Dictionary<Guid, IGroupController>();

        /// <summary>
        /// Lock used for accesing the list of groups.
        /// </summary>
        private readonly object _groupsLock = new object();

        /// <summary>
        /// Lock used for accesing the session-to-group map.
        /// </summary>
        private readonly object _mapsLock = new object();

        private bool _disposed = false;

        /// <summary>
        /// Initializes a new instance of the <see cref="SyncPlayManager" /> class.
        /// </summary>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <param name="userManager">The user manager.</param>
        /// <param name="sessionManager">The session manager.</param>
        /// <param name="libraryManager">The library manager.</param>
        public SyncPlayManager(
            ILoggerFactory loggerFactory,
            IUserManager userManager,
            ISessionManager sessionManager,
            ILibraryManager libraryManager)
        {
            _loggerFactory = loggerFactory;
            _userManager = userManager;
            _sessionManager = sessionManager;
            _libraryManager = libraryManager;
            _logger = loggerFactory.CreateLogger<SyncPlayManager>();
            _sessionManager.SessionStarted += OnSessionManagerSessionStarted;
        }

        /// <inheritdoc />
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <inheritdoc />
        public void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken)
        {
            // TODO: create abstract class for GroupRequests to avoid explicit request type here.
            if (!IsRequestValid(session, GroupRequestType.NewGroup, request))
            {
                return;
            }

            // Locking required to access list of groups.
            lock (_groupsLock)
            {
                // Locking required as session-to-group map will be edited.
                // Locking the group is not required as it is not visible yet.
                lock (_mapsLock)
                {
                    if (IsSessionInGroup(session))
                    {
                        LeaveGroup(session, cancellationToken);
                    }

                    var group = new GroupController(_loggerFactory, _userManager, _sessionManager, _libraryManager);
                    _groups[group.GroupId] = group;

                    AddSessionToGroup(session, group);
                    group.CreateGroup(session, request, cancellationToken);
                }
            }
        }

        /// <inheritdoc />
        public void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequest request, CancellationToken cancellationToken)
        {
            // TODO: create abstract class for GroupRequests to avoid explicit request type here.
            if (!IsRequestValid(session, GroupRequestType.JoinGroup, request))
            {
                return;
            }

            var user = _userManager.GetUserById(session.UserId);

            // Locking required to access list of groups.
            lock (_groupsLock)
            {
                _groups.TryGetValue(groupId, out IGroupController group);

                if (group == null)
                {
                    _logger.LogWarning("Session {SessionId} tried to join group {GroupId} that does not exist.", session.Id, groupId);

                    var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.GroupDoesNotExist, string.Empty);
                    _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
                    return;
                }

                // Locking required as session-to-group map will be edited.
                lock (_mapsLock)
                {
                    // Group lock required to let other requests end first.
                    lock (group)
                    {
                        if (!group.HasAccessToPlayQueue(user))
                        {
                            _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());

                            var error = new GroupUpdate<string>(group.GroupId, GroupUpdateType.LibraryAccessDenied, string.Empty);
                            _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
                            return;
                        }

                        if (IsSessionInGroup(session))
                        {
                            if (FindJoinedGroupId(session).Equals(groupId))
                            {
                                group.SessionRestore(session, request, cancellationToken);
                                return;
                            }

                            LeaveGroup(session, cancellationToken);
                        }

                        AddSessionToGroup(session, group);
                        group.SessionJoin(session, request, cancellationToken);
                    }
                }
            }
        }

        /// <inheritdoc />
        public void LeaveGroup(SessionInfo session, CancellationToken cancellationToken)
        {
            // TODO: create abstract class for GroupRequests to avoid explicit request type here.
            if (!IsRequestValid(session, GroupRequestType.LeaveGroup))
            {
                return;
            }

            // Locking required to access list of groups.
            lock (_groupsLock)
            {
                // Locking required as session-to-group map will be edited.
                lock (_mapsLock)
                {
                    var group = FindJoinedGroup(session);
                    if (group == null)
                    {
                        _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id);

                        var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty);
                        _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
                        return;
                    }

                    // Group lock required to let other requests end first.
                    lock (group)
                    {
                        RemoveSessionFromGroup(session, group);
                        group.SessionLeave(session, cancellationToken);

                        if (group.IsGroupEmpty())
                        {
                            _logger.LogInformation("Group {GroupId} is empty, removing it.", group.GroupId);
                            _groups.Remove(group.GroupId, out _);
                        }
                    }
                }
            }
        }

        /// <inheritdoc />
        public List<GroupInfoDto> ListGroups(SessionInfo session)
        {
            // TODO: create abstract class for GroupRequests to avoid explicit request type here.
            if (!IsRequestValid(session, GroupRequestType.ListGroups))
            {
                return new List<GroupInfoDto>();
            }

            var user = _userManager.GetUserById(session.UserId);
            List<GroupInfoDto> list = new List<GroupInfoDto>();

            // Locking required to access list of groups.
            lock (_groupsLock)
            {
                foreach (var group in _groups.Values)
                {
                    // Locking required as group is not thread-safe.
                    lock (group)
                    {
                        if (group.HasAccessToPlayQueue(user))
                        {
                            list.Add(group.GetInfo());
                        }
                    }
                }
            }

            return list;
        }

        /// <inheritdoc />
        public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken)
        {
            // TODO: create abstract class for GroupRequests to avoid explicit request type here.
            if (!IsRequestValid(session, GroupRequestType.Playback, request))
            {
                return;
            }

            var group = FindJoinedGroup(session);
            if (group == null)
            {
                _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id);

                var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty);
                _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
                return;
            }

            // Group lock required as GroupController is not thread-safe.
            lock (group)
            {
                group.HandleRequest(session, request, cancellationToken);
            }
        }

        /// <summary>
        /// Releases unmanaged and optionally managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            _sessionManager.SessionStarted -= OnSessionManagerSessionStarted;
            _disposed = true;
        }

        private void OnSessionManagerSessionStarted(object sender, SessionEventArgs e)
        {
            var session = e.SessionInfo;

            Guid groupId = FindJoinedGroupId(session);
            if (groupId.Equals(Guid.Empty))
            {
                return;
            }

            var request = new JoinGroupRequest(groupId);
            JoinGroup(session, groupId, request, CancellationToken.None);
        }

        /// <summary>
        /// Checks if a given session has joined a group.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <returns><c>true</c> if the session has joined a group, <c>false</c> otherwise.</returns>
        private bool IsSessionInGroup(SessionInfo session)
        {
            lock (_mapsLock)
            {
                return _sessionToGroupMap.ContainsKey(session.Id);
            }
        }

        /// <summary>
        /// Gets the group joined by the given session, if any.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <returns>The group.</returns>
        private IGroupController FindJoinedGroup(SessionInfo session)
        {
            lock (_mapsLock)
            {
                _sessionToGroupMap.TryGetValue(session.Id, out var group);
                return group;
            }
        }

        /// <summary>
        /// Gets the group identifier joined by the given session, if any.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <returns>The group identifier if the session has joined a group, an empty identifier otherwise.</returns>
        private Guid FindJoinedGroupId(SessionInfo session)
        {
            return FindJoinedGroup(session)?.GroupId ?? Guid.Empty;
        }

        /// <summary>
        /// Maps a session to a group.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="group">The group.</param>
        /// <exception cref="InvalidOperationException">Thrown when the user is in another group already.</exception>
        private void AddSessionToGroup(SessionInfo session, IGroupController group)
        {
            if (session == null)
            {
                throw new InvalidOperationException("Session is null!");
            }

            lock (_mapsLock)
            {
                if (IsSessionInGroup(session))
                {
                    throw new InvalidOperationException("Session in other group already!");
                }

                _sessionToGroupMap[session.Id] = group ?? throw new InvalidOperationException("Group is null!");
            }
        }

        /// <summary>
        /// Unmaps a session from a group.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="group">The group.</param>
        /// <exception cref="InvalidOperationException">Thrown when the user is not found in the specified group.</exception>
        private void RemoveSessionFromGroup(SessionInfo session, IGroupController group)
        {
            if (session == null)
            {
                throw new InvalidOperationException("Session is null!");
            }

            if (group == null)
            {
                throw new InvalidOperationException("Group is null!");
            }

            lock (_mapsLock)
            {
                if (!IsSessionInGroup(session))
                {
                    throw new InvalidOperationException("Session not in any group!");
                }

                _sessionToGroupMap.Remove(session.Id, out var tempGroup);
                if (!tempGroup.GroupId.Equals(group.GroupId))
                {
                    throw new InvalidOperationException("Session was in wrong group!");
                }
            }
        }

        /// <summary>
        /// Checks if a given session is allowed to make a given request.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="requestType">The request type.</param>
        /// <param name="request">The request.</param>
        /// <param name="checkRequest">Whether to check if request is null.</param>
        /// <returns><c>true</c> if the request is valid, <c>false</c> otherwise. Will return <c>false</c> also when session is null.</returns>
        private bool IsRequestValid<T>(SessionInfo session, GroupRequestType requestType, T request, bool checkRequest = true)
        {
            if (session == null || (request == null && checkRequest))
            {
                return false;
            }

            var user = _userManager.GetUserById(session.UserId);

            if (user.SyncPlayAccess == SyncPlayAccess.None)
            {
                _logger.LogWarning("Session {SessionId} requested {RequestType} but does not have access to SyncPlay.", session.Id, requestType);

                // TODO: rename to a more generic error. Next PR will fix this.
                var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.JoinGroupDenied, string.Empty);
                _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
                return false;
            }

            if (requestType.Equals(GroupRequestType.NewGroup) && user.SyncPlayAccess != SyncPlayAccess.CreateAndJoinGroups)
            {
                _logger.LogWarning("Session {SessionId} does not have permission to create groups.", session.Id);

                var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.CreateGroupDenied, string.Empty);
                _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None);
                return false;
            }

            return true;
        }

        /// <summary>
        /// Checks if a given session is allowed to make a given type of request.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="requestType">The request type.</param>
        /// <returns><c>true</c> if the request is valid, <c>false</c> otherwise. Will return <c>false</c> also when session is null.</returns>
        private bool IsRequestValid(SessionInfo session, GroupRequestType requestType)
        {
            return IsRequestValid(session, requestType, session, false);
        }
    }
}