-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathM3UFromXtream.cs
More file actions
215 lines (182 loc) · 10.3 KB
/
Copy pathM3UFromXtream.cs
File metadata and controls
215 lines (182 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
using Newtonsoft.Json;
using System.Text.RegularExpressions;
namespace M3UFromXtream
{
internal class M3UFromXtream
{
private static readonly HttpClient httpClient = new HttpClient();
static M3UFromXtream()
{
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0");
}
private static string? version = string.Empty;
static async Task Main(string[] args)
{
version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? string.Empty;
Console.WriteLine($"M3UFromXtream Version {version}");
Console.WriteLine("");
if (args.Length < 3 || args.Length > 4)
{
Console.WriteLine("Usage: M3UFromXtream <url> <username> <password> [output-file]");
Console.WriteLine("Example: M3UFromXtream http://example.com:8080 user pass output.m3u");
return;
}
string baseUrl = args[0];
string username = args[1];
string password = args[2];
string outputFile = args.Length > 3 ? args[3] : "playlist.m3u";
httpClient.Timeout = TimeSpan.FromSeconds(10);
try
{
Console.WriteLine("Connecting to Xtream Code API...");
await GenerateM3UFromXtream(baseUrl, username, password, outputFile).ConfigureAwait(false);
Console.WriteLine($"M3U playlist successfully created: {outputFile}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
/// <summary>
/// Generates an M3U playlist file from Xtream API data.
/// </summary>
/// <remarks>This method retrieves categories and streams from the Xtream API and writes them to
/// an M3U file. The generated file includes metadata such as the generation date and version
/// information.</remarks>
/// <param name="baseUrl">The base URL of the Xtream API. Must not end with a slash.</param>
/// <param name="username">The username for Xtream API authentication.</param>
/// <param name="password">The password for Xtream API authentication.</param>
/// <param name="outputFile">The path to the output file where the M3U playlist will be saved.</param>
/// <returns></returns>
static async Task GenerateM3UFromXtream(string baseUrl, string username, string password, string outputFile)
{
baseUrl = baseUrl.TrimEnd('/');
var categories = await GetCategories(baseUrl, username, password).ConfigureAwait(false);
Console.WriteLine($"Found {categories.Count} categories");
using var writer = new StreamWriter(outputFile);
writer.WriteLine("#EXTM3U");
writer.WriteLine($"# Generated by M3UFromXtream Version: {version}");
writer.WriteLine($"# Generated on: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
writer.WriteLine();
int channelCount = 0;
foreach (var category in categories)
{
Console.WriteLine($"Processing category: {category.CategoryName}");
bool success = false;
int failCounter = 0;
List<Stream> streams = new List<Stream>();
while (!success && failCounter < 3)
{
try
{
streams = await GetStreams(baseUrl, username, password, category.CategoryId).ConfigureAwait(false);
success = true;
}
catch(Exception ex)
{
failCounter++;
Console.WriteLine($"{failCounter} Error retrieving streams for category {category.CategoryName}: {ex.Message}");
// continue;
}
}
if(success is false)
{
Console.WriteLine($"Failed to retrieve streams for category {category.CategoryName} after 3 attempts. Aborting.");
continue;
}
foreach (var stream in streams)
{
if (string.IsNullOrEmpty(stream.Name) || string.IsNullOrEmpty(stream.StreamType))
continue;
string streamUrl = $"{baseUrl}/{username}/{password}/{stream.StreamId}";
writer.WriteLine(
$"#EXTINF:-1 tvg-id=\"{(stream.EpgChannelId ?? "").Replace("\r", "").Replace("\n", "")}\" " +
$"tvg-name=\"{EscapeM3UField(stream.Name).Replace("\r", "").Replace("\n", "")}\" " +
$"tvg-logo=\"{(stream.StreamIcon ?? "").Replace("\r", "").Replace("\n", "")}\" " +
$"group-title=\"{EscapeM3UField(category.CategoryName).Replace("\r", "").Replace("\n", "")}\"," +
$"{EscapeM3UField(stream.Name).Replace("\r", "").Replace("\n", "")}"
);
writer.WriteLine(streamUrl);
writer.WriteLine();
channelCount++;
}
}
Console.WriteLine($"Total channels processed: {channelCount}");
}
/// <summary>
/// Retrieves a list of live categories from the specified server.
/// </summary>
/// <remarks>This method sends an HTTP GET request to the server using the provided credentials to
/// retrieve live categories. Ensure that the <paramref name="baseUrl"/>, <paramref name="username"/>, and
/// <paramref name="password"/> are valid and correctly formatted.</remarks>
/// <param name="baseUrl">The base URL of the server to connect to.</param>
/// <param name="username">The username for authentication.</param>
/// <param name="password">The password for authentication.</param>
/// <returns>A task representing the asynchronous operation. The task result contains a list of <see cref="Category"/>
/// objects representing the live categories. Returns an empty list if no categories are found.</returns>
static async Task<List<Category>> GetCategories(string baseUrl, string username, string password)
{
string url = $"{baseUrl}/player_api.php?username={username}&password={password}&action=get_live_categories";
using var httpResponse = await httpClient.GetAsync(url).ConfigureAwait(false);
string response = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (!httpResponse.IsSuccessStatusCode)
throw new HttpRequestException($"Server returned {(int)httpResponse.StatusCode}: {response}");
//using (StreamWriter file = File.CreateText(@"C:\testdata\XcCategpries.json"))
//{
// file.Write(JsonPrettify(response));
//}
var categories = JsonConvert.DeserializeObject<List<Category>>(response);
return categories ?? new List<Category>();
}
/// <summary>
/// Retrieves a list of live streams for a specified category from the server.
/// </summary>
/// <param name="baseUrl">The base URL of the server to connect to.</param>
/// <param name="username">The username for authentication.</param>
/// <param name="password">The password for authentication.</param>
/// <param name="categoryId">The identifier of the category for which to retrieve streams.</param>
/// <returns>A task representing the asynchronous operation. The task result contains a list of <see cref="Stream"/>
/// objects representing the live streams in the specified category. Returns an empty list if no streams are
/// found.</returns>
static async Task<List<Stream>> GetStreams(string baseUrl, string username, string password, string categoryId)
{
string url = $"{baseUrl}/player_api.php?username={username}&password={password}&action=get_live_streams&category_id={categoryId}";
using var httpResponse = await httpClient.GetAsync(url).ConfigureAwait(false);
var response = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (!httpResponse.IsSuccessStatusCode)
throw new HttpRequestException($"Server returned {(int)httpResponse.StatusCode}: {response}");
//using (StreamWriter file = File.CreateText(@$"C:\testdata\XcStreams_{categoryId}.json"))
//{
// file.Write(JsonPrettify(response));
//}
var streams = JsonConvert.DeserializeObject<List<Stream>>(response);
return streams ?? new List<Stream>();
}
/// <summary>
/// Escapes special characters in an M3U field to ensure proper formatting.
/// </summary>
/// <remarks>This method replaces double quotes, commas, and colons with their escaped
/// counterparts to prevent misinterpretation in M3U playlists.</remarks>
/// <param name="field">The M3U field string to be escaped. Cannot be null.</param>
/// <returns>A new string with special characters escaped. Returns an empty string if the input is null or empty.</returns>
static string EscapeM3UField(string field)
{
if (string.IsNullOrEmpty(field))
return string.Empty;
// Escape special characters in M3U fields
return field.Replace("\"", "\\\"")
.Replace(",", "\\,")
.Replace(":", "\\:");
}
/// <summary>
/// Indents and adds line breaks to make JSON pretty for printing/viewing.
/// </summary>
/// <param name="json">Raw JSON string</param>
/// <returns>Formatted JSON string</returns>
public static string JsonPrettify(string json)
{
var obj = JsonConvert.DeserializeObject(json);
return JsonConvert.SerializeObject(obj, Formatting.Indented);
}
}
}