SatIpDiscovery.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. private int _tunerCountDVBS=0;
  29. private int _tunerCountDVBC=0;
  30. private int _tunerCountDVBT=0;
  31. private bool _supportsDVBS=false;
  32. private bool _supportsDVBC=false;
  33. private bool _supportsDVBT=false;
  34. public static SatIpDiscovery Current;
  35. public SatIpDiscovery(IDeviceDiscovery deviceDiscovery, IServerConfigurationManager config, ILogger logger, ILiveTvManager liveTvManager, IHttpClient httpClient, IJsonSerializer json)
  36. {
  37. _deviceDiscovery = deviceDiscovery;
  38. _config = config;
  39. _logger = logger;
  40. _liveTvManager = liveTvManager;
  41. _httpClient = httpClient;
  42. _json = json;
  43. Current = this;
  44. }
  45. public void Run()
  46. {
  47. _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
  48. }
  49. void _deviceDiscovery_DeviceDiscovered(object sender, SsdpMessageEventArgs e)
  50. {
  51. string st = null;
  52. string nt = null;
  53. e.Headers.TryGetValue("ST", out st);
  54. e.Headers.TryGetValue("NT", out nt);
  55. if (string.Equals(st, "urn:ses-com:device:SatIPServer:1", StringComparison.OrdinalIgnoreCase) ||
  56. string.Equals(nt, "urn:ses-com:device:SatIPServer:1", StringComparison.OrdinalIgnoreCase))
  57. {
  58. string location;
  59. if (e.Headers.TryGetValue("Location", out location) && !string.IsNullOrWhiteSpace(location))
  60. {
  61. _logger.Debug("SAT IP found at {0}", location);
  62. // Just get the beginning of the url
  63. Uri uri;
  64. if (Uri.TryCreate(location, UriKind.Absolute, out uri))
  65. {
  66. var apiUrl = location.Replace(uri.LocalPath, String.Empty, StringComparison.OrdinalIgnoreCase)
  67. .TrimEnd('/');
  68. AddDevice(apiUrl, location);
  69. }
  70. }
  71. }
  72. }
  73. private async void AddDevice(string deviceUrl, string infoUrl)
  74. {
  75. await _semaphore.WaitAsync().ConfigureAwait(false);
  76. try
  77. {
  78. var options = GetConfiguration();
  79. if (options.TunerHosts.Any(i => string.Equals(i.Type, SatIpHost.DeviceType, StringComparison.OrdinalIgnoreCase) && UriEquals(i.Url, deviceUrl)))
  80. {
  81. return;
  82. }
  83. _logger.Debug("Will attempt to add SAT device {0}", deviceUrl);
  84. var info = await GetInfo(infoUrl, CancellationToken.None).ConfigureAwait(false);
  85. var existing = GetConfiguration().TunerHosts
  86. .FirstOrDefault(i => string.Equals(i.Type, SatIpHost.DeviceType, StringComparison.OrdinalIgnoreCase) && string.Equals(i.DeviceId, info.DeviceId, StringComparison.OrdinalIgnoreCase));
  87. if (existing == null)
  88. {
  89. //if (string.IsNullOrWhiteSpace(info.M3UUrl))
  90. //{
  91. // return;
  92. //}
  93. await _liveTvManager.SaveTunerHost(new TunerHostInfo
  94. {
  95. Type = SatIpHost.DeviceType,
  96. Url = deviceUrl,
  97. InfoUrl = infoUrl,
  98. DataVersion = 1,
  99. DeviceId = info.DeviceId,
  100. FriendlyName = info.FriendlyName,
  101. Tuners = info.Tuners,
  102. M3UUrl = info.M3UUrl,
  103. IsEnabled = true
  104. }, true).ConfigureAwait(false);
  105. }
  106. else
  107. {
  108. existing.Url = deviceUrl;
  109. existing.InfoUrl = infoUrl;
  110. existing.M3UUrl = info.M3UUrl;
  111. existing.FriendlyName = info.FriendlyName;
  112. existing.Tuners = info.Tuners;
  113. await _liveTvManager.SaveTunerHost(existing, false).ConfigureAwait(false);
  114. }
  115. }
  116. catch (OperationCanceledException)
  117. {
  118. }
  119. catch (NotImplementedException)
  120. {
  121. }
  122. catch (Exception ex)
  123. {
  124. _logger.ErrorException("Error saving device", ex);
  125. }
  126. finally
  127. {
  128. _semaphore.Release();
  129. }
  130. }
  131. private bool UriEquals(string savedUri, string location)
  132. {
  133. return string.Equals(NormalizeUrl(location), NormalizeUrl(savedUri), StringComparison.OrdinalIgnoreCase);
  134. }
  135. private string NormalizeUrl(string url)
  136. {
  137. if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  138. {
  139. url = "http://" + url;
  140. }
  141. url = url.TrimEnd('/');
  142. // Strip off the port
  143. return new Uri(url).GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Port, UriFormat.UriEscaped);
  144. }
  145. private LiveTvOptions GetConfiguration()
  146. {
  147. return _config.GetConfiguration<LiveTvOptions>("livetv");
  148. }
  149. public void Dispose()
  150. {
  151. }
  152. private void ReadCapability(string capability)
  153. {
  154. string[] cap = capability.Split('-');
  155. switch (cap[0].ToLower())
  156. {
  157. case "dvbs":
  158. case "dvbs2":
  159. {
  160. // Optional that you know what an device Supports can you add an flag
  161. _supportsDVBS = true;
  162. for (int i = 0; i < int.Parse(cap[1]); i++)
  163. {
  164. //ToDo Create Digital Recorder / Tuner Capture Instance here for each with index FE param in Sat>Ip Spec for direct communication with this instance
  165. }
  166. _tunerCountDVBS = int.Parse(cap[1]);
  167. break;
  168. }
  169. case "dvbc":
  170. case "dvbc2":
  171. {
  172. // Optional that you know what an device Supports can you add an flag
  173. _supportsDVBC = true;
  174. for (int i = 0; i < int.Parse(cap[1]); i++)
  175. {
  176. //ToDo Create Digital Recorder / Tuner Capture Instance here for each with index FE param in Sat>Ip Spec for direct communication with this instance
  177. }
  178. _tunerCountDVBC = int.Parse(cap[1]);
  179. break;
  180. }
  181. case "dvbt":
  182. case "dvbt2":
  183. {
  184. // Optional that you know what an device Supports can you add an flag
  185. _supportsDVBT = true;
  186. for (int i = 0; i < int.Parse(cap[1]); i++)
  187. {
  188. //ToDo Create Digital Recorder / Tuner Capture Instance here for each with index FE param in Sat>Ip Spec for direct communication with this instance
  189. }
  190. _tunerCountDVBT = int.Parse(cap[1]);
  191. break;
  192. }
  193. }
  194. }
  195. public async Task<SatIpTunerHostInfo> GetInfo(string url, CancellationToken cancellationToken)
  196. {
  197. Uri locationUri = new Uri(url);
  198. string devicetype = "";
  199. string friendlyname = "";
  200. string uniquedevicename = "";
  201. string manufacturer = "";
  202. string manufacturerurl = "";
  203. string modelname = "";
  204. string modeldescription = "";
  205. string modelnumber = "";
  206. string modelurl = "";
  207. string serialnumber = "";
  208. string presentationurl = "";
  209. string capabilities = "";
  210. string m3u = "";
  211. var document = XDocument.Load(locationUri.AbsoluteUri);
  212. var xnm = new XmlNamespaceManager(new NameTable());
  213. XNamespace n1 = "urn:ses-com:satip";
  214. XNamespace n0 = "urn:schemas-upnp-org:device-1-0";
  215. xnm.AddNamespace("root", n0.NamespaceName);
  216. xnm.AddNamespace("satip:", n1.NamespaceName);
  217. if (document.Root != null)
  218. {
  219. var deviceElement = document.Root.Element(n0 + "device");
  220. if (deviceElement != null)
  221. {
  222. var devicetypeElement = deviceElement.Element(n0 + "deviceType");
  223. if (devicetypeElement != null)
  224. devicetype = devicetypeElement.Value;
  225. var friendlynameElement = deviceElement.Element(n0 + "friendlyName");
  226. if (friendlynameElement != null)
  227. friendlyname = friendlynameElement.Value;
  228. var manufactureElement = deviceElement.Element(n0 + "manufacturer");
  229. if (manufactureElement != null)
  230. manufacturer = manufactureElement.Value;
  231. var manufactureurlElement = deviceElement.Element(n0 + "manufacturerURL");
  232. if (manufactureurlElement != null)
  233. manufacturerurl = manufactureurlElement.Value;
  234. var modeldescriptionElement = deviceElement.Element(n0 + "modelDescription");
  235. if (modeldescriptionElement != null)
  236. modeldescription = modeldescriptionElement.Value;
  237. var modelnameElement = deviceElement.Element(n0 + "modelName");
  238. if (modelnameElement != null)
  239. modelname = modelnameElement.Value;
  240. var modelnumberElement = deviceElement.Element(n0 + "modelNumber");
  241. if (modelnumberElement != null)
  242. modelnumber = modelnumberElement.Value;
  243. var modelurlElement = deviceElement.Element(n0 + "modelURL");
  244. if (modelurlElement != null)
  245. modelurl = modelurlElement.Value;
  246. var serialnumberElement = deviceElement.Element(n0 + "serialNumber");
  247. if (serialnumberElement != null)
  248. serialnumber = serialnumberElement.Value;
  249. var uniquedevicenameElement = deviceElement.Element(n0 + "UDN");
  250. if (uniquedevicenameElement != null) uniquedevicename = uniquedevicenameElement.Value;
  251. var presentationUrlElement = deviceElement.Element(n0 + "presentationURL");
  252. if (presentationUrlElement != null) presentationurl = presentationUrlElement.Value;
  253. var capabilitiesElement = deviceElement.Element(n1 + "X_SATIPCAP");
  254. if (capabilitiesElement != null)
  255. {
  256. //_capabilities = capabilitiesElement.Value;
  257. //if (capabilitiesElement.Value.Contains(','))
  258. //{
  259. // string[] capabilities = capabilitiesElement.Value.Split(',');
  260. // foreach (var capability in capabilities)
  261. // {
  262. // ReadCapability(capability);
  263. // }
  264. //}
  265. //else
  266. //{
  267. // ReadCapability(capabilitiesElement.Value);
  268. //}
  269. }
  270. else
  271. {
  272. _supportsDVBS = true;
  273. _tunerCountDVBS =1;
  274. }
  275. var m3uElement = deviceElement.Element(n1 + "X_SATIPM3U");
  276. if (m3uElement != null) m3u = m3uElement.Value;
  277. }
  278. }
  279. var result = new SatIpTunerHostInfo
  280. {
  281. Url = url,
  282. Id = uniquedevicename,
  283. IsEnabled = true,
  284. Type = SatIpHost.DeviceType,
  285. Tuners = 1,
  286. TunersAvailable = 1,
  287. M3UUrl = m3u
  288. };
  289. result.FriendlyName = friendlyname;
  290. if (string.IsNullOrWhiteSpace(result.Id))
  291. {
  292. throw new NotImplementedException();
  293. }
  294. else if (!result.M3UUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  295. {
  296. var fullM3uUrl = url.Substring(0, url.LastIndexOf('/'));
  297. result.M3UUrl = fullM3uUrl + "/" + result.M3UUrl.TrimStart('/');
  298. }
  299. _logger.Debug("SAT device result: {0}", _json.SerializeToString(result));
  300. return result;
  301. }
  302. }
  303. public class SatIpTunerHostInfo : TunerHostInfo
  304. {
  305. public int TunersAvailable { get; set; }
  306. }
  307. }