M3uParser.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text.RegularExpressions;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Model.IO;
  10. using MediaBrowser.Common.Extensions;
  11. using MediaBrowser.Common.IO;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Controller;
  14. using MediaBrowser.Controller.IO;
  15. using MediaBrowser.Controller.LiveTv;
  16. using MediaBrowser.Model.Logging;
  17. namespace Emby.Server.Implementations.LiveTv.TunerHosts
  18. {
  19. public class M3uParser
  20. {
  21. private readonly ILogger _logger;
  22. private readonly IFileSystem _fileSystem;
  23. private readonly IHttpClient _httpClient;
  24. private readonly IServerApplicationHost _appHost;
  25. public M3uParser(ILogger logger, IFileSystem fileSystem, IHttpClient httpClient, IServerApplicationHost appHost)
  26. {
  27. _logger = logger;
  28. _fileSystem = fileSystem;
  29. _httpClient = httpClient;
  30. _appHost = appHost;
  31. }
  32. public async Task<List<M3UChannel>> Parse(string url, string channelIdPrefix, string tunerHostId, CancellationToken cancellationToken)
  33. {
  34. var urlHash = url.GetMD5().ToString("N");
  35. // Read the file and display it line by line.
  36. using (var reader = new StreamReader(await GetListingsStream(url, cancellationToken).ConfigureAwait(false)))
  37. {
  38. return GetChannels(reader, urlHash, channelIdPrefix, tunerHostId);
  39. }
  40. }
  41. public List<M3UChannel> ParseString(string text, string channelIdPrefix, string tunerHostId)
  42. {
  43. var urlHash = "text".GetMD5().ToString("N");
  44. // Read the file and display it line by line.
  45. using (var reader = new StringReader(text))
  46. {
  47. return GetChannels(reader, urlHash, channelIdPrefix, tunerHostId);
  48. }
  49. }
  50. public Task<Stream> GetListingsStream(string url, CancellationToken cancellationToken)
  51. {
  52. if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  53. {
  54. return _httpClient.Get(new HttpRequestOptions
  55. {
  56. Url = url,
  57. CancellationToken = cancellationToken,
  58. // Some data providers will require a user agent
  59. UserAgent = _appHost.FriendlyName + "/" + _appHost.ApplicationVersion
  60. });
  61. }
  62. return Task.FromResult(_fileSystem.OpenRead(url));
  63. }
  64. const string ExtInfPrefix = "#EXTINF:";
  65. private List<M3UChannel> GetChannels(TextReader reader, string urlHash, string channelIdPrefix, string tunerHostId)
  66. {
  67. var channels = new List<M3UChannel>();
  68. string line;
  69. string extInf = "";
  70. while ((line = reader.ReadLine()) != null)
  71. {
  72. line = line.Trim();
  73. if (string.IsNullOrWhiteSpace(line))
  74. {
  75. continue;
  76. }
  77. if (line.StartsWith("#EXTM3U", StringComparison.OrdinalIgnoreCase))
  78. {
  79. continue;
  80. }
  81. if (line.StartsWith(ExtInfPrefix, StringComparison.OrdinalIgnoreCase))
  82. {
  83. extInf = line.Substring(ExtInfPrefix.Length).Trim();
  84. _logger.Info("Found m3u channel: {0}", extInf);
  85. }
  86. else if (!string.IsNullOrWhiteSpace(extInf) && !line.StartsWith("#", StringComparison.OrdinalIgnoreCase))
  87. {
  88. var channel = GetChannelnfo(extInf, tunerHostId, line);
  89. channel.Id = channelIdPrefix + urlHash + line.GetMD5().ToString("N");
  90. channel.Path = line;
  91. channels.Add(channel);
  92. extInf = "";
  93. }
  94. }
  95. return channels;
  96. }
  97. private M3UChannel GetChannelnfo(string extInf, string tunerHostId, string mediaUrl)
  98. {
  99. var channel = new M3UChannel();
  100. channel.TunerHostId = tunerHostId;
  101. extInf = extInf.Trim();
  102. string remaining;
  103. var attributes = ParseExtInf(extInf, out remaining);
  104. extInf = remaining;
  105. string value;
  106. if (attributes.TryGetValue("tvg-logo", out value))
  107. {
  108. channel.ImageUrl = value;
  109. }
  110. channel.Name = GetChannelName(extInf, attributes);
  111. channel.Number = GetChannelNumber(extInf, attributes, mediaUrl);
  112. return channel;
  113. }
  114. private string GetChannelNumber(string extInf, Dictionary<string, string> attributes, string mediaUrl)
  115. {
  116. var nameParts = extInf.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  117. var nameInExtInf = nameParts.Length > 1 ? nameParts.Last().Trim() : null;
  118. string numberString = null;
  119. //Check for channel number with the format from SatIp
  120. // #EXTINF:0,84. VOX Schweiz
  121. if (!string.IsNullOrWhiteSpace(nameInExtInf))
  122. {
  123. var numberIndex = nameInExtInf.IndexOf('.');
  124. if (numberIndex > 0)
  125. {
  126. double number;
  127. if (double.TryParse(nameInExtInf.Substring(0, numberIndex), NumberStyles.AllowCurrencySymbol, CultureInfo.InvariantCulture, out number))
  128. {
  129. numberString = number.ToString();
  130. }
  131. }
  132. }
  133. if (!string.IsNullOrWhiteSpace(numberString))
  134. {
  135. numberString = numberString.Trim();
  136. }
  137. if (string.IsNullOrWhiteSpace(numberString) ||
  138. string.Equals(numberString, "-1", StringComparison.OrdinalIgnoreCase) ||
  139. string.Equals(numberString, "0", StringComparison.OrdinalIgnoreCase))
  140. {
  141. string value;
  142. if (attributes.TryGetValue("tvg-id", out value))
  143. {
  144. double doubleValue;
  145. if (double.TryParse(value, NumberStyles.AllowCurrencySymbol, CultureInfo.InvariantCulture, out doubleValue))
  146. {
  147. numberString = value;
  148. }
  149. }
  150. }
  151. if (!string.IsNullOrWhiteSpace(numberString))
  152. {
  153. numberString = numberString.Trim();
  154. }
  155. if (string.IsNullOrWhiteSpace(numberString) ||
  156. string.Equals(numberString, "-1", StringComparison.OrdinalIgnoreCase) ||
  157. string.Equals(numberString, "0", StringComparison.OrdinalIgnoreCase))
  158. {
  159. string value;
  160. if (attributes.TryGetValue("channel-id", out value))
  161. {
  162. numberString = value;
  163. }
  164. }
  165. if (!string.IsNullOrWhiteSpace(numberString))
  166. {
  167. numberString = numberString.Trim();
  168. }
  169. if (string.IsNullOrWhiteSpace(numberString) ||
  170. string.Equals(numberString, "-1", StringComparison.OrdinalIgnoreCase) ||
  171. string.Equals(numberString, "0", StringComparison.OrdinalIgnoreCase))
  172. {
  173. numberString = null;
  174. }
  175. if (string.IsNullOrWhiteSpace(numberString))
  176. {
  177. if (string.IsNullOrWhiteSpace(mediaUrl))
  178. {
  179. numberString = null;
  180. }
  181. else
  182. {
  183. numberString = Path.GetFileNameWithoutExtension(mediaUrl.Split('/').Last());
  184. double value;
  185. if (!double.TryParse(numberString, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
  186. {
  187. numberString = null;
  188. }
  189. }
  190. }
  191. return numberString;
  192. }
  193. private string GetChannelName(string extInf, Dictionary<string, string> attributes)
  194. {
  195. var nameParts = extInf.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  196. var nameInExtInf = nameParts.Length > 1 ? nameParts.Last().Trim() : null;
  197. //Check for channel number with the format from SatIp
  198. if (!string.IsNullOrWhiteSpace(nameInExtInf))
  199. {
  200. var numberIndex = nameInExtInf.IndexOf('.');
  201. if (numberIndex > 0)
  202. {
  203. double number;
  204. if (double.TryParse(nameInExtInf.Substring(0, numberIndex), NumberStyles.AllowCurrencySymbol, CultureInfo.InvariantCulture, out number))
  205. {
  206. //channel.Number = number.ToString();
  207. nameInExtInf = nameInExtInf.Substring(numberIndex + 1).Trim();
  208. }
  209. }
  210. }
  211. string name;
  212. attributes.TryGetValue("tvg-name", out name);
  213. if (string.IsNullOrWhiteSpace(name))
  214. {
  215. name = nameInExtInf;
  216. }
  217. if (string.IsNullOrWhiteSpace(name))
  218. {
  219. attributes.TryGetValue("tvg-id", out name);
  220. }
  221. if (string.IsNullOrWhiteSpace(name))
  222. {
  223. name = null;
  224. }
  225. return name;
  226. }
  227. private Dictionary<string, string> ParseExtInf(string line, out string remaining)
  228. {
  229. var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  230. var reg = new Regex(@"([a-z0-9\-_]+)=\""([^""]+)\""", RegexOptions.IgnoreCase);
  231. var matches = reg.Matches(line);
  232. var minIndex = int.MaxValue;
  233. foreach (Match match in matches)
  234. {
  235. dict[match.Groups[1].Value] = match.Groups[2].Value;
  236. minIndex = Math.Min(minIndex, match.Index);
  237. }
  238. if (minIndex > 0 && minIndex < line.Length)
  239. {
  240. line = line.Substring(0, minIndex);
  241. }
  242. remaining = line;
  243. return dict;
  244. }
  245. }
  246. public class M3UChannel : ChannelInfo
  247. {
  248. public string Path { get; set; }
  249. }
  250. }