aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/Session/WebSocketController.cs
blob: 0756aa1ec54fa9bf7a6a270193e87b545c03863f (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
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Session;
using MediaBrowser.Model.System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace MediaBrowser.Server.Implementations.Session
{
    public class WebSocketController : ISessionController, IDisposable
    {
        public SessionInfo Session { get; private set; }
        public IReadOnlyList<IWebSocketConnection> Sockets { get; private set; }

        private readonly ILogger _logger;

        private readonly ISessionManager _sessionManager;

        public WebSocketController(SessionInfo session, ILogger logger, ISessionManager sessionManager)
        {
            Session = session;
            _logger = logger;
            _sessionManager = sessionManager;
            Sockets = new List<IWebSocketConnection>();
        }

        public bool IsSessionActive
        {
            get
            {
                return Sockets.Any(i => i.State == WebSocketState.Open);
            }
        }

        public bool SupportsMediaControl
        {
            get { return GetActiveSockets().Any(); }
        }

        private IEnumerable<IWebSocketConnection> GetActiveSockets()
        {
            return Sockets
                .OrderByDescending(i => i.LastActivityDate)
                .Where(i => i.State == WebSocketState.Open);
        }

        public void AddWebSocket(IWebSocketConnection connection)
        {
            var sockets = Sockets.ToList();
            sockets.Add(connection);

            Sockets = sockets;

            connection.Closed += connection_Closed;
        }

        void connection_Closed(object sender, EventArgs e)
        {
            if (!GetActiveSockets().Any())
            {
                try
                {
                    _sessionManager.ReportSessionEnded(Session.Id);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error reporting session ended.", ex);
                }
            }
            else
            {
                var capabilities = new ClientCapabilities
                {
                    PlayableMediaTypes = Session.PlayableMediaTypes,
                    SupportedCommands = Session.SupportedCommands,
                    SupportsMediaControl = SupportsMediaControl
                };

                _sessionManager.ReportCapabilities(Session.Id, capabilities);
            }
        }

        private IWebSocketConnection GetActiveSocket()
        {
            var socket = GetActiveSockets()
                .FirstOrDefault();

            if (socket == null)
            {
                throw new InvalidOperationException("The requested session does not have an open web socket.");
            }

            return socket;
        }

        public Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken)
        {
            return SendMessage(new WebSocketMessage<PlayRequest>
            {
                MessageType = "Play",
                Data = command

            }, cancellationToken);
        }

        public Task SendPlaystateCommand(PlaystateRequest command, CancellationToken cancellationToken)
        {
            return SendMessage(new WebSocketMessage<PlaystateRequest>
            {
                MessageType = "Playstate",
                Data = command

            }, cancellationToken);
        }

        public Task SendLibraryUpdateInfo(LibraryUpdateInfo info, CancellationToken cancellationToken)
        {
            return SendMessages(new WebSocketMessage<LibraryUpdateInfo>
            {
                MessageType = "LibraryChanged",
                Data = info

            }, cancellationToken);
        }

        /// <summary>
        /// Sends the restart required message.
        /// </summary>
        /// <param name="info">The information.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public Task SendRestartRequiredNotification(SystemInfo info, CancellationToken cancellationToken)
        {
            return SendMessages(new WebSocketMessage<SystemInfo>
            {
                MessageType = "RestartRequired",
                Data = info

            }, cancellationToken);
        }


        /// <summary>
        /// Sends the user data change info.
        /// </summary>
        /// <param name="info">The info.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public Task SendUserDataChangeInfo(UserDataChangeInfo info, CancellationToken cancellationToken)
        {
            return SendMessages(new WebSocketMessage<UserDataChangeInfo>
            {
                MessageType = "UserDataChanged",
                Data = info

            }, cancellationToken);
        }

        /// <summary>
        /// Sends the server shutdown notification.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public Task SendServerShutdownNotification(CancellationToken cancellationToken)
        {
            return SendMessages(new WebSocketMessage<string>
            {
                MessageType = "ServerShuttingDown",
                Data = string.Empty

            }, cancellationToken);
        }

        /// <summary>
        /// Sends the server restart notification.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public Task SendServerRestartNotification(CancellationToken cancellationToken)
        {
            return SendMessages(new WebSocketMessage<string>
            {
                MessageType = "ServerRestarting",
                Data = string.Empty

            }, cancellationToken);
        }

        public Task SendGeneralCommand(GeneralCommand command, CancellationToken cancellationToken)
        {
            return SendMessage(new WebSocketMessage<GeneralCommand>
            {
                MessageType = "GeneralCommand",
                Data = command

            }, cancellationToken);
        }

        public Task SendSessionEndedNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
        {
            return SendMessages(new WebSocketMessage<SessionInfoDto>
            {
                MessageType = "SessionEnded",
                Data = sessionInfo

            }, cancellationToken);
        }

        public Task SendPlaybackStartNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
        {
            return SendMessages(new WebSocketMessage<SessionInfoDto>
            {
                MessageType = "PlaybackStart",
                Data = sessionInfo

            }, cancellationToken);
        }

        public Task SendPlaybackStoppedNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
        {
            return SendMessages(new WebSocketMessage<SessionInfoDto>
            {
                MessageType = "PlaybackStopped",
                Data = sessionInfo

            }, cancellationToken);
        }

        private Task SendMessage<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
        {
            if (SkipSending()) return Task.FromResult(true);

            var socket = GetActiveSocket();

            return socket.SendAsync(message, cancellationToken);
        }

        private Task SendMessages<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
        {
            if (SkipSending()) return Task.FromResult(true);

            var tasks = GetActiveSockets().Select(i => Task.Run(async () =>
            {
                try
                {
                    await i.SendAsync(message, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error sending web socket message", ex);
                }

            }, cancellationToken));

            return Task.WhenAll(tasks);
        }

        private bool SkipSending()
        {
            if (Session != null)
            {
                if (string.Equals(Session.Client, "mb-classic", StringComparison.OrdinalIgnoreCase))
                {
                    Version version;

                    if (!string.IsNullOrWhiteSpace(Session.ApplicationVersion) && Version.TryParse(Session.ApplicationVersion, out version))
                    {
                        if (version < new Version(3, 0, 196))
                        {
                            _logger.Debug("Skipping web socket message to MBC version {0}.", version);
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        public void Dispose()
        {
            foreach (var socket in Sockets.ToList())
            {
                socket.Closed -= connection_Closed;
            }
        }
    }
}