2
0

DlnaEntryPoint.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Net.Sockets;
  8. using System.Threading.Tasks;
  9. using Emby.Dlna.PlayTo;
  10. using Emby.Dlna.Ssdp;
  11. using Jellyfin.Networking.Configuration;
  12. using Jellyfin.Networking.Extensions;
  13. using MediaBrowser.Common.Configuration;
  14. using MediaBrowser.Common.Extensions;
  15. using MediaBrowser.Common.Net;
  16. using MediaBrowser.Controller;
  17. using MediaBrowser.Controller.Configuration;
  18. using MediaBrowser.Controller.Dlna;
  19. using MediaBrowser.Controller.Drawing;
  20. using MediaBrowser.Controller.Library;
  21. using MediaBrowser.Controller.MediaEncoding;
  22. using MediaBrowser.Controller.Plugins;
  23. using MediaBrowser.Controller.Session;
  24. using MediaBrowser.Model.Dlna;
  25. using MediaBrowser.Model.Globalization;
  26. using Microsoft.Extensions.Logging;
  27. using Rssdp;
  28. using Rssdp.Infrastructure;
  29. namespace Emby.Dlna.Main
  30. {
  31. public sealed class DlnaEntryPoint : IServerEntryPoint, IRunBeforeStartup
  32. {
  33. private readonly IServerConfigurationManager _config;
  34. private readonly ILogger<DlnaEntryPoint> _logger;
  35. private readonly IServerApplicationHost _appHost;
  36. private readonly ISessionManager _sessionManager;
  37. private readonly IHttpClientFactory _httpClientFactory;
  38. private readonly ILibraryManager _libraryManager;
  39. private readonly IUserManager _userManager;
  40. private readonly IDlnaManager _dlnaManager;
  41. private readonly IImageProcessor _imageProcessor;
  42. private readonly IUserDataManager _userDataManager;
  43. private readonly ILocalizationManager _localization;
  44. private readonly IMediaSourceManager _mediaSourceManager;
  45. private readonly IMediaEncoder _mediaEncoder;
  46. private readonly IDeviceDiscovery _deviceDiscovery;
  47. private readonly ISsdpCommunicationsServer _communicationsServer;
  48. private readonly INetworkManager _networkManager;
  49. private readonly object _syncLock = new();
  50. private readonly bool _disabled;
  51. private PlayToManager _manager;
  52. private SsdpDevicePublisher _publisher;
  53. private bool _disposed;
  54. public DlnaEntryPoint(
  55. IServerConfigurationManager config,
  56. ILoggerFactory loggerFactory,
  57. IServerApplicationHost appHost,
  58. ISessionManager sessionManager,
  59. IHttpClientFactory httpClientFactory,
  60. ILibraryManager libraryManager,
  61. IUserManager userManager,
  62. IDlnaManager dlnaManager,
  63. IImageProcessor imageProcessor,
  64. IUserDataManager userDataManager,
  65. ILocalizationManager localizationManager,
  66. IMediaSourceManager mediaSourceManager,
  67. IDeviceDiscovery deviceDiscovery,
  68. IMediaEncoder mediaEncoder,
  69. ISsdpCommunicationsServer communicationsServer,
  70. INetworkManager networkManager)
  71. {
  72. _config = config;
  73. _appHost = appHost;
  74. _sessionManager = sessionManager;
  75. _httpClientFactory = httpClientFactory;
  76. _libraryManager = libraryManager;
  77. _userManager = userManager;
  78. _dlnaManager = dlnaManager;
  79. _imageProcessor = imageProcessor;
  80. _userDataManager = userDataManager;
  81. _localization = localizationManager;
  82. _mediaSourceManager = mediaSourceManager;
  83. _deviceDiscovery = deviceDiscovery;
  84. _mediaEncoder = mediaEncoder;
  85. _communicationsServer = communicationsServer;
  86. _networkManager = networkManager;
  87. _logger = loggerFactory.CreateLogger<DlnaEntryPoint>();
  88. var netConfig = config.GetConfiguration<NetworkConfiguration>(NetworkConfigurationStore.StoreKey);
  89. _disabled = appHost.ListenWithHttps && netConfig.RequireHttps;
  90. if (_disabled && _config.GetDlnaConfiguration().EnableServer)
  91. {
  92. _logger.LogError("The DLNA specification does not support HTTPS.");
  93. }
  94. }
  95. public async Task RunAsync()
  96. {
  97. await ((DlnaManager)_dlnaManager).InitProfilesAsync().ConfigureAwait(false);
  98. if (_disabled)
  99. {
  100. // No use starting as dlna won't work, as we're running purely on HTTPS.
  101. return;
  102. }
  103. ReloadComponents();
  104. _config.NamedConfigurationUpdated += OnNamedConfigurationUpdated;
  105. }
  106. private void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  107. {
  108. if (string.Equals(e.Key, "dlna", StringComparison.OrdinalIgnoreCase))
  109. {
  110. ReloadComponents();
  111. }
  112. }
  113. private void ReloadComponents()
  114. {
  115. var options = _config.GetDlnaConfiguration();
  116. StartDeviceDiscovery();
  117. if (options.EnableServer)
  118. {
  119. StartDevicePublisher(options);
  120. }
  121. else
  122. {
  123. DisposeDevicePublisher();
  124. }
  125. if (options.EnablePlayTo)
  126. {
  127. StartPlayToManager();
  128. }
  129. else
  130. {
  131. DisposePlayToManager();
  132. }
  133. }
  134. private void StartDeviceDiscovery()
  135. {
  136. try
  137. {
  138. ((DeviceDiscovery)_deviceDiscovery).Start(_communicationsServer);
  139. }
  140. catch (Exception ex)
  141. {
  142. _logger.LogError(ex, "Error starting device discovery");
  143. }
  144. }
  145. public void StartDevicePublisher(Configuration.DlnaOptions options)
  146. {
  147. if (_publisher is not null)
  148. {
  149. return;
  150. }
  151. try
  152. {
  153. _publisher = new SsdpDevicePublisher(
  154. _communicationsServer,
  155. Environment.OSVersion.Platform.ToString(),
  156. // Can not use VersionString here since that includes OS and version
  157. Environment.OSVersion.Version.ToString(),
  158. _config.GetDlnaConfiguration().SendOnlyMatchedHost)
  159. {
  160. LogFunction = (msg) => _logger.LogDebug("{Msg}", msg),
  161. SupportPnpRootDevice = false
  162. };
  163. RegisterServerEndpoints();
  164. if (options.BlastAliveMessages)
  165. {
  166. _publisher.StartSendingAliveNotifications(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds));
  167. }
  168. }
  169. catch (Exception ex)
  170. {
  171. _logger.LogError(ex, "Error registering endpoint");
  172. }
  173. }
  174. private void RegisterServerEndpoints()
  175. {
  176. var udn = CreateUuid(_appHost.SystemId);
  177. var descriptorUri = "/dlna/" + udn + "/description.xml";
  178. // Only get bind addresses in LAN
  179. // IPv6 is currently unsupported
  180. var validInterfaces = _networkManager.GetInternalBindAddresses()
  181. .Where(x => x.Address is not null)
  182. .Where(x => x.AddressFamily != AddressFamily.InterNetworkV6)
  183. .ToList();
  184. if (validInterfaces.Count == 0)
  185. {
  186. // No interfaces returned, fall back to loopback
  187. validInterfaces = _networkManager.GetLoopbacks().ToList();
  188. }
  189. foreach (var intf in validInterfaces)
  190. {
  191. var fullService = "urn:schemas-upnp-org:device:MediaServer:1";
  192. _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, intf.Address);
  193. var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(intf.Address, false) + descriptorUri);
  194. var device = new SsdpRootDevice
  195. {
  196. CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info.
  197. Location = uri.Uri, // Must point to the URL that serves your devices UPnP description document.
  198. Address = intf.Address,
  199. PrefixLength = NetworkExtensions.MaskToCidr(intf.Subnet.BaseAddress),
  200. FriendlyName = "Jellyfin",
  201. Manufacturer = "Jellyfin",
  202. ModelName = "Jellyfin Server",
  203. Uuid = udn
  204. // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc.
  205. };
  206. SetProperties(device, fullService);
  207. _publisher.AddDevice(device);
  208. var embeddedDevices = new[]
  209. {
  210. "urn:schemas-upnp-org:service:ContentDirectory:1",
  211. "urn:schemas-upnp-org:service:ConnectionManager:1",
  212. // "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1"
  213. };
  214. foreach (var subDevice in embeddedDevices)
  215. {
  216. var embeddedDevice = new SsdpEmbeddedDevice
  217. {
  218. FriendlyName = device.FriendlyName,
  219. Manufacturer = device.Manufacturer,
  220. ModelName = device.ModelName,
  221. Uuid = udn
  222. // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc.
  223. };
  224. SetProperties(embeddedDevice, subDevice);
  225. device.AddDevice(embeddedDevice);
  226. }
  227. }
  228. }
  229. private static string CreateUuid(string text)
  230. {
  231. if (!Guid.TryParse(text, out var guid))
  232. {
  233. guid = text.GetMD5();
  234. }
  235. return guid.ToString("D", CultureInfo.InvariantCulture);
  236. }
  237. private static void SetProperties(SsdpDevice device, string fullDeviceType)
  238. {
  239. var serviceParts = fullDeviceType
  240. .Replace("urn:", string.Empty, StringComparison.OrdinalIgnoreCase)
  241. .Replace(":1", string.Empty, StringComparison.OrdinalIgnoreCase)
  242. .Split(':');
  243. device.DeviceTypeNamespace = serviceParts[0].Replace('.', '-');
  244. device.DeviceClass = serviceParts[1];
  245. device.DeviceType = serviceParts[2];
  246. }
  247. private void StartPlayToManager()
  248. {
  249. lock (_syncLock)
  250. {
  251. if (_manager is not null)
  252. {
  253. return;
  254. }
  255. try
  256. {
  257. _manager = new PlayToManager(
  258. _logger,
  259. _sessionManager,
  260. _libraryManager,
  261. _userManager,
  262. _dlnaManager,
  263. _appHost,
  264. _imageProcessor,
  265. _deviceDiscovery,
  266. _httpClientFactory,
  267. _userDataManager,
  268. _localization,
  269. _mediaSourceManager,
  270. _mediaEncoder);
  271. _manager.Start();
  272. }
  273. catch (Exception ex)
  274. {
  275. _logger.LogError(ex, "Error starting PlayTo manager");
  276. }
  277. }
  278. }
  279. private void DisposePlayToManager()
  280. {
  281. lock (_syncLock)
  282. {
  283. if (_manager is not null)
  284. {
  285. try
  286. {
  287. _logger.LogInformation("Disposing PlayToManager");
  288. _manager.Dispose();
  289. }
  290. catch (Exception ex)
  291. {
  292. _logger.LogError(ex, "Error disposing PlayTo manager");
  293. }
  294. _manager = null;
  295. }
  296. }
  297. }
  298. public void DisposeDevicePublisher()
  299. {
  300. if (_publisher is not null)
  301. {
  302. _logger.LogInformation("Disposing SsdpDevicePublisher");
  303. _publisher.Dispose();
  304. _publisher = null;
  305. }
  306. }
  307. /// <inheritdoc />
  308. public void Dispose()
  309. {
  310. if (_disposed)
  311. {
  312. return;
  313. }
  314. DisposeDevicePublisher();
  315. DisposePlayToManager();
  316. _disposed = true;
  317. }
  318. }
  319. }