SatIpDiscovery.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. using System;
  2. using System.Linq;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using System.Xml;
  6. using MediaBrowser.Common.Configuration;
  7. using MediaBrowser.Common.Net;
  8. using MediaBrowser.Controller.Configuration;
  9. using MediaBrowser.Controller.Dlna;
  10. using MediaBrowser.Controller.LiveTv;
  11. using MediaBrowser.Controller.Plugins;
  12. using MediaBrowser.Model.LiveTv;
  13. using MediaBrowser.Model.Logging;
  14. using MediaBrowser.Model.Serialization;
  15. using MediaBrowser.Model.Extensions;
  16. using System.Xml.Linq;
  17. namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp
  18. {
  19. public class SatIpDiscovery : IServerEntryPoint
  20. {
  21. private readonly IDeviceDiscovery _deviceDiscovery;
  22. private readonly IServerConfigurationManager _config;
  23. private readonly ILogger _logger;
  24. private readonly ILiveTvManager _liveTvManager;
  25. private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
  26. private readonly IHttpClient _httpClient;
  27. private readonly IJsonSerializer _json;
  28. public static SatIpDiscovery Current;
  29. public SatIpDiscovery(IDeviceDiscovery deviceDiscovery, IServerConfigurationManager config, ILogger logger, ILiveTvManager liveTvManager, IHttpClient httpClient, IJsonSerializer json)
  30. {
  31. _deviceDiscovery = deviceDiscovery;
  32. _config = config;
  33. _logger = logger;
  34. _liveTvManager = liveTvManager;
  35. _httpClient = httpClient;
  36. _json = json;
  37. Current = this;
  38. }
  39. public void Run()
  40. {
  41. _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
  42. }
  43. void _deviceDiscovery_DeviceDiscovered(object sender, SsdpMessageEventArgs e)
  44. {
  45. string st = null;
  46. string nt = null;
  47. e.Headers.TryGetValue("ST", out st);
  48. e.Headers.TryGetValue("NT", out nt);
  49. if (string.Equals(st, "urn:ses-com:device:SatIPServer:1", StringComparison.OrdinalIgnoreCase) ||
  50. string.Equals(nt, "urn:ses-com:device:SatIPServer:1", StringComparison.OrdinalIgnoreCase))
  51. {
  52. string location;
  53. if (e.Headers.TryGetValue("Location", out location) && !string.IsNullOrWhiteSpace(location))
  54. {
  55. _logger.Debug("SAT IP found at {0}", location);
  56. // Just get the beginning of the url
  57. Uri uri;
  58. if (Uri.TryCreate(location, UriKind.Absolute, out uri))
  59. {
  60. var apiUrl = location.Replace(uri.LocalPath, String.Empty, StringComparison.OrdinalIgnoreCase)
  61. .TrimEnd('/');
  62. AddDevice(apiUrl, location);
  63. }
  64. }
  65. }
  66. }
  67. private async void AddDevice(string deviceUrl, string infoUrl)
  68. {
  69. await _semaphore.WaitAsync().ConfigureAwait(false);
  70. try
  71. {
  72. var options = GetConfiguration();
  73. if (options.TunerHosts.Any(i => string.Equals(i.Type, SatIpHost.DeviceType, StringComparison.OrdinalIgnoreCase) && UriEquals(i.Url, deviceUrl)))
  74. {
  75. return;
  76. }
  77. _logger.Debug("Will attempt to add SAT device {0}", deviceUrl);
  78. var info = await GetInfo(infoUrl, CancellationToken.None).ConfigureAwait(false);
  79. var existing = GetConfiguration().TunerHosts
  80. .FirstOrDefault(i => string.Equals(i.Type, SatIpHost.DeviceType, StringComparison.OrdinalIgnoreCase) && string.Equals(i.DeviceId, info.DeviceId, StringComparison.OrdinalIgnoreCase));
  81. if (existing == null)
  82. {
  83. //if (string.IsNullOrWhiteSpace(info.M3UUrl))
  84. //{
  85. // return;
  86. //}
  87. await _liveTvManager.SaveTunerHost(new TunerHostInfo
  88. {
  89. Type = SatIpHost.DeviceType,
  90. Url = deviceUrl,
  91. InfoUrl = infoUrl,
  92. DataVersion = 1,
  93. DeviceId = info.DeviceId,
  94. FriendlyName = info.FriendlyName,
  95. Tuners = info.Tuners,
  96. M3UUrl = info.M3UUrl,
  97. IsEnabled = true
  98. }).ConfigureAwait(false);
  99. }
  100. else
  101. {
  102. existing.Url = deviceUrl;
  103. existing.InfoUrl = infoUrl;
  104. existing.M3UUrl = info.M3UUrl;
  105. existing.FriendlyName = info.FriendlyName;
  106. existing.Tuners = info.Tuners;
  107. await _liveTvManager.SaveTunerHost(existing).ConfigureAwait(false);
  108. }
  109. }
  110. catch (OperationCanceledException)
  111. {
  112. }
  113. catch (NotImplementedException)
  114. {
  115. }
  116. catch (Exception ex)
  117. {
  118. _logger.ErrorException("Error saving device", ex);
  119. }
  120. finally
  121. {
  122. _semaphore.Release();
  123. }
  124. }
  125. private bool UriEquals(string savedUri, string location)
  126. {
  127. return string.Equals(NormalizeUrl(location), NormalizeUrl(savedUri), StringComparison.OrdinalIgnoreCase);
  128. }
  129. private string NormalizeUrl(string url)
  130. {
  131. if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  132. {
  133. url = "http://" + url;
  134. }
  135. url = url.TrimEnd('/');
  136. // Strip off the port
  137. return new Uri(url).GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Port, UriFormat.UriEscaped);
  138. }
  139. private LiveTvOptions GetConfiguration()
  140. {
  141. return _config.GetConfiguration<LiveTvOptions>("livetv");
  142. }
  143. public void Dispose()
  144. {
  145. }
  146. public async Task<SatIpTunerHostInfo> GetInfo(string url, CancellationToken cancellationToken)
  147. {
  148. Uri locationUri = new Uri(url);
  149. string devicetype = "";
  150. string friendlyname = "";
  151. string uniquedevicename = "";
  152. string manufacturer = "";
  153. string manufacturerurl = "";
  154. string modelname = "";
  155. string modeldescription = "";
  156. string modelnumber = "";
  157. string modelurl = "";
  158. string serialnumber = "";
  159. string presentationurl = "";
  160. string capabilities = "";
  161. string m3u = "";
  162. var document = XDocument.Load(locationUri.AbsoluteUri);
  163. var xnm = new XmlNamespaceManager(new NameTable());
  164. XNamespace n1 = "urn:ses-com:satip";
  165. XNamespace n0 = "urn:schemas-upnp-org:device-1-0";
  166. xnm.AddNamespace("root", n0.NamespaceName);
  167. xnm.AddNamespace("satip:", n1.NamespaceName);
  168. if (document.Root != null)
  169. {
  170. var deviceElement = document.Root.Element(n0 + "device");
  171. if (deviceElement != null)
  172. {
  173. var devicetypeElement = deviceElement.Element(n0 + "deviceType");
  174. if (devicetypeElement != null)
  175. devicetype = devicetypeElement.Value;
  176. var friendlynameElement = deviceElement.Element(n0 + "friendlyName");
  177. if (friendlynameElement != null)
  178. friendlyname = friendlynameElement.Value;
  179. var manufactureElement = deviceElement.Element(n0 + "manufacturer");
  180. if (manufactureElement != null)
  181. manufacturer = manufactureElement.Value;
  182. var manufactureurlElement = deviceElement.Element(n0 + "manufacturerURL");
  183. if (manufactureurlElement != null)
  184. manufacturerurl = manufactureurlElement.Value;
  185. var modeldescriptionElement = deviceElement.Element(n0 + "modelDescription");
  186. if (modeldescriptionElement != null)
  187. modeldescription = modeldescriptionElement.Value;
  188. var modelnameElement = deviceElement.Element(n0 + "modelName");
  189. if (modelnameElement != null)
  190. modelname = modelnameElement.Value;
  191. var modelnumberElement = deviceElement.Element(n0 + "modelNumber");
  192. if (modelnumberElement != null)
  193. modelnumber = modelnumberElement.Value;
  194. var modelurlElement = deviceElement.Element(n0 + "modelURL");
  195. if (modelurlElement != null)
  196. modelurl = modelurlElement.Value;
  197. var serialnumberElement = deviceElement.Element(n0 + "serialNumber");
  198. if (serialnumberElement != null)
  199. serialnumber = serialnumberElement.Value;
  200. var uniquedevicenameElement = deviceElement.Element(n0 + "UDN");
  201. if (uniquedevicenameElement != null) uniquedevicename = uniquedevicenameElement.Value;
  202. var presentationUrlElement = deviceElement.Element(n0 + "presentationURL");
  203. if (presentationUrlElement != null) presentationurl = presentationUrlElement.Value;
  204. var capabilitiesElement = deviceElement.Element(n1 + "X_SATIPCAP");
  205. if (capabilitiesElement != null) capabilities = capabilitiesElement.Value;
  206. var m3uElement = deviceElement.Element(n1 + "X_SATIPM3U");
  207. if (m3uElement != null) m3u = m3uElement.Value;
  208. }
  209. }
  210. var result = new SatIpTunerHostInfo
  211. {
  212. Url = url,
  213. Id = uniquedevicename,
  214. IsEnabled = true,
  215. Type = SatIpHost.DeviceType,
  216. Tuners = 1,
  217. TunersAvailable = 1,
  218. M3UUrl = m3u
  219. };
  220. result.FriendlyName = friendlyname;
  221. if (string.IsNullOrWhiteSpace(result.Id))
  222. {
  223. throw new NotImplementedException();
  224. }
  225. else if (!result.M3UUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  226. {
  227. var fullM3uUrl = url.Substring(0, url.LastIndexOf('/'));
  228. result.M3UUrl = fullM3uUrl + "/" + result.M3UUrl.TrimStart('/');
  229. }
  230. _logger.Debug("SAT device result: {0}", _json.SerializeToString(result));
  231. return result;
  232. }
  233. }
  234. public class SatIpTunerHostInfo : TunerHostInfo
  235. {
  236. public int TunersAvailable { get; set; }
  237. }
  238. }