M3uParser.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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 CommonIO;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.LiveTv;
  13. using MediaBrowser.Model.Logging;
  14. namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
  15. {
  16. public class M3uParser
  17. {
  18. private readonly ILogger _logger;
  19. private readonly IFileSystem _fileSystem;
  20. private readonly IHttpClient _httpClient;
  21. private readonly IServerApplicationHost _appHost;
  22. public M3uParser(ILogger logger, IFileSystem fileSystem, IHttpClient httpClient, IServerApplicationHost appHost)
  23. {
  24. _logger = logger;
  25. _fileSystem = fileSystem;
  26. _httpClient = httpClient;
  27. _appHost = appHost;
  28. }
  29. public async Task<List<M3UChannel>> Parse(string url, string channelIdPrefix, string tunerHostId, CancellationToken cancellationToken)
  30. {
  31. var urlHash = url.GetMD5().ToString("N");
  32. // Read the file and display it line by line.
  33. using (var reader = new StreamReader(await GetListingsStream(url, cancellationToken).ConfigureAwait(false)))
  34. {
  35. return GetChannels(reader, urlHash, channelIdPrefix, tunerHostId);
  36. }
  37. }
  38. public Task<Stream> GetListingsStream(string url, CancellationToken cancellationToken)
  39. {
  40. if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  41. {
  42. return _httpClient.Get(new HttpRequestOptions
  43. {
  44. Url = url,
  45. CancellationToken = cancellationToken,
  46. // Some data providers will require a user agent
  47. UserAgent = _appHost.FriendlyName + "/" + _appHost.ApplicationVersion
  48. });
  49. }
  50. return Task.FromResult(_fileSystem.OpenRead(url));
  51. }
  52. private List<M3UChannel> GetChannels(StreamReader reader, string urlHash, string channelIdPrefix, string tunerHostId)
  53. {
  54. var channels = new List<M3UChannel>();
  55. string line;
  56. string extInf = "";
  57. while ((line = reader.ReadLine()) != null)
  58. {
  59. line = line.Trim();
  60. if (string.IsNullOrWhiteSpace(line))
  61. {
  62. continue;
  63. }
  64. if (line.StartsWith("#EXTM3U", StringComparison.OrdinalIgnoreCase))
  65. {
  66. continue;
  67. }
  68. if (line.StartsWith("#EXTINF:", StringComparison.OrdinalIgnoreCase))
  69. {
  70. extInf = line.Substring(8).Trim();
  71. _logger.Info("Found m3u channel: {0}", extInf);
  72. }
  73. else if (!string.IsNullOrWhiteSpace(extInf) && !line.StartsWith("#", StringComparison.OrdinalIgnoreCase))
  74. {
  75. var channel = GetChannelnfo(extInf, tunerHostId, line);
  76. channel.Id = channelIdPrefix + urlHash + line.GetMD5().ToString("N");
  77. channel.Path = line;
  78. channels.Add(channel);
  79. extInf = "";
  80. }
  81. }
  82. return channels;
  83. }
  84. private M3UChannel GetChannelnfo(string extInf, string tunerHostId, string mediaUrl)
  85. {
  86. var titleIndex = extInf.LastIndexOf(',');
  87. var channel = new M3UChannel();
  88. channel.TunerHostId = tunerHostId;
  89. channel.Number = extInf.Trim().Split(' ')[0] ?? "0";
  90. channel.Name = extInf.Substring(titleIndex + 1);
  91. //Check for channel number with the format from SatIp
  92. int number;
  93. var numberIndex = channel.Name.IndexOf('.');
  94. if (numberIndex > 0)
  95. {
  96. if (int.TryParse(channel.Name.Substring(0, numberIndex), out number))
  97. {
  98. channel.Number = number.ToString();
  99. channel.Name = channel.Name.Substring(numberIndex + 1);
  100. }
  101. }
  102. if (string.Equals(channel.Number, "-1", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(mediaUrl))
  103. {
  104. channel.Number = Path.GetFileNameWithoutExtension(mediaUrl.Split('/').Last());
  105. }
  106. if (string.Equals(channel.Number, "-1", StringComparison.OrdinalIgnoreCase))
  107. {
  108. channel.Number = "0";
  109. }
  110. channel.ImageUrl = FindProperty("tvg-logo", extInf);
  111. var name = FindProperty("tvg-name", extInf);
  112. if (string.IsNullOrWhiteSpace(name))
  113. {
  114. name = FindProperty("tvg-id", extInf);
  115. }
  116. channel.Name = name;
  117. var numberString = FindProperty("tvg-id", extInf);
  118. if (string.IsNullOrWhiteSpace(numberString))
  119. {
  120. numberString = FindProperty("channel-id", extInf);
  121. }
  122. if (!string.IsNullOrWhiteSpace(numberString))
  123. {
  124. channel.Number = numberString;
  125. }
  126. return channel;
  127. }
  128. private string FindProperty(string property, string properties)
  129. {
  130. var reg = new Regex(@"([a-z0-9\-_]+)=\""([^""]+)\""", RegexOptions.IgnoreCase);
  131. var matches = reg.Matches(properties);
  132. foreach (Match match in matches)
  133. {
  134. if (match.Groups[1].Value == property)
  135. {
  136. return match.Groups[2].Value;
  137. }
  138. }
  139. return null;
  140. }
  141. }
  142. public class M3UChannel : ChannelInfo
  143. {
  144. public string Path { get; set; }
  145. }
  146. }