-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
208 lines (179 loc) · 7.27 KB
/
Program.cs
File metadata and controls
208 lines (179 loc) · 7.27 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
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Windows.Media.Control;
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(MusicInfo))]
internal partial class SourceGenerationContext : JsonSerializerContext { }
class Program
{
static volatile string musicData = JsonSerializer.Serialize(new MusicInfo(), SourceGenerationContext.Default.MusicInfo);
static string lastSong = "";
static string currentArtUrl = "none";
static DateTime lastRequestTime = DateTime.Now;
static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
Console.WriteLine("[INFO] WindowsMusic Helper Started.");
Console.WriteLine("[INFO] Listening on http://localhost:61942/ ...");
GlobalSystemMediaTransportControlsSessionManager? manager = null;
try
{
manager = await GlobalSystemMediaTransportControlsSessionManager.RequestAsync();
}
catch (Exception ex)
{
Console.WriteLine($"[CRITICAL] Could not access Media Manager. Error: {ex.Message}");
return;
}
_ = Task.Run(async () =>
{
while (true)
{
if ((DateTime.Now - lastRequestTime).TotalSeconds > 30)
{
Console.WriteLine("[TIMEOUT] No requests for 30s. Shutting down.");
Environment.Exit(0);
}
await UpdateMedia(manager);
await Task.Delay(500); // Lowered delay slightly for smoother metadata updates
}
});
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:61942/");
try { listener.Start(); }
catch (Exception e)
{
Console.WriteLine($"[ERROR] Failed to start HTTP listener: {e.Message}");
return;
}
while (listener.IsListening)
{
try
{
var context = await listener.GetContextAsync();
lastRequestTime = DateTime.Now;
byte[] b = Encoding.UTF8.GetBytes(musicData);
context.Response.ContentType = "application/json";
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
await context.Response.OutputStream.WriteAsync(b, 0, b.Length);
context.Response.Close();
}
catch (Exception ex) { Console.WriteLine($"[HTTP ERROR] {ex.Message}"); }
}
}
static string FormatDuration(TimeSpan duration)
{
if (duration.TotalHours >= 1)
return duration.ToString(@"h\:mm\:ss");
return duration.ToString(@"m\:ss");
}
static async Task UpdateMedia(GlobalSystemMediaTransportControlsSessionManager manager)
{
var session = manager.GetCurrentSession();
if (session == null)
{
if (lastSong != "None")
{
Console.WriteLine("No active media session found.");
ResetState();
}
return;
}
try
{
var playback = session.GetPlaybackInfo();
bool isPaused = playback?.PlaybackStatus != GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing;
var props = await session.TryGetMediaPropertiesAsync();
string title = props?.Title ?? "Unknown";
string artist = props?.Artist ?? "Unknown";
string currentSong = $"{title} - {artist}";
long positionMs = 0;
long durationMs = 0;
string timeStr = "0:00";
string totalTimeStr = "0:00";
try
{
var timeline = session.GetTimelineProperties();
if (timeline != null)
{
var start = timeline.StartTime;
var end = timeline.EndTime;
var position = timeline.Position;
var duration = end - start;
if (duration < TimeSpan.Zero)
{
duration = end;
}
positionMs = Math.Max(0, (long)position.TotalMilliseconds);
durationMs = Math.Max(0, (long)duration.TotalMilliseconds);
timeStr = FormatDuration(TimeSpan.FromMilliseconds(positionMs));
totalTimeStr = FormatDuration(TimeSpan.FromMilliseconds(durationMs));
}
}
catch { }
if (currentSong != lastSong)
{
Console.WriteLine($"[EVENT] Song changed: {currentSong}");
lastSong = currentSong;
currentArtUrl = "none";
_ = Task.Run(async () => {
var newUrl = await GetAlbumArtUrl(artist, title);
currentArtUrl = newUrl;
});
}
var dataObj = new MusicInfo
{
song = currentSong,
time = timeStr,
totalTime = totalTimeStr,
art = currentArtUrl,
isPaused = isPaused,
positionMs = positionMs,
durationMs = durationMs,
snapshotUnixMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
};
musicData = JsonSerializer.Serialize(dataObj, SourceGenerationContext.Default.MusicInfo);
}
catch (Exception ex) { Console.WriteLine($"[UPDATE ERROR] {ex.Message}"); }
}
static void ResetState()
{
lastSong = "None";
musicData = JsonSerializer.Serialize(new MusicInfo(), SourceGenerationContext.Default.MusicInfo);
}
static async Task<string> GetAlbumArtUrl(string artist, string title)
{
if (string.IsNullOrWhiteSpace(artist) || string.IsNullOrWhiteSpace(title) || artist == "Unknown")
return "none";
try
{
string query = $"artist:\"{artist}\" track:\"{title}\"";
string url = $"https://api.deezer.com/search?q={Uri.EscapeDataString(query)}&limit=1";
if (!httpClient.DefaultRequestHeaders.Contains("User-Agent"))
httpClient.DefaultRequestHeaders.Add("User-Agent", "WindowsMusicHelper/1.0");
var response = await httpClient.GetStringAsync(url);
using var doc = JsonDocument.Parse(response);
if (doc.RootElement.TryGetProperty("data", out JsonElement dataArray) && dataArray.GetArrayLength() > 0)
{
var album = dataArray[0].GetProperty("album");
return album.GetProperty("cover_medium").GetString() ?? "none";
}
}
catch { }
return "none";
}
}
public class MusicInfo
{
public string song { get; set; } = "None";
public string time { get; set; } = "0:00";
public string totalTime { get; set; } = "0:00";
public string art { get; set; } = "none";
public bool isPaused { get; set; } = true;
public long positionMs { get; set; } = 0;
public long durationMs { get; set; } = 0;
public long snapshotUnixMs { get; set; } = 0;
}