DlnaEntryPoint.cs 15 KB

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