DlnaEntryPoint.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Globalization;
  4. using System.Net.Http;
  5. using System.Net.Sockets;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Emby.Dlna.PlayTo;
  9. using Emby.Dlna.Ssdp;
  10. using MediaBrowser.Common.Configuration;
  11. using MediaBrowser.Common.Extensions;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Controller;
  14. using MediaBrowser.Controller.Configuration;
  15. using MediaBrowser.Controller.Dlna;
  16. using MediaBrowser.Controller.Drawing;
  17. using MediaBrowser.Controller.Library;
  18. using MediaBrowser.Controller.MediaEncoding;
  19. using MediaBrowser.Controller.Plugins;
  20. using MediaBrowser.Controller.Session;
  21. using MediaBrowser.Controller.TV;
  22. using MediaBrowser.Model.Dlna;
  23. using MediaBrowser.Model.Globalization;
  24. using MediaBrowser.Model.Net;
  25. using MediaBrowser.Model.System;
  26. using Microsoft.Extensions.Logging;
  27. using Rssdp;
  28. using Rssdp.Infrastructure;
  29. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  30. namespace Emby.Dlna.Main
  31. {
  32. public sealed class DlnaEntryPoint : IServerEntryPoint, IRunBeforeStartup
  33. {
  34. private readonly IServerConfigurationManager _config;
  35. private readonly ILogger<DlnaEntryPoint> _logger;
  36. private readonly IServerApplicationHost _appHost;
  37. private readonly ISessionManager _sessionManager;
  38. private readonly IHttpClientFactory _httpClientFactory;
  39. private readonly ILibraryManager _libraryManager;
  40. private readonly IUserManager _userManager;
  41. private readonly IDlnaManager _dlnaManager;
  42. private readonly IImageProcessor _imageProcessor;
  43. private readonly IUserDataManager _userDataManager;
  44. private readonly ILocalizationManager _localization;
  45. private readonly IMediaSourceManager _mediaSourceManager;
  46. private readonly IMediaEncoder _mediaEncoder;
  47. private readonly IDeviceDiscovery _deviceDiscovery;
  48. private readonly ISocketFactory _socketFactory;
  49. private readonly INetworkManager _networkManager;
  50. private readonly object _syncLock = new object();
  51. private PlayToManager _manager;
  52. private SsdpDevicePublisher _publisher;
  53. private ISsdpCommunicationsServer _communicationsServer;
  54. private bool _disposed;
  55. public DlnaEntryPoint(
  56. IServerConfigurationManager config,
  57. ILoggerFactory loggerFactory,
  58. IServerApplicationHost appHost,
  59. ISessionManager sessionManager,
  60. IHttpClientFactory httpClientFactory,
  61. ILibraryManager libraryManager,
  62. IUserManager userManager,
  63. IDlnaManager dlnaManager,
  64. IImageProcessor imageProcessor,
  65. IUserDataManager userDataManager,
  66. ILocalizationManager localizationManager,
  67. IMediaSourceManager mediaSourceManager,
  68. IDeviceDiscovery deviceDiscovery,
  69. IMediaEncoder mediaEncoder,
  70. ISocketFactory socketFactory,
  71. INetworkManager networkManager,
  72. IUserViewManager userViewManager,
  73. ITVSeriesManager tvSeriesManager)
  74. {
  75. _config = config;
  76. _appHost = appHost;
  77. _sessionManager = sessionManager;
  78. _httpClientFactory = httpClientFactory;
  79. _libraryManager = libraryManager;
  80. _userManager = userManager;
  81. _dlnaManager = dlnaManager;
  82. _imageProcessor = imageProcessor;
  83. _userDataManager = userDataManager;
  84. _localization = localizationManager;
  85. _mediaSourceManager = mediaSourceManager;
  86. _deviceDiscovery = deviceDiscovery;
  87. _mediaEncoder = mediaEncoder;
  88. _socketFactory = socketFactory;
  89. _networkManager = networkManager;
  90. _logger = loggerFactory.CreateLogger<DlnaEntryPoint>();
  91. ContentDirectory = new ContentDirectory.ContentDirectoryService(
  92. dlnaManager,
  93. userDataManager,
  94. imageProcessor,
  95. libraryManager,
  96. config,
  97. userManager,
  98. loggerFactory.CreateLogger<ContentDirectory.ContentDirectoryService>(),
  99. httpClientFactory,
  100. localizationManager,
  101. mediaSourceManager,
  102. userViewManager,
  103. mediaEncoder,
  104. tvSeriesManager);
  105. ConnectionManager = new ConnectionManager.ConnectionManagerService(
  106. dlnaManager,
  107. config,
  108. loggerFactory.CreateLogger<ConnectionManager.ConnectionManagerService>(),
  109. httpClientFactory);
  110. MediaReceiverRegistrar = new MediaReceiverRegistrar.MediaReceiverRegistrarService(
  111. loggerFactory.CreateLogger<MediaReceiverRegistrar.MediaReceiverRegistrarService>(),
  112. httpClientFactory,
  113. config);
  114. Current = this;
  115. }
  116. public static DlnaEntryPoint Current { get; private set; }
  117. public IContentDirectory ContentDirectory { get; private set; }
  118. public IConnectionManager ConnectionManager { get; private set; }
  119. public IMediaReceiverRegistrar MediaReceiverRegistrar { get; private set; }
  120. public async Task RunAsync()
  121. {
  122. await ((DlnaManager)_dlnaManager).InitProfilesAsync().ConfigureAwait(false);
  123. await ReloadComponents().ConfigureAwait(false);
  124. _config.NamedConfigurationUpdated += OnNamedConfigurationUpdated;
  125. }
  126. private async void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  127. {
  128. if (string.Equals(e.Key, "dlna", StringComparison.OrdinalIgnoreCase))
  129. {
  130. await ReloadComponents().ConfigureAwait(false);
  131. }
  132. }
  133. private async Task ReloadComponents()
  134. {
  135. var options = _config.GetDlnaConfiguration();
  136. StartSsdpHandler();
  137. if (options.EnableServer)
  138. {
  139. await StartDevicePublisher(options).ConfigureAwait(false);
  140. }
  141. else
  142. {
  143. DisposeDevicePublisher();
  144. }
  145. if (options.EnablePlayTo)
  146. {
  147. StartPlayToManager();
  148. }
  149. else
  150. {
  151. DisposePlayToManager();
  152. }
  153. }
  154. private void StartSsdpHandler()
  155. {
  156. try
  157. {
  158. if (_communicationsServer == null)
  159. {
  160. var enableMultiSocketBinding = OperatingSystem.Id == OperatingSystemId.Windows ||
  161. OperatingSystem.Id == OperatingSystemId.Linux;
  162. _communicationsServer = new SsdpCommunicationsServer(_socketFactory, _networkManager, _logger, enableMultiSocketBinding)
  163. {
  164. IsShared = true
  165. };
  166. StartDeviceDiscovery(_communicationsServer);
  167. }
  168. }
  169. catch (Exception ex)
  170. {
  171. _logger.LogError(ex, "Error starting ssdp handlers");
  172. }
  173. }
  174. private void LogMessage(string msg)
  175. {
  176. _logger.LogDebug(msg);
  177. }
  178. private void StartDeviceDiscovery(ISsdpCommunicationsServer communicationsServer)
  179. {
  180. try
  181. {
  182. ((DeviceDiscovery)_deviceDiscovery).Start(communicationsServer);
  183. }
  184. catch (Exception ex)
  185. {
  186. _logger.LogError(ex, "Error starting device discovery");
  187. }
  188. }
  189. private void DisposeDeviceDiscovery()
  190. {
  191. try
  192. {
  193. _logger.LogInformation("Disposing DeviceDiscovery");
  194. ((DeviceDiscovery)_deviceDiscovery).Dispose();
  195. }
  196. catch (Exception ex)
  197. {
  198. _logger.LogError(ex, "Error stopping device discovery");
  199. }
  200. }
  201. public async Task StartDevicePublisher(Configuration.DlnaOptions options)
  202. {
  203. if (!options.BlastAliveMessages)
  204. {
  205. return;
  206. }
  207. if (_publisher != null)
  208. {
  209. return;
  210. }
  211. try
  212. {
  213. _publisher = new SsdpDevicePublisher(_communicationsServer, _networkManager, OperatingSystem.Name, Environment.OSVersion.VersionString, _config.GetDlnaConfiguration().SendOnlyMatchedHost)
  214. {
  215. LogFunction = LogMessage,
  216. SupportPnpRootDevice = false
  217. };
  218. await RegisterServerEndpoints().ConfigureAwait(false);
  219. _publisher.StartBroadcastingAliveMessages(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds));
  220. }
  221. catch (Exception ex)
  222. {
  223. _logger.LogError(ex, "Error registering endpoint");
  224. }
  225. }
  226. private async Task RegisterServerEndpoints()
  227. {
  228. var addresses = await _appHost.GetLocalIpAddresses(CancellationToken.None).ConfigureAwait(false);
  229. var udn = CreateUuid(_appHost.SystemId);
  230. foreach (var address in addresses)
  231. {
  232. if (address.AddressFamily == AddressFamily.InterNetworkV6)
  233. {
  234. // Not supporting IPv6 right now
  235. continue;
  236. }
  237. // Limit to LAN addresses only
  238. if (!_networkManager.IsAddressInSubnets(address, true, true))
  239. {
  240. continue;
  241. }
  242. var fullService = "urn:schemas-upnp-org:device:MediaServer:1";
  243. _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address);
  244. var descriptorUri = "/dlna/" + udn + "/description.xml";
  245. var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorUri);
  246. var device = new SsdpRootDevice
  247. {
  248. CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info.
  249. Location = uri, // Must point to the URL that serves your devices UPnP description document.
  250. Address = address,
  251. SubnetMask = _networkManager.GetLocalIpSubnetMask(address),
  252. FriendlyName = "Jellyfin",
  253. Manufacturer = "Jellyfin",
  254. ModelName = "Jellyfin Server",
  255. Uuid = udn
  256. // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc.
  257. };
  258. SetProperies(device, fullService);
  259. _publisher.AddDevice(device);
  260. var embeddedDevices = new[]
  261. {
  262. "urn:schemas-upnp-org:service:ContentDirectory:1",
  263. "urn:schemas-upnp-org:service:ConnectionManager:1",
  264. // "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1"
  265. };
  266. foreach (var subDevice in embeddedDevices)
  267. {
  268. var embeddedDevice = new SsdpEmbeddedDevice
  269. {
  270. FriendlyName = device.FriendlyName,
  271. Manufacturer = device.Manufacturer,
  272. ModelName = device.ModelName,
  273. Uuid = udn
  274. // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc.
  275. };
  276. SetProperies(embeddedDevice, subDevice);
  277. device.AddDevice(embeddedDevice);
  278. }
  279. }
  280. }
  281. private string CreateUuid(string text)
  282. {
  283. if (!Guid.TryParse(text, out var guid))
  284. {
  285. guid = text.GetMD5();
  286. }
  287. return guid.ToString("N", CultureInfo.InvariantCulture);
  288. }
  289. private void SetProperies(SsdpDevice device, string fullDeviceType)
  290. {
  291. var service = fullDeviceType.Replace("urn:", string.Empty, StringComparison.OrdinalIgnoreCase).Replace(":1", string.Empty, StringComparison.OrdinalIgnoreCase);
  292. var serviceParts = service.Split(':');
  293. var deviceTypeNamespace = serviceParts[0].Replace('.', '-');
  294. device.DeviceTypeNamespace = deviceTypeNamespace;
  295. device.DeviceClass = serviceParts[1];
  296. device.DeviceType = serviceParts[2];
  297. }
  298. private void StartPlayToManager()
  299. {
  300. lock (_syncLock)
  301. {
  302. if (_manager != null)
  303. {
  304. return;
  305. }
  306. try
  307. {
  308. _manager = new PlayToManager(
  309. _logger,
  310. _sessionManager,
  311. _libraryManager,
  312. _userManager,
  313. _dlnaManager,
  314. _appHost,
  315. _imageProcessor,
  316. _deviceDiscovery,
  317. _httpClientFactory,
  318. _config,
  319. _userDataManager,
  320. _localization,
  321. _mediaSourceManager,
  322. _mediaEncoder);
  323. _manager.Start();
  324. }
  325. catch (Exception ex)
  326. {
  327. _logger.LogError(ex, "Error starting PlayTo manager");
  328. }
  329. }
  330. }
  331. private void DisposePlayToManager()
  332. {
  333. lock (_syncLock)
  334. {
  335. if (_manager != null)
  336. {
  337. try
  338. {
  339. _logger.LogInformation("Disposing PlayToManager");
  340. _manager.Dispose();
  341. }
  342. catch (Exception ex)
  343. {
  344. _logger.LogError(ex, "Error disposing PlayTo manager");
  345. }
  346. _manager = null;
  347. }
  348. }
  349. }
  350. public void DisposeDevicePublisher()
  351. {
  352. if (_publisher != null)
  353. {
  354. _logger.LogInformation("Disposing SsdpDevicePublisher");
  355. _publisher.Dispose();
  356. _publisher = null;
  357. }
  358. }
  359. /// <inheritdoc />
  360. public void Dispose()
  361. {
  362. if (_disposed)
  363. {
  364. return;
  365. }
  366. DisposeDevicePublisher();
  367. DisposePlayToManager();
  368. DisposeDeviceDiscovery();
  369. if (_communicationsServer != null)
  370. {
  371. _logger.LogInformation("Disposing SsdpCommunicationsServer");
  372. _communicationsServer.Dispose();
  373. _communicationsServer = null;
  374. }
  375. ContentDirectory = null;
  376. ConnectionManager = null;
  377. MediaReceiverRegistrar = null;
  378. Current = null;
  379. _disposed = true;
  380. }
  381. }
  382. }