SatIpDiscovery.cs 11 KB

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