M3uParser.cs 8.4 KB

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