DlnaEntryPoint.cs 14 KB

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