-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
316 lines (273 loc) · 10.9 KB
/
Program.cs
File metadata and controls
316 lines (273 loc) · 10.9 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DiscordRPC;
using YoutubeExplode;
using YoutubeExplode.Videos;
namespace YouTubeMusicDiscordRPC
{
class Program
{
private static DiscordRpcClient discordClient;
private static YoutubeClient youtubeClient;
private static string currentVideoId = "";
private static MusicInfo currentMusicInfo;
private const string CLIENT_ID = "1415069890766704700";
static async Task Main(string[] args)
{
Console.Title = "YouTube Music Discord RPC";
Console.WriteLine("🎵 Rich Presence YouTube Music pour Discord");
Console.WriteLine("=============================================\n");
// Initialisation
InitializeDiscordRPC();
youtubeClient = new YoutubeClient();
Console.WriteLine("Instructions:");
Console.WriteLine("1. Ouvrez YouTube Music dans votre navigateur");
Console.WriteLine("2. Copiez l'URL de la musique en cours");
Console.WriteLine("3. Collez l'URL ici et appuyez sur Entrée");
Console.WriteLine("4. Tapez 'stop' pour arrêter");
Console.WriteLine("5. Tapez 'exit' pour quitter\n");
// Boucle principale
while (true)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("🎵 Collez l'URL YouTube Music: ");
Console.ResetColor();
string input = Console.ReadLine()?.Trim();
if (string.IsNullOrEmpty(input))
continue;
if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
break;
if (input.Equals("stop", StringComparison.OrdinalIgnoreCase))
{
SetIdlePresence();
Console.WriteLine("❌ Rich Presence arrêté.");
continue;
}
if (input.Equals("clear", StringComparison.OrdinalIgnoreCase))
{
Console.Clear();
continue;
}
await ProcessYouTubeUrl(input);
}
Cleanup();
}
static void InitializeDiscordRPC()
{
discordClient = new DiscordRpcClient(CLIENT_ID);
discordClient.OnReady += (sender, e) =>
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"\n✅ Connecté à Discord en tant que {e.User.Username}");
Console.ResetColor();
};
discordClient.OnError += (sender, e) =>
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"\n❌ Erreur Discord: {e.Message}");
Console.ResetColor();
};
discordClient.OnConnectionFailed += (sender, e) =>
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"\n❌ Connexion Discord échouée");
Console.ResetColor();
};
discordClient.Initialize();
SetIdlePresence();
}
static async Task ProcessYouTubeUrl(string url)
{
try
{
if (!url.Contains("youtube.com") && !url.Contains("youtu.be"))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("⚠️ URL YouTube non valide");
Console.ResetColor();
return;
}
string videoId = ExtractVideoIdFromUrl(url);
if (string.IsNullOrEmpty(videoId))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("⚠️ Impossible d'extraire l'ID de la vidéo");
Console.ResetColor();
return;
}
// Éviter de refaire la requête si c'est la même vidéo
if (videoId == currentVideoId && currentMusicInfo != null)
{
SetDiscordPresence(currentMusicInfo);
return;
}
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("🔄 Récupération des informations de la musique...");
Console.ResetColor();
var video = await youtubeClient.Videos.GetAsync(videoId);
currentMusicInfo = new MusicInfo
{
VideoId = videoId,
Title = CleanTitle(video.Title),
Artist = video.Author.ChannelTitle,
Duration = video.Duration.HasValue ? (int)video.Duration.Value.TotalSeconds : 0,
ThumbnailUrl = GetThumbnailUrl(videoId),
Url = url
};
currentVideoId = videoId;
SetDiscordPresence(currentMusicInfo);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"\n✅ Musique mise à jour:");
Console.WriteLine($" Titre: {currentMusicInfo.Title}");
Console.WriteLine($" Artiste: {currentMusicInfo.Artist}");
Console.WriteLine($" Durée: {FormatTime(currentMusicInfo.Duration)}");
Console.ResetColor();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"\n❌ Erreur: {ex.Message}");
Console.ResetColor();
SetErrorPresence();
}
}
static void SetDiscordPresence(MusicInfo musicInfo)
{
var presence = new RichPresence()
{
Details = $"{Truncate(musicInfo.Title, 128)}",
State = $"Par {Truncate(musicInfo.Artist, 128)}",
Timestamps = new Timestamps()
{
Start = DateTime.UtcNow
},
Assets = new Assets()
{
LargeImageKey = musicInfo.ThumbnailUrl,
LargeImageText = $"YouTube Music - {FormatTime(musicInfo.Duration)}",
SmallImageKey = "music_icon",
SmallImageText = "En lecture sur YouTube Music"
},
Buttons = new Button[]
{
new Button()
{
Label = "Écouter sur YouTube Music",
Url = musicInfo.Url
}
}
};
discordClient.SetPresence(presence);
}
static void SetIdlePresence()
{
var presence = new RichPresence()
{
Details = "Aucune musique en cours",
State = "En attente sur YouTube Music",
Assets = new Assets()
{
LargeImageKey = "youtube_music",
LargeImageText = "YouTube Music",
SmallImageKey = "idle",
SmallImageText = "En attente"
}
};
discordClient.SetPresence(presence);
currentVideoId = "";
currentMusicInfo = null;
}
static void SetErrorPresence()
{
var presence = new RichPresence()
{
Details = "Erreur de lecture",
State = "Vérifiez l'URL YouTube Music",
Assets = new Assets()
{
LargeImageKey = "error",
LargeImageText = "Erreur",
SmallImageKey = "warning",
SmallImageText = "Problème détecté"
}
};
discordClient.SetPresence(presence);
}
// Méthodes utilitaires
static string ExtractVideoIdFromUrl(string url)
{
try
{
if (url.Contains("youtu.be/"))
{
return url.Split(new[] { "youtu.be/" }, StringSplitOptions.None)[1].Split('?')[0];
}
else if (url.Contains("v="))
{
var uri = new Uri(url);
var query = System.Web.HttpUtility.ParseQueryString(uri.Query);
return query["v"];
}
else if (url.Contains("youtube.com/watch/"))
{
return url.Split(new[] { "watch/" }, StringSplitOptions.None)[1].Split('?')[0];
}
}
catch
{
return null;
}
return null;
}
static string GetThumbnailUrl(string videoId)
{
// Format standard des thumbnails YouTube
return $"https://img.youtube.com/vi/{videoId}/maxresdefault.jpg";
}
static string CleanTitle(string title)
{
// Nettoyer le titre des tags communs
string[] toRemove = {
"(Official Video)", "(Official Music Video)", "[Official Video]",
"(Official Audio)", "[Official Audio]", "(Lyrics)", "[Lyrics]",
"(Lyric Video)", "[Lyric Video]", "| Official Video", "| Official Audio",
"(Official HD Video)", "[HD]", "(HD)", "| HD", "(4K)", "[4K]", "| 4K",
"(Clean Version)", "[Clean]", "(Explicit)", "[Explicit]"
};
foreach (var tag in toRemove)
{
title = title.Replace(tag, "");
}
return title.Trim(' ', '-', '|', '"', '\'');
}
static string FormatTime(int seconds)
{
if (seconds <= 0) return "0:00";
TimeSpan time = TimeSpan.FromSeconds(seconds);
return $"{(int)time.TotalMinutes}:{time.Seconds:00}";
}
static string Truncate(string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Length <= maxLength ? value : value.Substring(0, maxLength - 3) + "...";
}
static void Cleanup()
{
Console.WriteLine("\n🛑 Arrêt du Rich Presence...");
discordClient?.ClearPresence();
discordClient?.Dispose();
Console.WriteLine("✅ Application arrêtée. Appuyez sur une touche pour fermer...");
Console.ReadKey();
}
}
public class MusicInfo
{
public string VideoId { get; set; }
public string Title { get; set; }
public string Artist { get; set; }
public int Duration { get; set; }
public string ThumbnailUrl { get; set; }
public string Url { get; set; }
}
}