using System.Net.Http.Headers; using System.Text.RegularExpressions; using System.Xml; namespace TV_Player.MAUI { public class ProgramInfo : ObservableViewModelBase { private string _title; private int _durationValue; public string Title { get => _title; set => SetProperty(ref _title, value); } public DateTime StartTime { get; set; } public DateTime EndTime { get; set; } public int DurationValue { get => _durationValue; set => SetProperty(ref _durationValue, value); } } public class ProgramGuide { public string Id { get; set; } public string DisplayName { get; set; } public List Programs { get; set; } = new List(); } public static class M3UParser { public static async Task> DownloadGuideFromWebAsync(string url) { List epgChannels = new List(); try { using (var client = new HttpClient()) using (var request = new HttpRequestMessage()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/text")); request.Method = HttpMethod.Get; request.RequestUri = new Uri(url); var response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); epgChannels = ParseEpg(responseBody); } } catch (HttpRequestException ex) { System.Diagnostics.Debug.WriteLine($"Network error downloading EPG from {url}: {ex.Message}"); } catch (UriFormatException ex) { System.Diagnostics.Debug.WriteLine($"Invalid EPG URL: {url} - {ex.Message}"); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"Unexpected error downloading EPG: {ex.Message}"); } return epgChannels; } private static List ParseEpg(string epgData) { List epgChannels = new List(); XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; settings.IgnoreComments = true; using (XmlReader reader = XmlReader.Create(new System.IO.StringReader(epgData), settings)) { try { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "channel") { ProgramGuide channel = new ProgramGuide(); channel.Id = reader.GetAttribute("id"); reader.Read(); channel.DisplayName = reader.ReadElementContentAsString(); epgChannels.Add(channel); continue; } if (reader.NodeType == XmlNodeType.Element && reader.Name == "programme") { ProgramInfo program = new ProgramInfo(); var id = reader.GetAttribute("channel"); var channel = epgChannels.FirstOrDefault(x => x.Id == id); if (channel == null) continue; if (!DateTime.TryParseExact(reader.GetAttribute("start"), "yyyyMMddHHmmss zzz", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var startTime)) continue; if (!DateTime.TryParseExact(reader.GetAttribute("stop"), "yyyyMMddHHmmss zzz", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var endTime)) continue; program.StartTime = startTime; program.EndTime = endTime; reader.Read(); program.Title = reader.ReadElementContentAsString(); channel.Programs.Add(program); } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "channel") { break; } } } catch (XmlException ex) { System.Diagnostics.Debug.WriteLine($"XML parsing error: {ex.Message}"); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"Unexpected error parsing EPG: {ex.Message}"); } } return epgChannels; } private static async Task ReadFile(string url) { try { using (var client = new HttpClient()) using (var request = new HttpRequestMessage()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/text")); request.Method = HttpMethod.Get; request.RequestUri = new Uri(url); var response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } catch (HttpRequestException ex) { System.Diagnostics.Debug.WriteLine($"Network error downloading from {url}: {ex.Message}"); throw; } catch (UriFormatException ex) { System.Diagnostics.Debug.WriteLine($"Invalid URL: {url} - {ex.Message}"); throw; } } public static async Task<(List programList, string programGuide)> DownloadM3UFromWebAsync(string url) { var fileData=await ReadFile(url); // Parse M3U content return ParseM3UFromString(fileData); } private static string[] SplitStringBeforeSeparator(string input, string separator) { string[] parts = input.Split(separator); // Reconstruct the string until the separator is reached int separatorIndex = input.IndexOf(separator); if (separatorIndex != -1) { parts[0] = input.Substring(0, separatorIndex + 1); for (int i = 1; i < parts.Length; i++) { parts[i] = separator + parts[i]; } } return parts; } private static (List programList, string programGuide) ParseM3UFromString(string content) { List playlistItems = new List(); string programGuideLink = string.Empty; try { if (string.IsNullOrWhiteSpace(content)) { System.Diagnostics.Debug.WriteLine("M3U content is empty"); return (playlistItems, programGuideLink); } var m3u = SplitStringBeforeSeparator(content, "#EXT"); foreach (var line in m3u) { if (line.StartsWith("#EXTINF:")) { if (TryParseM3ULine(line, out var m3uInfo)) { playlistItems.Add(m3uInfo); } } if (line.StartsWith("#EXTM3U")) { programGuideLink = ExtractXtvgUrl(line); } } } catch (ArgumentException ex) { System.Diagnostics.Debug.WriteLine($"Invalid M3U format: {ex.Message}"); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"Error parsing M3U file: {ex.Message}"); } return (playlistItems, programGuideLink); } private static bool TryParseM3ULine(string m3uLine, out M3UInfo? info) { info = null; string pattern = @"#EXTINF:\d+ CUID=""(?.*?)"" number=""(?.*?)"" tvg-id=""(?.*?)"" tvg-name=""(?.*?)"".*?tvg-logo=""(?.*?)"" group-title=""(?.*?)""[^,]*,(?.*)[^\r](?.*)$"; Regex regex = new Regex(pattern, RegexOptions.IgnoreCase); Match match = regex.Match(m3uLine); if (match.Success) { info = new M3UInfo { CUID = match.Groups["CUID"].Value, Number = match.Groups["Number"].Value, TvgID = match.Groups["TvgID"].Value, TvgName = match.Groups["TvgName"].Value, GroupTitle = match.Groups["GroupTitle"].Value, Logo = match.Groups["Logo"].Value, Name = match.Groups["Name"].Value, Url = match.Groups["URL"].Value }; return true; } return false; } private static string ExtractXtvgUrl(string m3uEntry) { // Define a regular expression pattern to match x-tvg-url attribute string pattern = @"x-tvg-url=""(.*?)"""; // Use Regex.Match to find the first match Match match = Regex.Match(m3uEntry, pattern); // Check if a match is found and get the value from the capturing group if (match.Success && match.Groups.Count > 1) { return match.Groups[1].Value; } // Return null or an empty string if no match is found return string.Empty; } } }