-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDeezerRPC.cpp
More file actions
588 lines (485 loc) · 21.1 KB
/
DeezerRPC.cpp
File metadata and controls
588 lines (485 loc) · 21.1 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
// DeezerRPC.cpp
#include <windows.h>
#include <winhttp.h>
#include <shellapi.h>
#include <commctrl.h>
#pragma comment(lib, "winhttp.lib")
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "windowsapp.lib")
const bool DEBUG = false;
#define DISCORDPP_IMPLEMENTATION
#include "discordpp.h"
#include <iostream>
#include <thread>
#include <atomic>
#include <string>
#include <csignal>
#include <fstream>
#include <winrt/base.h>
#include <wrl.h>
#include <winrt/Windows.Media.Control.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <json.hpp>
#define WM_APP_TRAYICON (WM_APP + 1)
#define ID_TRAYICON 1
#define ID_EXIT 2
#define ID_AUTOSTART 3
#define ID_DEEZER_RPC_IS_ENABLED 4
#define ID_BRAVE_RPC_IS_ENABLED 5
#define IDI_ICON1 101
#define IDI_ICON2 102
using json = nlohmann::json;
using namespace winrt::Windows::Media::Control;
using namespace winrt::Windows::Foundation;
const uint64_t DEEZER_APP_ID = 1234921022856237196;
const uint64_t BROWSER_APP_ID = 1428086836760150219;
std::atomic<bool> running = true;
bool showConsole = DEBUG;
bool is_deezer_rpc_enabled = true;
bool is_brave_rpc_enabled = true;
HWND g_hwnd = NULL;
NOTIFYICONDATA nid = { 0 };
void signalHandler(int signum) {
running.store(false);
}
void DebugLog(const std::string& message) {
if (DEBUG) {
std::cout << message << std::endl;
}
}
template<typename T>
void DebugLog(const std::string& prefix, const T& value) {
if (DEBUG) {
std::cout << prefix << value << std::endl;
}
}
void DebugError(const std::string& message) {
if (DEBUG) {
std::cerr << message << std::endl;
}
}
std::string UrlEncode(const std::string& str) {
std::string encoded;
for (unsigned char c : str) {
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
encoded += c;
} else if (c == ' ') {
encoded += '+';
} else {
char hex[3];
sprintf_s(hex, "%02X", c);
encoded += '%' + std::string(hex);
}
}
return encoded;
}
std::string HttpGet(const std::wstring& host, const std::wstring& path) {
std::string response;
HINTERNET hSession = WinHttpOpen(L"DeezerRPC/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession) return response;
HINTERNET hConnect = WinHttpConnect(hSession, host.c_str(), INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!hConnect) {
WinHttpCloseHandle(hSession);
return response;
}
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", path.c_str(),
NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (!hRequest) {
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return response;
}
if (WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) &&
WinHttpReceiveResponse(hRequest, NULL)) {
unsigned long bytesAvailable = 0;
do {
bytesAvailable = 0;
WinHttpQueryDataAvailable(hRequest, &bytesAvailable);
if (bytesAvailable > 0) {
std::vector<char> buffer(bytesAvailable + 1);
unsigned long bytesRead = 0;
if (WinHttpReadData(hRequest, buffer.data(), bytesAvailable, &bytesRead)) {
buffer[bytesRead] = '\0';
response += buffer.data();
}
}
} while (bytesAvailable > 0);
}
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return response;
}
// Structure pour stocker les infos Deezer d'une track
struct DeezerTrackInfo {
std::string albumCover;
std::string artistImage;
int trackId = 0;
std::string trackUrl;
};
// Fonction unique pour récupérer toutes les infos d'une track Deezer
DeezerTrackInfo GetDeezerTrackInfo(const std::string& title, const std::string& artist) {
DeezerTrackInfo info;
try {
std::string query = UrlEncode(title + " " + artist);
std::wstring host = L"api.deezer.com";
std::wstring path = L"/search/track?q=" + std::wstring(query.begin(), query.end());
std::string response = HttpGet(host, path);
if (response.empty()) return info;
auto j = json::parse(response);
if (j.contains("data") && !j["data"].empty()) {
auto track = j["data"][0];
info.trackId = track["id"];
if (track.contains("album") && track["album"].contains("cover_big"))
info.albumCover = track["album"]["cover_big"];
if (track.contains("artist") && track["artist"].contains("picture_big"))
info.artistImage = track["artist"]["picture_big"];
if (track.contains("link"))
info.trackUrl = track["link"];
}
}
catch (const std::exception& e) {
DebugError("Erreur lors de la récupération de la track Deezer: " + std::string(e.what()));
}
return info;
}
GlobalSystemMediaTransportControlsSession GetDeezerSession(GlobalSystemMediaTransportControlsSessionManager const& manager) {
auto sessions = manager.GetSessions();
for (uint32_t i = 0; i < sessions.Size(); ++i) {
auto session = sessions.GetAt(i);
auto id = session.SourceAppUserModelId();
if (!id.empty() && std::wstring(id).find(L"deezer") != std::wstring::npos) {
return session;
}
}
return nullptr;
}
GlobalSystemMediaTransportControlsSession GetCurrentSession(GlobalSystemMediaTransportControlsSessionManager const& manager)
{
auto sessions = manager.GetSessions();
if (sessions.Size() == 0) {
return nullptr;
}
// get the active session between deezer and Brave
for (uint32_t i = 0; i < sessions.Size(); ++i) {
// find the session with the most recent activity
auto session = sessions.GetAt(i);
if (session == nullptr) {
continue;
}
auto playback = session.GetPlaybackInfo();
if (playback == nullptr) {
continue;
}
if (playback.PlaybackStatus() == GlobalSystemMediaTransportControlsSessionPlaybackStatus::Playing)
{
return session;
}
}
return nullptr;
}
void DisableAutoStart() {
HKEY hKey;
if (RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_SET_VALUE, &hKey) == ERROR_SUCCESS) {
RegDeleteValue(hKey, L"DeezerRPC");
RegCloseKey(hKey);
}
}
void EnableAutoStart() {
WCHAR path[MAX_PATH];
GetModuleFileName(NULL, path, MAX_PATH);
HKEY hKey;
if (RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_SET_VALUE, &hKey) == ERROR_SUCCESS) {
RegSetValueEx(hKey, L"DeezerRPC", 0, REG_SZ, (BYTE*)path, (wcslen(path) + 1) * sizeof(WCHAR));
RegCloseKey(hKey);
}
}
void InitTrayIcon(HWND hwnd) {
nid.cbSize = sizeof(NOTIFYICONDATA);
nid.hWnd = hwnd;
nid.uID = ID_TRAYICON;
nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
nid.uCallbackMessage = WM_APP_TRAYICON;
// Charger l'icône personnalisée
nid.hIcon = (HICON)LoadImage(
GetModuleHandle(NULL),
MAKEINTRESOURCE(IDI_ICON2),
IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON), // 16x16 généralement
GetSystemMetrics(SM_CYSMICON),
LR_DEFAULTCOLOR
);
// Utiliser l'icône par défaut si échec du chargement
if (nid.hIcon == NULL) {
nid.hIcon = LoadIcon(NULL, IDI_APPLICATION);
}
wcscpy_s(nid.szTip, L"Deezer Rich Presence");
Shell_NotifyIcon(NIM_ADD, &nid);
}
bool IsAutoStartEnabled() {
HKEY hKey;
bool enabled = false;
if (RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
WCHAR path[MAX_PATH] = {0};
DWORD pathSize = sizeof(path);
if (RegQueryValueEx(hKey, L"DeezerRPC", NULL, NULL, (LPBYTE)path, &pathSize) == ERROR_SUCCESS) {
enabled = true;
}
RegCloseKey(hKey);
}
return enabled;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_APP_TRAYICON:
if (lParam == WM_RBUTTONUP || lParam == WM_LBUTTONUP) {
POINT pt;
GetCursorPos(&pt);
bool autoStartEnabled = IsAutoStartEnabled();
HMENU hMenu = CreatePopupMenu();
AppendMenu(hMenu, MF_STRING, ID_AUTOSTART,
autoStartEnabled ? L"Disabled start on Launch" : L"Enabled start on Launch");
AppendMenu(hMenu, MF_SEPARATOR, 0, NULL);
AppendMenu(hMenu, MF_STRING | (is_deezer_rpc_enabled ? MF_CHECKED : MF_UNCHECKED), ID_DEEZER_RPC_IS_ENABLED, L"Deezer RPC is Enabled");
AppendMenu(hMenu, MF_STRING | (is_brave_rpc_enabled ? MF_CHECKED : MF_UNCHECKED), ID_BRAVE_RPC_IS_ENABLED, L"Brave RPC is Enabled");
AppendMenu(hMenu, MF_SEPARATOR, 0, NULL);
AppendMenu(hMenu, MF_STRING, ID_EXIT, L"Exit");
SetForegroundWindow(hwnd);
TrackPopupMenu(hMenu, TPM_RIGHTBUTTON, pt.x, pt.y, 0, hwnd, NULL);
DestroyMenu(hMenu);
}
return 0;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case ID_AUTOSTART:
if (IsAutoStartEnabled()) {
DisableAutoStart();
DebugLog("Demarrage automatique desactive");
} else {
EnableAutoStart();
DebugLog("Demarrage automatique active");
}
return 0;
case ID_DEEZER_RPC_IS_ENABLED:
is_deezer_rpc_enabled = !is_deezer_rpc_enabled;
DebugLog("Deezer RPC " + std::string(is_deezer_rpc_enabled ? "enabled" : "disabled"));
return 0;
case ID_BRAVE_RPC_IS_ENABLED:
is_brave_rpc_enabled = !is_brave_rpc_enabled;
DebugLog("Brave RPC " + std::string(is_brave_rpc_enabled ? "enabled" : "disabled"));
return 0;
case ID_EXIT:
running = false;
PostQuitMessage(0);
return 0;
}
break;
case WM_DESTROY:
Shell_NotifyIcon(NIM_DELETE, &nid);
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
HWND CreateMessageWindow() {
WNDCLASSEX wcex = { 0 };
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.lpfnWndProc = WindowProc;
wcex.hInstance = GetModuleHandle(NULL);
wcex.lpszClassName = L"DeezerRPCClass";
RegisterClassEx(&wcex);
HWND hwnd = CreateWindowEx(
0, L"DeezerRPCClass", L"DeezerRPC",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
400, 300, NULL, NULL, GetModuleHandle(NULL), NULL);
return hwnd;
}
std::shared_ptr<discordpp::Client> CreateClient(uint64_t appId)
{
auto client = std::make_shared<discordpp::Client>();
client->SetApplicationId(appId);
client->AddLogCallback([](auto message, auto severity) {
if (DEBUG) {
std::cout << "[" << EnumToString(severity) << "] " << message << std::endl;
}
}, discordpp::LoggingSeverity::Info);
client->SetStatusChangedCallback([client](discordpp::Client::Status status, discordpp::Client::Error error, int32_t errorDetail) {
DebugLog("🔄 Status changed: " + discordpp::Client::StatusToString(status));
if (status == discordpp::Client::Status::Ready) {
DebugLog("✅ Client prêt !");
}
});
return client;
}
// Remplace main() par WinMain() pour une application Windows native
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
// Creer une console uniquement si DEBUG est active
if (DEBUG) {
AllocConsole();
FILE* pConsole;
freopen_s(&pConsole, "CONOUT$", "w", stdout);
freopen_s(&pConsole, "CONOUT$", "w", stderr);
}
// Initialiser les contrôles communs (necessaire pour les menus)
INITCOMMONCONTROLSEX icex = { sizeof(INITCOMMONCONTROLSEX), ICC_STANDARD_CLASSES };
InitCommonControlsEx(&icex);
// Creer la fenêtre invisible et l icône du systray
g_hwnd = CreateMessageWindow();
InitTrayIcon(g_hwnd);
winrt::init_apartment();
std::signal(SIGINT, signalHandler);
DebugLog("🚀 Initialisation Discord SDK...");
auto deezer_client = CreateClient(DEEZER_APP_ID);
auto brave_client = CreateClient(BROWSER_APP_ID);
// Initialisation du contrôleur media Windows
GlobalSystemMediaTransportControlsSessionManager manager = GlobalSystemMediaTransportControlsSessionManager::RequestAsync().get();
MSG msg;
GlobalSystemMediaTransportControlsSession session = nullptr;
GlobalSystemMediaTransportControlsSession OLD_session = nullptr;
while (running) {
// Traiter les messages Windows sans bloquer
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT) {
running = false;
break;
}
}
session = GetCurrentSession(manager);
if (session == nullptr && OLD_session != nullptr) {
session = OLD_session;
}
if (session == nullptr) {
// Plus aucune session du tout, on clear
continue;
}
if (OLD_session == nullptr || session.SourceAppUserModelId() != OLD_session.SourceAppUserModelId()) {
OLD_session = session;
}
auto id = session.SourceAppUserModelId();
// Si Deezer est actif, on met a jour le statut Discord pour Deezer
if (!id.empty() && (std::wstring(id).find(L"deezer") != std::wstring::npos ) && is_deezer_rpc_enabled) {
// clear le statut Brave si Deezer est actif
brave_client->ClearRichPresence();
auto playback = session.GetPlaybackInfo();
auto props = session.TryGetMediaPropertiesAsync().get();
auto timeline = session.GetTimelineProperties();
bool isPaused = playback.PlaybackStatus() == GlobalSystemMediaTransportControlsSessionPlaybackStatus::Paused;
bool isPlaying = playback.PlaybackStatus() == GlobalSystemMediaTransportControlsSessionPlaybackStatus::Playing;
if (isPlaying || isPaused) {
std::string title_utf8 = winrt::to_string(props.Title());
std::string artist_utf8 = winrt::to_string(props.Artist());
std::string album_utf8 = winrt::to_string(props.AlbumTitle());
double pos = timeline.Position().count() / 1e7;
double dur = (timeline.EndTime() - timeline.StartTime()).count() / 1e7;
auto start = std::chrono::system_clock::now() - std::chrono::seconds((int)pos);
auto end = start + std::chrono::seconds((int)dur);
// Nouvelle récupération simplifiée via Deezer
DeezerTrackInfo trackInfo = GetDeezerTrackInfo(title_utf8, artist_utf8);
std::string albumArtUrl = trackInfo.albumCover;
std::string artistImageUrl = trackInfo.artistImage;
discordpp::Activity activity;
activity.SetType(discordpp::ActivityTypes::Listening);
activity.SetState(isPaused ? "⏸️ En pause" : ("par " + artist_utf8));
activity.SetDetails("🎵 " + title_utf8);
// Ajouter les assets d image
discordpp::ActivityAssets assets;
if (!albumArtUrl.empty()) {
assets.SetLargeImage(albumArtUrl.c_str());
assets.SetLargeText(title_utf8 + " - " + artist_utf8);
} else {
// Image par defaut si la pochette n est pas trouvee
assets.SetLargeImage("deezer_logo");
assets.SetLargeText("Deezer Music");
}
// Ajouter une petite icône pour l etat de lecture
if (!artistImageUrl.empty()) {
assets.SetSmallImage(artistImageUrl.c_str());
assets.SetSmallText(artist_utf8);
} else {
// Fallback aux icônes statiques
assets.SetSmallImage(isPaused ? "paused_icon" : "playing_icon");
assets.SetSmallText(isPaused ? "En pause" : "En lecture");
}
activity.SetAssets(assets);
if (isPlaying) {
double pos = timeline.Position().count() / 1e7;
double dur = (timeline.EndTime() - timeline.StartTime()).count() / 1e7;
auto start = std::chrono::system_clock::now() - std::chrono::seconds((int)pos);
auto end = start + std::chrono::seconds((int)dur);
discordpp::ActivityTimestamps timestamps;
timestamps.SetStart(std::chrono::duration_cast<std::chrono::seconds>(start.time_since_epoch()).count());
timestamps.SetEnd(std::chrono::duration_cast<std::chrono::seconds>(end.time_since_epoch()).count());
activity.SetTimestamps(timestamps);
}
deezer_client->UpdateRichPresence(activity, [](discordpp::ClientResult result) {
if (result.Successful()) {
DebugLog("🎮 Rich Presence mise a jour !");
}
});
} else {
deezer_client->ClearRichPresence();
}
} else if (!id.empty() && (std::wstring(id).find(L"Brave") != std::wstring::npos ) && is_brave_rpc_enabled) {
// Si Brave est actif, on met a jour le statut Discord pour Brave
// clear le statut Deezer si Brave est actif
deezer_client->ClearRichPresence();
auto playback = session.GetPlaybackInfo();
auto props = session.TryGetMediaPropertiesAsync().get();
auto timeline = session.GetTimelineProperties();
bool isPaused = playback.PlaybackStatus() == GlobalSystemMediaTransportControlsSessionPlaybackStatus::Paused;
bool isPlaying = playback.PlaybackStatus() == GlobalSystemMediaTransportControlsSessionPlaybackStatus::Playing;
if (isPlaying || isPaused) {
std::string title_utf8 = winrt::to_string(props.Title());
std::string artist_utf8 = winrt::to_string(props.Artist());
std::string album_utf8 = winrt::to_string(props.AlbumTitle());
double pos = timeline.Position().count() / 1e7;
double dur = (timeline.EndTime() - timeline.StartTime()).count() / 1e7;
auto start = std::chrono::system_clock::now() - std::chrono::seconds((int)pos);
auto end = start + std::chrono::seconds((int)dur);
// Créer l'activité Discord pour Brave (watching video)
discordpp::Activity activity;
activity.SetType(discordpp::ActivityTypes::Watching);
activity.SetState(isPaused ? "⏸️ En pause" : ("par " + artist_utf8));
activity.SetDetails("🎬 " + title_utf8);
// Ajouter les assets d image
discordpp::ActivityAssets assets;
// Image par defaut pour Brave
assets.SetLargeImage("brave_logo");
assets.SetLargeText("Brave Browser");
// Ajouter une petite icône pour l etat de lecture
assets.SetSmallImage(isPaused ? "paused_icon" : "playing_icon");
assets.SetSmallText(isPaused ? "En pause" : "En lecture");
activity.SetAssets(assets);
if (isPlaying) {
double pos = timeline.Position().count() / 1e7;
double dur = (timeline.EndTime() - timeline.StartTime()).count() / 1e7;
auto start = std::chrono::system_clock::now() - std::chrono::seconds((int)pos);
auto end = start + std::chrono::seconds((int)dur);
discordpp::ActivityTimestamps timestamps;
timestamps.SetStart(std::chrono::duration_cast<std::chrono::seconds>(start.time_since_epoch()).count());
timestamps.SetEnd(std::chrono::duration_cast<std::chrono::seconds>(end.time_since_epoch()).count());
activity.SetTimestamps(timestamps);
}
brave_client->UpdateRichPresence(activity, [](discordpp::ClientResult result) {
if (result.Successful()) {
DebugLog("🎮 Brave Rich Presence mise a jour !");
}
});
} else {
brave_client->ClearRichPresence();
}
} else {
// Aucune session Deezer ou Brave active, on clear le statut Discord
deezer_client->ClearRichPresence();
brave_client->ClearRichPresence();
}
discordpp::RunCallbacks();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
// Nettoyer l icône du systray avant de quitter
Shell_NotifyIcon(NIM_DELETE, &nid);
return 0;
}