aboutsummaryrefslogtreecommitdiff
path: root/Emby.Dlna/Main/DlnaEntryPoint.cs
blob: 16108522c364f2ff5ebcf4a0f823461a18d2fec8 (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
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dlna;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using Emby.Dlna.PlayTo;
using Emby.Dlna.Ssdp;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Threading;
using Rssdp;
using Rssdp.Infrastructure;

namespace Emby.Dlna.Main
{
    public class DlnaEntryPoint : IServerEntryPoint
    {
        private readonly IServerConfigurationManager _config;
        private readonly ILogger _logger;
        private readonly IServerApplicationHost _appHost;

        private PlayToManager _manager;
        private readonly ISessionManager _sessionManager;
        private readonly IHttpClient _httpClient;
        private readonly ILibraryManager _libraryManager;
        private readonly IUserManager _userManager;
        private readonly IDlnaManager _dlnaManager;
        private readonly IImageProcessor _imageProcessor;
        private readonly IUserDataManager _userDataManager;
        private readonly ILocalizationManager _localization;
        private readonly IMediaSourceManager _mediaSourceManager;
        private readonly IMediaEncoder _mediaEncoder;

        private readonly IDeviceDiscovery _deviceDiscovery;

        private bool _ssdpHandlerStarted;
        private bool _dlnaServerStarted;
        private SsdpDevicePublisher _Publisher;

        private readonly ITimerFactory _timerFactory;
        private readonly ISocketFactory _socketFactory;
        private readonly IEnvironmentInfo _environmentInfo;
        private readonly INetworkManager _networkManager;

        private ISsdpCommunicationsServer _communicationsServer;

        public DlnaEntryPoint(IServerConfigurationManager config,
            ILogManager logManager,
            IServerApplicationHost appHost,
            ISessionManager sessionManager,
            IHttpClient httpClient,
            ILibraryManager libraryManager,
            IUserManager userManager,
            IDlnaManager dlnaManager,
            IImageProcessor imageProcessor,
            IUserDataManager userDataManager,
            ILocalizationManager localization,
            IMediaSourceManager mediaSourceManager,
            IDeviceDiscovery deviceDiscovery, IMediaEncoder mediaEncoder, ISocketFactory socketFactory, ITimerFactory timerFactory, IEnvironmentInfo environmentInfo, INetworkManager networkManager)
        {
            _config = config;
            _appHost = appHost;
            _sessionManager = sessionManager;
            _httpClient = httpClient;
            _libraryManager = libraryManager;
            _userManager = userManager;
            _dlnaManager = dlnaManager;
            _imageProcessor = imageProcessor;
            _userDataManager = userDataManager;
            _localization = localization;
            _mediaSourceManager = mediaSourceManager;
            _deviceDiscovery = deviceDiscovery;
            _mediaEncoder = mediaEncoder;
            _socketFactory = socketFactory;
            _timerFactory = timerFactory;
            _environmentInfo = environmentInfo;
            _networkManager = networkManager;
            _logger = logManager.GetLogger("Dlna");
        }

        public void Run()
        {
            ((DlnaManager)_dlnaManager).InitProfiles();

            ReloadComponents();

            _config.ConfigurationUpdated += _config_ConfigurationUpdated;
            _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
        }

        private bool _lastEnableUpnP;
        void _config_ConfigurationUpdated(object sender, EventArgs e)
        {
            if (_lastEnableUpnP != _config.Configuration.EnableUPnP)
            {
                ReloadComponents();
            }
            _lastEnableUpnP = _config.Configuration.EnableUPnP;
        }

        void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
        {
            if (string.Equals(e.Key, "dlna", StringComparison.OrdinalIgnoreCase))
            {
                ReloadComponents();
            }
        }

        private async void ReloadComponents()
        {
            var options = _config.GetDlnaConfiguration();

            if (!_ssdpHandlerStarted)
            {
                StartSsdpHandler();
            }

            var isServerStarted = _dlnaServerStarted;

            if (options.EnableServer && !isServerStarted)
            {
                await StartDlnaServer().ConfigureAwait(false);
            }
            else if (!options.EnableServer && isServerStarted)
            {
                DisposeDlnaServer();
            }

            var isPlayToStarted = _manager != null;

            if (options.EnablePlayTo && !isPlayToStarted)
            {
                StartPlayToManager();
            }
            else if (!options.EnablePlayTo && isPlayToStarted)
            {
                DisposePlayToManager();
            }
        }

        private void StartSsdpHandler()
        {
            try
            {
                if (_communicationsServer == null)
                {
                    var enableMultiSocketBinding = _environmentInfo.OperatingSystem == OperatingSystem.Windows;

                    _communicationsServer = new SsdpCommunicationsServer(_socketFactory, _networkManager, _logger, enableMultiSocketBinding)
                    {
                        IsShared = true
                    };
                }

                StartPublishing(_communicationsServer);
                _ssdpHandlerStarted = true;

                StartDeviceDiscovery(_communicationsServer);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error starting ssdp handlers", ex);
            }
        }

        private void LogMessage(string msg)
        {
            _logger.Debug(msg);
        }

        private void StartPublishing(ISsdpCommunicationsServer communicationsServer)
        {
            SsdpDevicePublisherBase.LogFunction = LogMessage;
            _Publisher = new SsdpDevicePublisher(communicationsServer, _timerFactory, _environmentInfo.OperatingSystemName, _environmentInfo.OperatingSystemVersion);
        }

        private void StartDeviceDiscovery(ISsdpCommunicationsServer communicationsServer)
        {
            try
            {
                ((DeviceDiscovery)_deviceDiscovery).Start(communicationsServer);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error starting device discovery", ex);
            }
        }

        private void DisposeDeviceDiscovery()
        {
            try
            {
                ((DeviceDiscovery)_deviceDiscovery).Dispose();
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error stopping device discovery", ex);
            }
        }

        private void DisposeSsdpHandler()
        {
            DisposeDeviceDiscovery();

            try
            {
                ((DeviceDiscovery)_deviceDiscovery).Dispose();

                _ssdpHandlerStarted = false;
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error stopping ssdp handlers", ex);
            }
        }

        public async Task StartDlnaServer()
        {
            try
            {
                await RegisterServerEndpoints().ConfigureAwait(false);

                _dlnaServerStarted = true;
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error registering endpoint", ex);
            }
        }

        private async Task RegisterServerEndpoints()
        {
            if (!_config.GetDlnaConfiguration().BlastAliveMessages)
            {
                return;
            }

            var cacheLength = _config.GetDlnaConfiguration().BlastAliveMessageIntervalSeconds;
            _Publisher.SupportPnpRootDevice = false;

            var addresses = (await _appHost.GetLocalIpAddresses().ConfigureAwait(false)).ToList();

            var udn = CreateUuid(_appHost.SystemId);

            foreach (var address in addresses)
            {
                //if (IPAddress.IsLoopback(address))
                //{
                //    // Should we allow this?
                //    continue;
                //}

                var fullService = "urn:schemas-upnp-org:device:MediaServer:1";

                _logger.Info("Registering publisher for {0} on {1}", fullService, address.ToString());

                var descriptorUri = "/dlna/" + udn + "/description.xml";
                var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorUri);

                var device = new SsdpRootDevice
                {
                    CacheLifetime = TimeSpan.FromSeconds(cacheLength), //How long SSDP clients can cache this info.
                    Location = uri, // Must point to the URL that serves your devices UPnP description document. 
                    FriendlyName = "Emby Server",
                    Manufacturer = "Emby",
                    ModelName = "Emby Server",
                    Uuid = udn
                    // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc.                
                };

                SetProperies(device, fullService);
                _Publisher.AddDevice(device);

                var embeddedDevices = new List<string>
                {
                    "urn:schemas-upnp-org:service:ContentDirectory:1",
                    "urn:schemas-upnp-org:service:ConnectionManager:1",
                    //"urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1"
                };

                foreach (var subDevice in embeddedDevices)
                {
                    var embeddedDevice = new SsdpEmbeddedDevice
                    {
                        FriendlyName = device.FriendlyName,
                        Manufacturer = device.Manufacturer,
                        ModelName = device.ModelName,
                        Uuid = udn
                        // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc.                
                    };

                    SetProperies(embeddedDevice, subDevice);
                    device.AddDevice(embeddedDevice);
                }
            }
        }

        private string CreateUuid(string text)
        {
            Guid guid;
            if (!Guid.TryParse(text, out guid))
            {
                guid = text.GetMD5();
            }
            return guid.ToString("N");
        }

        private void SetProperies(SsdpDevice device, string fullDeviceType)
        {
            var service = fullDeviceType.Replace("urn:", string.Empty).Replace(":1", string.Empty);

            var serviceParts = service.Split(':');

            var deviceTypeNamespace = serviceParts[0].Replace('.', '-');

            device.DeviceTypeNamespace = deviceTypeNamespace;
            device.DeviceClass = serviceParts[1];
            device.DeviceType = serviceParts[2];
        }

        private readonly object _syncLock = new object();
        private void StartPlayToManager()
        {
            lock (_syncLock)
            {
                try
                {
                    _manager = new PlayToManager(_logger,
                        _sessionManager,
                        _libraryManager,
                        _userManager,
                        _dlnaManager,
                        _appHost,
                        _imageProcessor,
                        _deviceDiscovery,
                        _httpClient,
                        _config,
                        _userDataManager,
                        _localization,
                        _mediaSourceManager,
                        _mediaEncoder,
                        _timerFactory);

                    _manager.Start();
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error starting PlayTo manager", ex);
                }
            }
        }

        private void DisposePlayToManager()
        {
            lock (_syncLock)
            {
                if (_manager != null)
                {
                    try
                    {
                        _manager.Dispose();
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorException("Error disposing PlayTo manager", ex);
                    }
                    _manager = null;
                }
            }
        }

        public void Dispose()
        {
            DisposeDlnaServer();
            DisposePlayToManager();
            DisposeSsdpHandler();

            if (_communicationsServer != null)
            {
                _communicationsServer.Dispose();
                _communicationsServer = null;
            }
        }

        public void DisposeDlnaServer()
        {
            if (_Publisher != null)
            {
                var devices = _Publisher.Devices.ToList();
                var tasks = devices.Select(i => _Publisher.RemoveDevice(i)).ToArray();

                Task.WaitAll(tasks);
                //foreach (var device in devices)
                //{
                //    try
                //    {
                //        _Publisher.RemoveDevice(device);
                //    }
                //    catch (Exception ex)
                //    {
                //        _logger.ErrorException("Error sending bye bye", ex);
                //    }
                //}
                _Publisher.Dispose();
            }

            _dlnaServerStarted = false;
        }
    }
}