DlnaEntryPoint.cs 14 KB

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