DlnaEntryPoint.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Dlna;
  7. using MediaBrowser.Controller.Drawing;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.Localization;
  10. using MediaBrowser.Controller.Plugins;
  11. using MediaBrowser.Controller.Session;
  12. using MediaBrowser.Dlna.PlayTo;
  13. using MediaBrowser.Dlna.Ssdp;
  14. using MediaBrowser.Model.Logging;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Linq;
  18. using System.Threading.Tasks;
  19. using MediaBrowser.Controller.MediaEncoding;
  20. using Rssdp;
  21. namespace MediaBrowser.Dlna.Main
  22. {
  23. public class DlnaEntryPoint : IServerEntryPoint
  24. {
  25. private readonly IServerConfigurationManager _config;
  26. private readonly ILogger _logger;
  27. private readonly IServerApplicationHost _appHost;
  28. private readonly INetworkManager _network;
  29. private PlayToManager _manager;
  30. private readonly ISessionManager _sessionManager;
  31. private readonly IHttpClient _httpClient;
  32. private readonly ILibraryManager _libraryManager;
  33. private readonly IUserManager _userManager;
  34. private readonly IDlnaManager _dlnaManager;
  35. private readonly IImageProcessor _imageProcessor;
  36. private readonly IUserDataManager _userDataManager;
  37. private readonly ILocalizationManager _localization;
  38. private readonly IMediaSourceManager _mediaSourceManager;
  39. private readonly IMediaEncoder _mediaEncoder;
  40. private readonly IDeviceDiscovery _deviceDiscovery;
  41. private bool _ssdpHandlerStarted;
  42. private bool _dlnaServerStarted;
  43. private SsdpDevicePublisher _Publisher;
  44. public DlnaEntryPoint(IServerConfigurationManager config,
  45. ILogManager logManager,
  46. IServerApplicationHost appHost,
  47. INetworkManager network,
  48. ISessionManager sessionManager,
  49. IHttpClient httpClient,
  50. ILibraryManager libraryManager,
  51. IUserManager userManager,
  52. IDlnaManager dlnaManager,
  53. IImageProcessor imageProcessor,
  54. IUserDataManager userDataManager,
  55. ILocalizationManager localization,
  56. IMediaSourceManager mediaSourceManager,
  57. IDeviceDiscovery deviceDiscovery, IMediaEncoder mediaEncoder)
  58. {
  59. _config = config;
  60. _appHost = appHost;
  61. _network = network;
  62. _sessionManager = sessionManager;
  63. _httpClient = httpClient;
  64. _libraryManager = libraryManager;
  65. _userManager = userManager;
  66. _dlnaManager = dlnaManager;
  67. _imageProcessor = imageProcessor;
  68. _userDataManager = userDataManager;
  69. _localization = localization;
  70. _mediaSourceManager = mediaSourceManager;
  71. _deviceDiscovery = deviceDiscovery;
  72. _mediaEncoder = mediaEncoder;
  73. _logger = logManager.GetLogger("Dlna");
  74. }
  75. public void Run()
  76. {
  77. ((DlnaManager)_dlnaManager).InitProfiles();
  78. ReloadComponents();
  79. _config.ConfigurationUpdated += _config_ConfigurationUpdated;
  80. _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
  81. }
  82. private bool _lastEnableUpnP;
  83. void _config_ConfigurationUpdated(object sender, EventArgs e)
  84. {
  85. if (_lastEnableUpnP != _config.Configuration.EnableUPnP)
  86. {
  87. ReloadComponents();
  88. }
  89. _lastEnableUpnP = _config.Configuration.EnableUPnP;
  90. }
  91. void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  92. {
  93. if (string.Equals(e.Key, "dlna", StringComparison.OrdinalIgnoreCase))
  94. {
  95. ReloadComponents();
  96. }
  97. }
  98. private async void ReloadComponents()
  99. {
  100. var options = _config.GetDlnaConfiguration();
  101. if (!_ssdpHandlerStarted)
  102. {
  103. StartSsdpHandler();
  104. }
  105. var isServerStarted = _dlnaServerStarted;
  106. if (options.EnableServer && !isServerStarted)
  107. {
  108. await StartDlnaServer().ConfigureAwait(false);
  109. }
  110. else if (!options.EnableServer && isServerStarted)
  111. {
  112. DisposeDlnaServer();
  113. }
  114. var isPlayToStarted = _manager != null;
  115. if (options.EnablePlayTo && !isPlayToStarted)
  116. {
  117. StartPlayToManager();
  118. }
  119. else if (!options.EnablePlayTo && isPlayToStarted)
  120. {
  121. DisposePlayToManager();
  122. }
  123. }
  124. private void StartSsdpHandler()
  125. {
  126. try
  127. {
  128. StartPublishing();
  129. _ssdpHandlerStarted = true;
  130. StartDeviceDiscovery();
  131. }
  132. catch (Exception ex)
  133. {
  134. _logger.ErrorException("Error starting ssdp handlers", ex);
  135. }
  136. }
  137. private void StartPublishing()
  138. {
  139. _Publisher = new SsdpDevicePublisher();
  140. }
  141. private void StartDeviceDiscovery()
  142. {
  143. try
  144. {
  145. ((DeviceDiscovery)_deviceDiscovery).Start();
  146. }
  147. catch (Exception ex)
  148. {
  149. _logger.ErrorException("Error starting device discovery", ex);
  150. }
  151. }
  152. private void DisposeDeviceDiscovery()
  153. {
  154. try
  155. {
  156. ((DeviceDiscovery)_deviceDiscovery).Dispose();
  157. }
  158. catch (Exception ex)
  159. {
  160. _logger.ErrorException("Error stopping device discovery", ex);
  161. }
  162. }
  163. private void DisposeSsdpHandler()
  164. {
  165. DisposeDeviceDiscovery();
  166. try
  167. {
  168. ((DeviceDiscovery)_deviceDiscovery).Dispose();
  169. _ssdpHandlerStarted = false;
  170. }
  171. catch (Exception ex)
  172. {
  173. _logger.ErrorException("Error stopping ssdp handlers", ex);
  174. }
  175. }
  176. public async Task StartDlnaServer()
  177. {
  178. try
  179. {
  180. await RegisterServerEndpoints().ConfigureAwait(false);
  181. _dlnaServerStarted = true;
  182. }
  183. catch (Exception ex)
  184. {
  185. _logger.ErrorException("Error registering endpoint", ex);
  186. }
  187. }
  188. private async Task RegisterServerEndpoints()
  189. {
  190. if (!_config.GetDlnaConfiguration().BlastAliveMessages)
  191. {
  192. return;
  193. }
  194. var cacheLength = _config.GetDlnaConfiguration().BlastAliveMessageIntervalSeconds * 2;
  195. _Publisher.SupportPnpRootDevice = true;
  196. foreach (var address in await _appHost.GetLocalIpAddresses().ConfigureAwait(false))
  197. {
  198. //if (IPAddress.IsLoopback(address))
  199. //{
  200. // // Should we allow this?
  201. // continue;
  202. //}
  203. var addressString = address.ToString();
  204. var services = new List<string>
  205. {
  206. "urn:schemas-upnp-org:device:MediaServer:1",
  207. "urn:schemas-upnp-org:service:ContentDirectory:1",
  208. "urn:schemas-upnp-org:service:ConnectionManager:1",
  209. "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1"
  210. };
  211. var udn = (addressString).GetMD5().ToString("N");
  212. foreach (var fullService in services)
  213. {
  214. _logger.Info("Registering publisher for {0} on {1}", fullService, addressString);
  215. var descriptorURI = "/dlna/" + udn + "/description.xml";
  216. var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorURI);
  217. var service = fullService.Replace("urn:", string.Empty).Replace(":1", string.Empty);
  218. var serviceParts = service.Split(':');
  219. var deviceTypeNamespace = serviceParts[0].Replace('.', '-');
  220. _Publisher.AddDevice(new SsdpRootDevice
  221. {
  222. CacheLifetime = TimeSpan.FromSeconds(cacheLength), //How long SSDP clients can cache this info.
  223. Location = uri, // Must point to the URL that serves your devices UPnP description document.
  224. DeviceTypeNamespace = deviceTypeNamespace,
  225. DeviceClass = serviceParts[1],
  226. DeviceType = serviceParts[2],
  227. FriendlyName = "Emby Server",
  228. Manufacturer = "Emby",
  229. ModelName = "Emby Server",
  230. Uuid = udn // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc.
  231. });
  232. }
  233. }
  234. }
  235. private readonly object _syncLock = new object();
  236. private void StartPlayToManager()
  237. {
  238. lock (_syncLock)
  239. {
  240. try
  241. {
  242. _manager = new PlayToManager(_logger,
  243. _sessionManager,
  244. _libraryManager,
  245. _userManager,
  246. _dlnaManager,
  247. _appHost,
  248. _imageProcessor,
  249. _deviceDiscovery,
  250. _httpClient,
  251. _config,
  252. _userDataManager,
  253. _localization,
  254. _mediaSourceManager,
  255. _mediaEncoder);
  256. _manager.Start();
  257. }
  258. catch (Exception ex)
  259. {
  260. _logger.ErrorException("Error starting PlayTo manager", ex);
  261. }
  262. }
  263. }
  264. private void DisposePlayToManager()
  265. {
  266. lock (_syncLock)
  267. {
  268. if (_manager != null)
  269. {
  270. try
  271. {
  272. _manager.Dispose();
  273. }
  274. catch (Exception ex)
  275. {
  276. _logger.ErrorException("Error disposing PlayTo manager", ex);
  277. }
  278. _manager = null;
  279. }
  280. }
  281. }
  282. public void Dispose()
  283. {
  284. DisposeDlnaServer();
  285. DisposePlayToManager();
  286. DisposeSsdpHandler();
  287. }
  288. public void DisposeDlnaServer()
  289. {
  290. if (_Publisher != null)
  291. {
  292. var devices = _Publisher.Devices.ToList();
  293. Parallel.ForEach(devices, device =>
  294. {
  295. try
  296. {
  297. _Publisher.RemoveDevice(device);
  298. }
  299. catch (Exception ex)
  300. {
  301. _logger.ErrorException("Error sending bye bye", ex);
  302. }
  303. });
  304. //foreach (var device in devices)
  305. //{
  306. // try
  307. // {
  308. // _Publisher.RemoveDevice(device);
  309. // }
  310. // catch (Exception ex)
  311. // {
  312. // _logger.ErrorException("Error sending bye bye", ex);
  313. // }
  314. //}
  315. _Publisher.Dispose();
  316. }
  317. _dlnaServerStarted = false;
  318. }
  319. }
  320. }