SatIpDiscovery.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using System.Xml;
  10. using MediaBrowser.Common.Configuration;
  11. using MediaBrowser.Common.Extensions;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Controller.Configuration;
  14. using MediaBrowser.Controller.Dlna;
  15. using MediaBrowser.Controller.LiveTv;
  16. using MediaBrowser.Controller.Plugins;
  17. using MediaBrowser.Model.LiveTv;
  18. using MediaBrowser.Model.Logging;
  19. using MediaBrowser.Model.Serialization;
  20. namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp
  21. {
  22. public class SatIpDiscovery : IServerEntryPoint
  23. {
  24. private readonly IDeviceDiscovery _deviceDiscovery;
  25. private readonly IServerConfigurationManager _config;
  26. private readonly ILogger _logger;
  27. private readonly ILiveTvManager _liveTvManager;
  28. private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
  29. private readonly IHttpClient _httpClient;
  30. private readonly IJsonSerializer _json;
  31. public static SatIpDiscovery Current;
  32. public SatIpDiscovery(IDeviceDiscovery deviceDiscovery, IServerConfigurationManager config, ILogger logger, ILiveTvManager liveTvManager, IHttpClient httpClient, IJsonSerializer json)
  33. {
  34. _deviceDiscovery = deviceDiscovery;
  35. _config = config;
  36. _logger = logger;
  37. _liveTvManager = liveTvManager;
  38. _httpClient = httpClient;
  39. _json = json;
  40. Current = this;
  41. }
  42. public void Run()
  43. {
  44. _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
  45. }
  46. void _deviceDiscovery_DeviceDiscovered(object sender, SsdpMessageEventArgs e)
  47. {
  48. string st = null;
  49. string nt = null;
  50. e.Headers.TryGetValue("ST", out st);
  51. e.Headers.TryGetValue("NT", out nt);
  52. if (string.Equals(st, "urn:ses-com:device:SatIPServer:1", StringComparison.OrdinalIgnoreCase) ||
  53. string.Equals(nt, "urn:ses-com:device:SatIPServer:1", StringComparison.OrdinalIgnoreCase))
  54. {
  55. string location;
  56. if (e.Headers.TryGetValue("Location", out location) && !string.IsNullOrWhiteSpace(location))
  57. {
  58. _logger.Debug("SAT IP found at {0}", location);
  59. // Just get the beginning of the url
  60. AddDevice(location);
  61. }
  62. }
  63. }
  64. private async void AddDevice(string location)
  65. {
  66. await _semaphore.WaitAsync().ConfigureAwait(false);
  67. try
  68. {
  69. var options = GetConfiguration();
  70. if (options.TunerHosts.Any(i => string.Equals(i.Type, SatIpHost.DeviceType, StringComparison.OrdinalIgnoreCase) && UriEquals(i.Url, location)))
  71. {
  72. return;
  73. }
  74. _logger.Debug("Will attempt to add SAT device {0}", location);
  75. var info = await GetInfo(location, CancellationToken.None).ConfigureAwait(false);
  76. var existing = GetConfiguration().TunerHosts
  77. .FirstOrDefault(i => string.Equals(i.Type, SatIpHost.DeviceType, StringComparison.OrdinalIgnoreCase) && string.Equals(i.DeviceId, info.DeviceId, StringComparison.OrdinalIgnoreCase));
  78. if (existing == null)
  79. {
  80. await _liveTvManager.SaveTunerHost(new TunerHostInfo
  81. {
  82. Type = SatIpHost.DeviceType,
  83. Url = location,
  84. DataVersion = 1,
  85. DeviceId = info.DeviceId,
  86. FriendlyName = info.FriendlyName,
  87. Tuners = info.Tuners
  88. }).ConfigureAwait(false);
  89. }
  90. else
  91. {
  92. if (!string.Equals(existing.Url, location, StringComparison.OrdinalIgnoreCase))
  93. {
  94. existing.Url = location;
  95. existing.M3UUrl = info.M3UUrl;
  96. existing.FriendlyName = info.FriendlyName;
  97. existing.Tuners = info.Tuners;
  98. await _liveTvManager.SaveTunerHost(existing).ConfigureAwait(false);
  99. }
  100. }
  101. }
  102. catch (OperationCanceledException)
  103. {
  104. }
  105. catch (NotImplementedException)
  106. {
  107. }
  108. catch (Exception ex)
  109. {
  110. _logger.ErrorException("Error saving device", ex);
  111. }
  112. finally
  113. {
  114. _semaphore.Release();
  115. }
  116. }
  117. private bool UriEquals(string savedUri, string location)
  118. {
  119. return string.Equals(NormalizeUrl(location), NormalizeUrl(savedUri), StringComparison.OrdinalIgnoreCase);
  120. }
  121. private string NormalizeUrl(string url)
  122. {
  123. if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  124. {
  125. url = "http://" + url;
  126. }
  127. url = url.TrimEnd('/');
  128. // Strip off the port
  129. return new Uri(url).GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Port, UriFormat.UriEscaped);
  130. }
  131. private LiveTvOptions GetConfiguration()
  132. {
  133. return _config.GetConfiguration<LiveTvOptions>("livetv");
  134. }
  135. public void Dispose()
  136. {
  137. }
  138. public async Task<SatIpTunerHostInfo> GetInfo(string url, CancellationToken cancellationToken)
  139. {
  140. var result = new SatIpTunerHostInfo
  141. {
  142. Url = url,
  143. IsEnabled = true,
  144. Type = SatIpHost.DeviceType,
  145. Tuners = 1,
  146. TunersAvailable = 1
  147. };
  148. using (var stream = await _httpClient.Get(url, cancellationToken).ConfigureAwait(false))
  149. {
  150. using (var streamReader = new StreamReader(stream))
  151. {
  152. // Use XmlReader for best performance
  153. using (var reader = XmlReader.Create(streamReader))
  154. {
  155. reader.MoveToContent();
  156. // Loop through each element
  157. while (reader.Read())
  158. {
  159. if (reader.NodeType == XmlNodeType.Element)
  160. {
  161. switch (reader.Name)
  162. {
  163. case "device":
  164. using (var subtree = reader.ReadSubtree())
  165. {
  166. FillFromDeviceNode(result, subtree);
  167. }
  168. break;
  169. default:
  170. reader.Skip();
  171. break;
  172. }
  173. }
  174. }
  175. }
  176. }
  177. }
  178. if (string.IsNullOrWhiteSpace(result.DeviceId))
  179. {
  180. throw new NotImplementedException();
  181. }
  182. // Device hasn't implemented an m3u list
  183. if (string.IsNullOrWhiteSpace(result.M3UUrl))
  184. {
  185. result.IsEnabled = false;
  186. }
  187. else if (!result.M3UUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  188. {
  189. var fullM3uUrl = url.Substring(0, url.LastIndexOf('/'));
  190. result.M3UUrl = fullM3uUrl + "/" + result.M3UUrl.TrimStart('/');
  191. }
  192. _logger.Debug("SAT device result: {0}", _json.SerializeToString(result));
  193. return result;
  194. }
  195. private void FillFromDeviceNode(SatIpTunerHostInfo info, XmlReader reader)
  196. {
  197. reader.MoveToContent();
  198. while (reader.Read())
  199. {
  200. if (reader.NodeType == XmlNodeType.Element)
  201. {
  202. switch (reader.LocalName)
  203. {
  204. case "UDN":
  205. {
  206. info.DeviceId = reader.ReadElementContentAsString();
  207. break;
  208. }
  209. case "friendlyName":
  210. {
  211. info.FriendlyName = reader.ReadElementContentAsString();
  212. break;
  213. }
  214. case "satip:X_SATIPCAP":
  215. case "X_SATIPCAP":
  216. {
  217. // <satip:X_SATIPCAP xmlns:satip="urn:ses-com:satip">DVBS2-2</satip:X_SATIPCAP>
  218. var value = reader.ReadElementContentAsString() ?? string.Empty;
  219. var parts = value.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
  220. if (parts.Length == 2)
  221. {
  222. int intValue;
  223. if (int.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out intValue))
  224. {
  225. info.TunersAvailable = intValue;
  226. }
  227. if (int.TryParse(parts[0].Substring(parts[0].Length - 1), NumberStyles.Any, CultureInfo.InvariantCulture, out intValue))
  228. {
  229. info.Tuners = intValue;
  230. }
  231. }
  232. break;
  233. }
  234. case "satip:X_SATIPM3U":
  235. case "X_SATIPM3U":
  236. {
  237. // <satip:X_SATIPM3U xmlns:satip="urn:ses-com:satip">/channellist.lua?select=m3u</satip:X_SATIPM3U>
  238. info.M3UUrl = reader.ReadElementContentAsString();
  239. break;
  240. }
  241. default:
  242. reader.Skip();
  243. break;
  244. }
  245. }
  246. }
  247. }
  248. }
  249. public class SatIpTunerHostInfo : TunerHostInfo
  250. {
  251. public int TunersAvailable { get; set; }
  252. }
  253. }