From 6e789fd83f300090a16cfc839059e2a512800ea5 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sat, 4 Jul 2026 01:49:42 +0300 Subject: [PATCH] Release 1.0.0 Signed-off-by: faumaray --- src/CoreClient.cpp | 127 ++++-- src/CoreClient.hpp | 17 +- src/main.cpp | 968 ++++++++++++++++++++++++++++++++++++++------- 3 files changed, 933 insertions(+), 179 deletions(-) diff --git a/src/CoreClient.cpp b/src/CoreClient.cpp index 59e909c..be020db 100644 --- a/src/CoreClient.cpp +++ b/src/CoreClient.cpp @@ -3,9 +3,30 @@ #include #include #include +#include namespace Echoion::Desktop { + namespace + { + // The server double-encodes payloads: RpcResponse.result / .error and + // RpcNotification.data are JSON *strings*. Decode such a string value + // into its object/array form (pass-through if already structured). + QJsonValue decodeEmbedded(const QJsonValue& v) + { + if (!v.isString()) { + return v; + } + QJsonDocument d = QJsonDocument::fromJson(v.toString().toUtf8()); + if (d.isObject()) { + return d.object(); + } + if (d.isArray()) { + return d.array(); + } + return QJsonValue(); + } + } // namespace CoreClient::CoreClient(QObject* parent) : QObject(parent), @@ -195,8 +216,13 @@ namespace Echoion::Desktop {"ManageUsers", 56}, {"GetServerInfo", 57}, {"RequestLoginToken", 58}, - {"ValidateLoginToken", 59}}; + {"ValidateLoginToken", 59}, + {"ToggleShuffle", 60}, + {"ToggleRepeat", 61}, + {"ShuffleQueue", 62}}; + // Values above are only used to reject locally-unknown methods; the wire + // contract is the method NAME (Core decodes RpcMethod by name). return methodMap.value(method, -1); } @@ -231,7 +257,12 @@ namespace Echoion::Desktop // Core deserializes RpcMethod via Void::Json reflection, which encodes // enums by name. methodInt above is only used to reject unknown methods. request["method"] = method; - request["params"] = params; + // RpcRequest.params is a JSON-encoded STRING on the server (handlers + // re-parse it via Void::Json::parse). Reflection rejects an object for a + // string field, so the params object must be serialized to a string + // here — otherwise the whole request fails to decode. + request["params"] = QString::fromUtf8( + QJsonDocument(params).toJson(QJsonDocument::Compact)); if (!authToken_.isEmpty()) { request["authToken"] = authToken_; @@ -288,7 +319,12 @@ namespace Echoion::Desktop QJsonObject request; request["id"] = static_cast(newRequestId); request["method"] = pending.method; - request["params"] = pending.params; + // Same wire format as sendRequest: the server's + // RpcRequest.params is a JSON-encoded STRING; a raw object + // here made every retried request fail to decode. + request["params"] = QString::fromUtf8( + QJsonDocument(pending.params) + .toJson(QJsonDocument::Compact)); if (!authToken_.isEmpty()) { request["authToken"] = authToken_; @@ -351,6 +387,10 @@ namespace Echoion::Desktop if (autoConnectEnabled_ && reconnectAttempts_ < MAX_RECONNECT_ATTEMPTS) { startReconnectTimer(); + } else if (autoConnectEnabled_) { + // Attempts exhausted: hand control back to the user (the UI + // shows a manual Reconnect action). + emit reconnectExhausted(); } } @@ -395,30 +435,52 @@ namespace Echoion::Desktop if (obj.contains("event")) { handleEvent(obj); - } else if (obj.contains("id")) { + } else if (obj.contains("requestId")) { handleRpcResponse(obj); } } void CoreClient::handleRpcResponse(const QJsonObject& response) { - quint64 requestId = response["id"].toVariant().toULongLong(); + quint64 requestId = + response["requestId"].toVariant().toULongLong(); auto it = pendingRequests_.find(requestId); - if (it != pendingRequests_.end()) { - auto callback = std::move(it->second.callback); - pendingRequests_.erase(it); - - if (callback) { - callback(response); - } + if (it == pendingRequests_.end()) { + return; } + auto callback = std::move(it->second.callback); + pendingRequests_.erase(it); + if (!callback) { + return; + } + + // Normalise into a flat object the callbacks can read directly: + // success (bool), data (decoded result payload), error, and a + // convenience message pulled from result/error. + const bool success = response["success"].toBool(); + QJsonValue data = decodeEmbedded(response.value("result")); + QJsonValue error = decodeEmbedded(response.value("error")); + + QString message; + if (data.isObject() && data.toObject().contains("message")) { + message = data.toObject()["message"].toString(); + } else if (error.isObject() && error.toObject().contains("message")) { + message = error.toObject()["message"].toString(); + } + + QJsonObject cb; + cb["success"] = success; + cb["data"] = data; + cb["error"] = error; + cb["message"] = message; + callback(cb); } void CoreClient::handleEvent(const QJsonObject& event) { QString eventName = event["event"].toString(); - QJsonObject data = event["data"].toObject(); + QJsonObject data = decodeEmbedded(event.value("data")).toObject(); emit eventReceived(eventName, data); @@ -470,8 +532,9 @@ namespace Echoion::Desktop void CoreClient::setVolume(int volume) { + // UI uses 0-100; the server's volume model is normalised 0.0-1.0. QJsonObject params; - params["volume"] = volume; + params["volume"] = std::clamp(volume, 0, 100) / 100.0; call("SetVolume", params); } @@ -483,24 +546,24 @@ namespace Echoion::Desktop call("QueueTrack", params); } - void CoreClient::removeFromQueue(int position) + void CoreClient::removeFromQueue(quint64 queueId) { QJsonObject params; - params["position"] = position; + params["queueId"] = static_cast(queueId); call("RemoveFromQueue", params); } void CoreClient::clearQueue() { call("ClearQueue"); } - void CoreClient::moveInQueue(int from, int to) + void CoreClient::moveInQueue(quint64 queueId, int newPosition) { QJsonObject params; - params["from"] = from; - params["to"] = to; + params["queueId"] = static_cast(queueId); + params["newPosition"] = newPosition; call("MoveInQueue", params); } - void CoreClient::shuffle() { call("Shuffle"); } + void CoreClient::shuffle() { call("ShuffleQueue"); } void CoreClient::toggleRepeat() { call("ToggleRepeat"); } void CoreClient::toggleShuffle() { call("ToggleShuffle"); } @@ -509,7 +572,7 @@ namespace Echoion::Desktop { QJsonObject params; params["query"] = query; - call("Search", params); + call("SearchTracks", params); } // Playlist management @@ -529,10 +592,30 @@ namespace Echoion::Desktop call("SavePlaylist", params); } + void CoreClient::deletePlaylist(const QString& playlistId) + { + QJsonObject params; + params["playlistId"] = playlistId; + call("DeletePlaylist", params); + } + void CoreClient::getUserPlaylists() { call("GetPlaylists"); } + // Configuration + void CoreClient::getConfig() { call("GetConfig"); } + + void CoreClient::setConfig(const QString& configJson) + { + // configJson is the full config object; forwarded as the params payload. + QJsonObject params = + QJsonDocument::fromJson(configJson.toUtf8()).object(); + call("SetConfig", params); + } + + void CoreClient::reloadConfig() { call("ReloadConfig"); } + // Data requests - void CoreClient::requestPlaybackState() { call("GetPlaybackState"); } + void CoreClient::requestPlaybackState() { call("GetStatus"); } void CoreClient::requestQueue() { call("GetQueue"); } void CoreClient::requestCurrentTrack() { call("GetCurrentTrack"); } diff --git a/src/CoreClient.hpp b/src/CoreClient.hpp index 8bcff64..d6c57e9 100644 --- a/src/CoreClient.hpp +++ b/src/CoreClient.hpp @@ -60,11 +60,11 @@ namespace Echoion::Desktop void seek(int positionMs); void setVolume(int volume); - // Queue management + // Queue management (queueId matches GetQueue items + queue events) void queueTrack(const QString& query); - void removeFromQueue(int position); + void removeFromQueue(quint64 queueId); void clearQueue(); - void moveInQueue(int from, int to); + void moveInQueue(quint64 queueId, int newPosition); void shuffle(); void toggleRepeat(); void toggleShuffle(); @@ -75,9 +75,16 @@ namespace Echoion::Desktop // Playlist management void loadPlaylist(const QString& playlistId); void savePlaylist(const QString& name, const QString& description); + void deletePlaylist(const QString& playlistId); void getUserPlaylists(); - // Data requests (fetch on demand) + // Configuration + void getConfig(); + void setConfig(const QString& configJson); + void reloadConfig(); + + // Data requests (fetch on demand). Data-returning calls may also be + // issued via call(method, params, callback) for a one-shot reply. void requestPlaybackState(); void requestQueue(); void requestCurrentTrack(); @@ -88,6 +95,8 @@ namespace Echoion::Desktop void connected(); void disconnected(); void reconnecting(int attempt); + // All automatic reconnect attempts failed; manual retry needed. + void reconnectExhausted(); void connectionError(const QString& error); void connectionFailed(const QString& reason); diff --git a/src/main.cpp b/src/main.cpp index f2970d6..fac5c2f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,28 +1,56 @@ #include "CoreClient.hpp" #include +#include #include #include #include +#include +#include +#include #include #include +#include +#include #include #include +#include +#include +#include #include +#include #include +#include +#include #include #include #include -#include using namespace Echoion::Desktop; -class SimpleMainWindow : public QMainWindow +namespace +{ + QString formatMs(qint64 ms) + { + if (ms < 0) { + ms = 0; + } + qint64 totalSec = ms / 1000; + return QString("%1:%2") + .arg(totalSec / 60) + .arg(totalSec % 60, 2, 10, QChar('0')); + } +} // namespace + +// Full desktop client for the Echoion RPC server: connection/auth plus tabbed +// panels (Now Playing, Queue, Search, Playlists, Admin) wired to the RPC API and +// live event stream. +class MainWindow : public QMainWindow { Q_OBJECT public: - SimpleMainWindow(CoreClient* client, QWidget* parent = nullptr) + MainWindow(CoreClient* client, QWidget* parent = nullptr) : QMainWindow(parent), client_(client) { setupUI(); @@ -34,16 +62,18 @@ class SimpleMainWindow : public QMainWindow void onConnectClicked() { - QString host = hostEdit->text(); + if (client_->isConnected()) { + client_->disconnectFromHost(); + return; + } + QString host = hostEdit_->text(); if (host.isEmpty()) { host = "localhost"; } - - int port = portEdit->text().toInt(); + int port = portEdit_->text().toInt(); if (port <= 0) { port = 8765; } - statusBar()->showMessage( QString("Connecting to %1:%2...").arg(host).arg(port)); client_->connectToHost(host, port); @@ -51,10 +81,9 @@ class SimpleMainWindow : public QMainWindow void onRequestTokenClicked() { - QString nickname = nicknameEdit->text(); + QString nickname = nicknameEdit_->text(); if (nickname.isEmpty()) { - QMessageBox::warning(this, "Error", - "Please enter your nickname"); + QMessageBox::warning(this, "Error", "Please enter your nickname"); return; } client_->requestAuthToken(nickname); @@ -62,7 +91,7 @@ class SimpleMainWindow : public QMainWindow void onAuthClicked() { - QString token = tokenEdit->text(); + QString token = tokenEdit_->text(); if (token.isEmpty()) { QMessageBox::warning(this, "Error", "Please enter the token"); return; @@ -84,25 +113,23 @@ class SimpleMainWindow : public QMainWindow void onAuthTokenRequested() { - QMessageBox::information( - this, "Token Requested", - "Please check your TeamSpeak PM for the authentication token."); - authStatus->setText("Token requested - check PM"); - authStatus->setStyleSheet("color: orange;"); + authStatus_->setText("Token requested - check PM"); + authStatus_->setStyleSheet("color: orange;"); } void onAuthenticated() { - authStatus->setText("Authenticated"); - authStatus->setStyleSheet("color: green;"); + authStatus_->setText("Authenticated"); + authStatus_->setStyleSheet("color: green;"); statusBar()->showMessage("Authenticated successfully"); - client_->requestPlaybackState(); + setControlsEnabled(true); + refreshAll(); } void onAuthFailed(const QString& reason) { - authStatus->setText("Auth failed"); - authStatus->setStyleSheet("color: red;"); + authStatus_->setText("Auth failed"); + authStatus_->setStyleSheet("color: red;"); QMessageBox::warning(this, "Authentication Failed", reason); } @@ -111,186 +138,821 @@ class SimpleMainWindow : public QMainWindow if (event == "playback.started" || event == "playback.trackChanged") { QJsonObject track = data["track"].toObject(); - QString title = track["title"].toString(); - QString artist = track["artist"].toString(); - currentTrackLabel->setText(title.isEmpty() ? "Unknown" : title); - artistLabel->setText(artist.isEmpty() ? "-" : artist); - playbackStatus->setText("Playing"); + trackTitle_->setText(track["title"].toString("Unknown")); + trackArtist_->setText(track["artist"].toString("-")); + playbackStatus_->setText("Playing"); + } else if (event == "playback.position") { + if (!seekSlider_->isSliderDown()) { + qint64 pos = data["position"].toVariant().toLongLong(); + qint64 dur = data["duration"].toVariant().toLongLong(); + seekSlider_->setMaximum(dur > 0 ? static_cast(dur) + : 1); + seekSlider_->setValue(static_cast(pos)); + timeLabel_->setText(formatMs(pos) + " / " + formatMs(dur)); + } } else if (event == "playback.paused") { - playbackStatus->setText("Paused"); + playbackStatus_->setText("Paused"); } else if (event == "playback.resumed") { - playbackStatus->setText("Playing"); - } else if (event == "playback.stopped") { - playbackStatus->setText("Stopped"); - currentTrackLabel->setText("No track playing"); - artistLabel->setText("-"); + playbackStatus_->setText("Playing"); + } else if (event == "playback.stopped" || + event == "playback.finished") { + playbackStatus_->setText("Stopped"); + if (tabs_->tabText(tabs_->currentIndex()) == "History") { + refreshHistory(); + } + } else if (event == "playback.volumeChanged") { + int v = static_cast(data["volume"].toDouble() * 100.0); + volumeSlider_->blockSignals(true); + volumeSlider_->setValue(v); + volumeSlider_->blockSignals(false); + } else if (event == "playback.shuffleChanged") { + shuffleBtn_->setChecked(data["shuffle"].toBool()); + } else if (event == "playback.repeatChanged") { + repeatBtn_->setChecked(data["repeat"].toBool()); + } else if (event.startsWith("queue.")) { + refreshQueue(); } } - void onPlayClicked() { client_->requestPlaybackState(); } - void onPauseClicked() { client_->pause(); } - void onSkipClicked() { client_->skip(); } - void updateConnectionStatus() { - if (client_->isConnected()) { - connectionStatus->setText("Connected"); - connectionStatus->setStyleSheet("color: green;"); - connectBtn->setText("Disconnect"); - } else { - connectionStatus->setText("Disconnected"); - connectionStatus->setStyleSheet("color: red;"); - connectBtn->setText("Connect"); + const bool connected = client_->isConnected(); + connectionStatus_->setText(connected ? "Connected" : "Disconnected"); + connectionStatus_->setStyleSheet(connected ? "color: green;" + : "color: red;"); + connectBtn_->setText(connected ? "Disconnect" : "Connect"); + if (!connected) { + setControlsEnabled(false); } } private: + // ── Data refreshers ───────────────────────────────────────────────── + + void refreshAll() + { + client_->requestPlaybackState(); + refreshQueue(); + } + + void refreshQueue() + { + client_->call("GetQueue", QJsonObject{}, + [this](const QJsonObject& r) { + if (!r["success"].toBool()) { + return; + } + applyingQueueUpdate_ = true; + queueList_->clear(); + for (const QJsonValue& v : + r["data"].toObject()["queue"].toArray()) { + QJsonObject item = v.toObject(); + QJsonObject track = item["track"].toObject(); + auto* li = new QListWidgetItem( + QString("%1 - %2") + .arg(track["title"].toString(), + track["artist"].toString())); + li->setData(Qt::UserRole, + item["queueId"].toVariant()); + queueList_->addItem(li); + } + applyingQueueUpdate_ = false; + }); + } + + void doSearch() + { + QString q = searchEdit_->text(); + if (q.isEmpty()) { + return; + } + QJsonObject params; + params["query"] = q; + client_->call("SearchTracks", params, + [this](const QJsonObject& r) { + searchList_->clear(); + if (!r["success"].toBool()) { + statusBar()->showMessage("Search failed: " + + r["message"].toString()); + return; + } + for (const QJsonValue& v : + r["data"].toObject()["tracks"].toArray()) { + QJsonObject t = v.toObject(); + auto* li = new QListWidgetItem( + QString("%1 - %2") + .arg(t["title"].toString(), + t["artist"].toString())); + li->setData(Qt::UserRole, t["id"].toString()); + const QString thumb = + t["thumbnailUrl"].toString(); + if (!thumb.isEmpty()) { + loadThumbnail(thumb, li); + } + searchList_->addItem(li); + } + }); + } + + // Fetch a thumbnail (cached) and set it as the item's icon. The item + // may be deleted before the reply lands, hence the QPointer-like + // guard via the list's item lookup. + void loadThumbnail(const QString& url, QListWidgetItem* item) + { + if (QPixmap cached; QPixmapCache::find(url, &cached)) { + item->setIcon(QIcon(cached)); + return; + } + QNetworkReply* reply = + thumbnailFetcher_.get(QNetworkRequest(QUrl(url))); + connect(reply, &QNetworkReply::finished, this, + [this, reply, url, item]() { + reply->deleteLater(); + if (reply->error() != QNetworkReply::NoError) { + return; + } + QPixmap pixmap; + if (!pixmap.loadFromData(reply->readAll())) { + return; + } + pixmap = pixmap.scaled(48, 48, Qt::KeepAspectRatio, + Qt::SmoothTransformation); + QPixmapCache::insert(url, pixmap); + // Only touch the item if it still exists in the list. + for (int i = 0; i < searchList_->count(); ++i) { + if (searchList_->item(i) == item) { + item->setIcon(QIcon(pixmap)); + break; + } + } + }); + } + + void refreshPlaylists() + { + client_->call("GetPlaylists", QJsonObject{}, + [this](const QJsonObject& r) { + playlistList_->clear(); + if (!r["success"].toBool()) { + return; + } + for (const QJsonValue& v : + r["data"].toObject()["playlists"].toArray()) { + QJsonObject p = v.toObject(); + auto* li = new QListWidgetItem( + QString("%1 (%2 tracks)") + .arg(p["name"].toString()) + .arg(p["trackCount"].toInt())); + li->setData(Qt::UserRole, p["id"].toString()); + playlistList_->addItem(li); + } + }); + } + + void showPlaylistContents(const QString& playlistId, + const QString& title) + { + QJsonObject params; + params["playlistId"] = playlistId; + client_->call("GetPlaylist", params, [this, title]( + const QJsonObject& r) { + if (!r["success"].toBool()) { + statusBar()->showMessage("Couldn't load playlist: " + + r["message"].toString()); + return; + } + QJsonArray tracks = r["data"].toObject()["tracks"].toArray(); + + auto* dialog = new QDialog(this); + dialog->setAttribute(Qt::WA_DeleteOnClose); + dialog->setWindowTitle(title); + dialog->resize(480, 420); + auto* layout = new QVBoxLayout(dialog); + auto* list = new QListWidget(dialog); + for (const QJsonValue& v : tracks) { + QJsonObject t = v.toObject(); + auto* li = new QListWidgetItem( + QString("%1 - %2").arg(t["title"].toString(), + t["artist"].toString())); + li->setData(Qt::UserRole, t["url"].toString( + t["id"].toString())); + list->addItem(li); + } + layout->addWidget(list); + + auto* buttons = new QHBoxLayout(); + auto* queueOne = new QPushButton("Queue Selected", dialog); + auto* queueAll = new QPushButton("Queue All", dialog); + buttons->addWidget(queueOne); + buttons->addWidget(queueAll); + layout->addLayout(buttons); + + connect(queueOne, &QPushButton::clicked, dialog, + [this, list]() { + if (auto* it = list->currentItem()) { + client_->queueTrack( + it->data(Qt::UserRole).toString()); + } + }); + connect(queueAll, &QPushButton::clicked, dialog, + [this, list]() { + for (int i = 0; i < list->count(); ++i) { + client_->queueTrack(list->item(i) + ->data(Qt::UserRole) + .toString()); + } + }); + dialog->show(); + }); + } + + void refreshHistory() + { + QJsonObject params; + params["limit"] = 25; + client_->call("GetHistory", params, [this](const QJsonObject& r) { + if (!r["success"].toBool()) { + return; + } + historyList_->clear(); + for (const QJsonValue& v : + r["data"].toObject()["tracks"].toArray()) { + QJsonObject t = v.toObject(); + auto* li = new QListWidgetItem( + QString("%1 - %2").arg(t["title"].toString(), + t["artist"].toString())); + li->setData(Qt::UserRole, + t["url"].toString(t["id"].toString())); + historyList_->addItem(li); + } + }); + client_->call("GetStats", QJsonObject{}, + [this](const QJsonObject& r) { + if (!r["success"].toBool()) { + return; + } + QJsonObject d = r["data"].toObject(); + const qint64 playtimeMin = + d["totalPlaytimeMs"].toVariant() + .toLongLong() / + 60000; + QString text = + QString("Plays: %1 · Unique tracks: %2 · " + "Playtime: %3h %4m") + .arg(d["totalPlays"].toVariant() + .toLongLong()) + .arg(d["totalTracks"].toVariant() + .toLongLong()) + .arg(playtimeMin / 60) + .arg(playtimeMin % 60); + const QString top = + d["mostPlayedTitle"].toString(); + if (!top.isEmpty()) { + text += QString("\nMost played: %1 (%2x)") + .arg(top) + .arg(d["mostPlayedCount"] + .toVariant() + .toLongLong()); + } + historyStats_->setText(text); + }); + } + + void refreshServerInfo() + { + client_->call("GetServerInfo", QJsonObject{}, + [this](const QJsonObject& r) { + if (!r["success"].toBool()) { + return; + } + QJsonObject d = r["data"].toObject(); + serverInfo_->setText( + QString("Version: %1\nUptime: %2s\nClients: " + "%3\nSubscribers: %4\nQueue: %5") + .arg(d["version"].toString()) + .arg(d["uptimeSeconds"].toVariant() + .toLongLong()) + .arg(d["connectedClients"].toInt()) + .arg(d["subscribers"].toInt()) + .arg(d["queueLength"].toInt())); + }); + } + + void refreshAuditLog() + { + client_->call("GetAuditLog", QJsonObject{}, + [this](const QJsonObject& r) { + auditList_->clear(); + if (!r["success"].toBool()) { + auditList_->addItem(r["message"].toString( + "Permission denied")); + return; + } + for (const QJsonValue& v : + r["data"].toObject()["entries"].toArray()) { + QJsonObject e = v.toObject(); + auditList_->addItem( + QString("client %1 → method %2") + .arg(e["clientId"].toVariant() + .toLongLong()) + .arg(e["method"].toInt())); + } + }); + } + + // ── UI construction ───────────────────────────────────────────────── + void setupUI() { setWindowTitle("Echoion Desktop Client"); - setMinimumSize(600, 400); + setMinimumSize(720, 560); - auto* centralWidget = new QWidget(this); - setCentralWidget(centralWidget); + auto* central = new QWidget(this); + setCentralWidget(central); + auto* root = new QVBoxLayout(central); - auto* mainLayout = new QVBoxLayout(centralWidget); + root->addWidget(buildConnectionBar()); - // Connection Section - auto* connGroup = new QGroupBox("Connection", this); - auto* connLayout = new QFormLayout(connGroup); + tabs_ = new QTabWidget(this); + tabs_->addTab(buildNowPlayingTab(), "Now Playing"); + tabs_->addTab(buildQueueTab(), "Queue"); + tabs_->addTab(buildSearchTab(), "Search"); + tabs_->addTab(buildPlaylistsTab(), "Playlists"); + tabs_->addTab(buildHistoryTab(), "History"); + tabs_->addTab(buildAdminTab(), "Admin"); + connect(tabs_, &QTabWidget::currentChanged, this, + [this](int index) { + if (tabs_->tabText(index) == "History") { + refreshHistory(); + } + }); + root->addWidget(tabs_); - hostEdit = new QLineEdit(this); - hostEdit->setPlaceholderText("localhost"); - connLayout->addRow("Host:", hostEdit); - - portEdit = new QLineEdit(this); - portEdit->setText("8765"); - connLayout->addRow("Port:", portEdit); - - auto* connBtnLayout = new QHBoxLayout(); - connectBtn = new QPushButton("Connect", this); - connectionStatus = new QLabel("Disconnected", this); - connectionStatus->setStyleSheet("color: red;"); - connBtnLayout->addWidget(connectBtn); - connBtnLayout->addWidget(connectionStatus); - connBtnLayout->addStretch(); - connLayout->addRow(connBtnLayout); - - mainLayout->addWidget(connGroup); - - // Auth Section - auto* authGroup = new QGroupBox("Authentication", this); - auto* authLayout = new QFormLayout(authGroup); - - nicknameEdit = new QLineEdit(this); - nicknameEdit->setPlaceholderText("Your TeamSpeak nickname"); - authLayout->addRow("Nickname:", nicknameEdit); - - tokenEdit = new QLineEdit(this); - tokenEdit->setPlaceholderText("Token from PM"); - tokenEdit->setEchoMode(QLineEdit::Password); - authLayout->addRow("Token:", tokenEdit); - - auto* authBtnLayout = new QHBoxLayout(); - requestTokenBtn = new QPushButton("Request Token", this); - authBtn = new QPushButton("Authenticate", this); - authStatus = new QLabel("Not authenticated", this); - authStatus->setStyleSheet("color: red;"); - authBtnLayout->addWidget(requestTokenBtn); - authBtnLayout->addWidget(authBtn); - authBtnLayout->addWidget(authStatus); - authBtnLayout->addStretch(); - authLayout->addRow(authBtnLayout); - - mainLayout->addWidget(authGroup); - - // Playback Section - auto* playbackGroup = new QGroupBox("Current Playback", this); - auto* playbackLayout = new QVBoxLayout(playbackGroup); - - currentTrackLabel = new QLabel("No track playing", this); - currentTrackLabel->setStyleSheet( - "font-size: 14px; font-weight: bold;"); - playbackLayout->addWidget(currentTrackLabel); - - artistLabel = new QLabel("-", this); - artistLabel->setStyleSheet("color: gray;"); - playbackLayout->addWidget(artistLabel); - - playbackStatus = new QLabel("Stopped", this); - playbackLayout->addWidget(playbackStatus); - - auto* controlLayout = new QHBoxLayout(); - auto* playBtn = new QPushButton("Play", this); - auto* pauseBtn = new QPushButton("Pause", this); - auto* skipBtn = new QPushButton("Skip", this); - controlLayout->addWidget(playBtn); - controlLayout->addWidget(pauseBtn); - controlLayout->addWidget(skipBtn); - controlLayout->addStretch(); - playbackLayout->addLayout(controlLayout); - - mainLayout->addWidget(playbackGroup); - mainLayout->addStretch(); - - // Status Bar statusBar()->showMessage("Ready"); + setControlsEnabled(false); + } - // Connect UI signals - connect(connectBtn, &QPushButton::clicked, this, - &SimpleMainWindow::onConnectClicked); - connect(requestTokenBtn, &QPushButton::clicked, this, - &SimpleMainWindow::onRequestTokenClicked); - connect(authBtn, &QPushButton::clicked, this, - &SimpleMainWindow::onAuthClicked); - connect(playBtn, &QPushButton::clicked, this, - &SimpleMainWindow::onPlayClicked); - connect(pauseBtn, &QPushButton::clicked, this, - &SimpleMainWindow::onPauseClicked); + QWidget* buildConnectionBar() + { + auto* box = new QGroupBox("Connection && Authentication", this); + auto* form = new QFormLayout(box); + + auto* connRow = new QHBoxLayout(); + hostEdit_ = new QLineEdit(this); + hostEdit_->setPlaceholderText("localhost"); + portEdit_ = new QLineEdit("8765", this); + portEdit_->setFixedWidth(70); + connectBtn_ = new QPushButton("Connect", this); + connectionStatus_ = new QLabel("Disconnected", this); + connectionStatus_->setStyleSheet("color: red;"); + connRow->addWidget(hostEdit_); + connRow->addWidget(portEdit_); + connRow->addWidget(connectBtn_); + connRow->addWidget(connectionStatus_); + form->addRow("Server:", connRow); + + auto* authRow = new QHBoxLayout(); + nicknameEdit_ = new QLineEdit(this); + nicknameEdit_->setPlaceholderText("TeamSpeak nickname"); + requestTokenBtn_ = new QPushButton("Request Token", this); + tokenEdit_ = new QLineEdit(this); + tokenEdit_->setPlaceholderText("Token from PM"); + tokenEdit_->setEchoMode(QLineEdit::Password); + authBtn_ = new QPushButton("Authenticate", this); + authStatus_ = new QLabel("Not authenticated", this); + authStatus_->setStyleSheet("color: red;"); + authRow->addWidget(nicknameEdit_); + authRow->addWidget(requestTokenBtn_); + authRow->addWidget(tokenEdit_); + authRow->addWidget(authBtn_); + authRow->addWidget(authStatus_); + form->addRow("Auth:", authRow); + + return box; + } + + QWidget* buildNowPlayingTab() + { + auto* w = new QWidget(this); + auto* l = new QVBoxLayout(w); + + trackTitle_ = new QLabel("No track playing", this); + trackTitle_->setStyleSheet("font-size: 16px; font-weight: bold;"); + trackArtist_ = new QLabel("-", this); + trackArtist_->setStyleSheet("color: gray;"); + playbackStatus_ = new QLabel("Stopped", this); + l->addWidget(trackTitle_); + l->addWidget(trackArtist_); + l->addWidget(playbackStatus_); + + auto* seekRow = new QHBoxLayout(); + seekSlider_ = new QSlider(Qt::Horizontal, this); + seekSlider_->setMaximum(1); + timeLabel_ = new QLabel("0:00 / 0:00", this); + seekRow->addWidget(seekSlider_); + seekRow->addWidget(timeLabel_); + l->addLayout(seekRow); + + auto* playRow = new QHBoxLayout(); + playQueryEdit_ = new QLineEdit(this); + playQueryEdit_->setPlaceholderText( + "Song name or URL to play / queue"); + auto* playBtn = new QPushButton("Play", this); + auto* queueBtn = new QPushButton("Queue", this); + playRow->addWidget(playQueryEdit_); + playRow->addWidget(playBtn); + playRow->addWidget(queueBtn); + l->addLayout(playRow); + + auto* ctrlRow = new QHBoxLayout(); + auto* pauseBtn = new QPushButton("Pause", this); + auto* resumeBtn = new QPushButton("Resume", this); + auto* stopBtn = new QPushButton("Stop", this); + auto* skipBtn = new QPushButton("Skip", this); + shuffleBtn_ = new QPushButton("Shuffle", this); + shuffleBtn_->setCheckable(true); + repeatBtn_ = new QPushButton("Repeat", this); + repeatBtn_->setCheckable(true); + ctrlRow->addWidget(pauseBtn); + ctrlRow->addWidget(resumeBtn); + ctrlRow->addWidget(stopBtn); + ctrlRow->addWidget(skipBtn); + ctrlRow->addWidget(shuffleBtn_); + ctrlRow->addWidget(repeatBtn_); + l->addLayout(ctrlRow); + + auto* volRow = new QHBoxLayout(); + volRow->addWidget(new QLabel("Volume:", this)); + volumeSlider_ = new QSlider(Qt::Horizontal, this); + volumeSlider_->setRange(0, 100); + volumeSlider_->setValue(50); + volRow->addWidget(volumeSlider_); + l->addLayout(volRow); + l->addStretch(); + + connect(playBtn, &QPushButton::clicked, this, [this]() { + if (!playQueryEdit_->text().isEmpty()) { + client_->play(playQueryEdit_->text()); + } + }); + connect(queueBtn, &QPushButton::clicked, this, [this]() { + if (!playQueryEdit_->text().isEmpty()) { + client_->queueTrack(playQueryEdit_->text()); + } + }); + connect(pauseBtn, &QPushButton::clicked, client_, + &CoreClient::pause); + connect(resumeBtn, &QPushButton::clicked, client_, + &CoreClient::resume); + connect(stopBtn, &QPushButton::clicked, client_, &CoreClient::stop); connect(skipBtn, &QPushButton::clicked, this, - &SimpleMainWindow::onSkipClicked); + [this]() { client_->skip(1); }); + connect(shuffleBtn_, &QPushButton::clicked, client_, + &CoreClient::toggleShuffle); + connect(repeatBtn_, &QPushButton::clicked, client_, + &CoreClient::toggleRepeat); + connect(seekSlider_, &QSlider::sliderReleased, this, [this]() { + client_->seek(seekSlider_->value()); + }); + connect(volumeSlider_, &QSlider::sliderReleased, this, [this]() { + client_->setVolume(volumeSlider_->value()); + }); + return w; + } + + QWidget* buildQueueTab() + { + auto* w = new QWidget(this); + auto* l = new QVBoxLayout(w); + queueList_ = new QListWidget(this); + // Drag-drop reordering: a local row move is translated into a + // MoveInQueue RPC. The applyingQueueUpdate_ guard stops the + // server's queue.reordered broadcast (which triggers a refresh) + // from echoing back as another move. + queueList_->setDragDropMode(QAbstractItemView::InternalMove); + queueList_->setDefaultDropAction(Qt::MoveAction); + connect(queueList_->model(), &QAbstractItemModel::rowsMoved, this, + [this](const QModelIndex&, int from, int, const QModelIndex&, + int to) { + if (applyingQueueUpdate_) { + return; + } + // rowsMoved reports the pre-removal target index. + const int dest = to > from ? to - 1 : to; + if (auto* it = queueList_->item(dest)) { + client_->moveInQueue( + it->data(Qt::UserRole).toULongLong(), dest); + } + }); + l->addWidget(queueList_); + auto* row = new QHBoxLayout(); + auto* refresh = new QPushButton("Refresh", this); + auto* remove = new QPushButton("Remove", this); + auto* up = new QPushButton("Move Up", this); + auto* down = new QPushButton("Move Down", this); + auto* clear = new QPushButton("Clear", this); + row->addWidget(refresh); + row->addWidget(remove); + row->addWidget(up); + row->addWidget(down); + row->addWidget(clear); + l->addLayout(row); + + connect(refresh, &QPushButton::clicked, this, + &MainWindow::refreshQueue); + connect(clear, &QPushButton::clicked, client_, + &CoreClient::clearQueue); + connect(remove, &QPushButton::clicked, this, [this]() { + if (auto* it = queueList_->currentItem()) { + client_->removeFromQueue( + it->data(Qt::UserRole).toULongLong()); + } + }); + connect(up, &QPushButton::clicked, this, [this]() { + int r = queueList_->currentRow(); + if (auto* it = queueList_->currentItem(); it && r > 0) { + client_->moveInQueue( + it->data(Qt::UserRole).toULongLong(), r - 1); + } + }); + connect(down, &QPushButton::clicked, this, [this]() { + int r = queueList_->currentRow(); + if (auto* it = queueList_->currentItem(); + it && r < queueList_->count() - 1) { + client_->moveInQueue( + it->data(Qt::UserRole).toULongLong(), r + 1); + } + }); + return w; + } + + QWidget* buildHistoryTab() + { + auto* w = new QWidget(this); + auto* l = new QVBoxLayout(w); + historyStats_ = new QLabel("No statistics yet.", this); + l->addWidget(historyStats_); + historyList_ = new QListWidget(this); + l->addWidget(historyList_); + auto* row = new QHBoxLayout(); + auto* refresh = new QPushButton("Refresh", this); + auto* playSel = new QPushButton("Play Selected", this); + row->addWidget(refresh); + row->addWidget(playSel); + l->addLayout(row); + + connect(refresh, &QPushButton::clicked, this, + &MainWindow::refreshHistory); + auto playItem = [this](QListWidgetItem* it) { + if (it) { + client_->play(it->data(Qt::UserRole).toString()); + } + }; + connect(playSel, &QPushButton::clicked, this, [this, playItem]() { + playItem(historyList_->currentItem()); + }); + connect(historyList_, &QListWidget::itemDoubleClicked, this, + [playItem](QListWidgetItem* it) { playItem(it); }); + return w; + } + + QWidget* buildSearchTab() + { + auto* w = new QWidget(this); + auto* l = new QVBoxLayout(w); + auto* row = new QHBoxLayout(); + searchEdit_ = new QLineEdit(this); + searchEdit_->setPlaceholderText("Search query"); + auto* searchBtn = new QPushButton("Search", this); + row->addWidget(searchEdit_); + row->addWidget(searchBtn); + l->addLayout(row); + searchList_ = new QListWidget(this); + l->addWidget(searchList_); + auto* actions = new QHBoxLayout(); + auto* playSel = new QPushButton("Play Selected", this); + auto* queueSel = new QPushButton("Queue Selected", this); + actions->addWidget(playSel); + actions->addWidget(queueSel); + l->addLayout(actions); + + connect(searchBtn, &QPushButton::clicked, this, + &MainWindow::doSearch); + connect(searchEdit_, &QLineEdit::returnPressed, this, + &MainWindow::doSearch); + connect(playSel, &QPushButton::clicked, this, [this]() { + if (auto* it = searchList_->currentItem()) { + client_->play(it->data(Qt::UserRole).toString()); + } + }); + connect(queueSel, &QPushButton::clicked, this, [this]() { + if (auto* it = searchList_->currentItem()) { + client_->queueTrack(it->data(Qt::UserRole).toString()); + } + }); + return w; + } + + QWidget* buildPlaylistsTab() + { + auto* w = new QWidget(this); + auto* l = new QVBoxLayout(w); + playlistList_ = new QListWidget(this); + l->addWidget(playlistList_); + auto* row = new QHBoxLayout(); + auto* refresh = new QPushButton("Refresh", this); + auto* load = new QPushButton("Load", this); + auto* save = new QPushButton("Save Queue As...", this); + auto* del = new QPushButton("Delete", this); + row->addWidget(refresh); + row->addWidget(load); + row->addWidget(save); + row->addWidget(del); + l->addLayout(row); + + connect(refresh, &QPushButton::clicked, this, + &MainWindow::refreshPlaylists); + connect(load, &QPushButton::clicked, this, [this]() { + if (auto* it = playlistList_->currentItem()) { + client_->loadPlaylist(it->data(Qt::UserRole).toString()); + } + }); + connect(playlistList_, &QListWidget::itemDoubleClicked, this, + [this](QListWidgetItem* it) { + showPlaylistContents( + it->data(Qt::UserRole).toString(), it->text()); + }); + connect(del, &QPushButton::clicked, this, [this]() { + if (auto* it = playlistList_->currentItem()) { + client_->deletePlaylist(it->data(Qt::UserRole).toString()); + QTimer::singleShot(200, this, + &MainWindow::refreshPlaylists); + } + }); + connect(save, &QPushButton::clicked, this, [this]() { + bool ok = false; + QString name = QInputDialog::getText( + this, "Save Playlist", "Name:", QLineEdit::Normal, "", &ok); + if (ok && !name.isEmpty()) { + client_->savePlaylist(name, ""); + QTimer::singleShot(300, this, + &MainWindow::refreshPlaylists); + } + }); + return w; + } + + QWidget* buildAdminTab() + { + auto* w = new QWidget(this); + auto* l = new QVBoxLayout(w); + + serverInfo_ = new QLabel("(not loaded)", this); + l->addWidget(serverInfo_); + auto* infoRow = new QHBoxLayout(); + auto* refreshInfo = new QPushButton("Refresh Info", this); + auto* hotReload = new QPushButton("Hot Reload", this); + auto* shutdown = new QPushButton("Shutdown", this); + infoRow->addWidget(refreshInfo); + infoRow->addWidget(hotReload); + infoRow->addWidget(shutdown); + infoRow->addStretch(); + l->addLayout(infoRow); + + l->addWidget(new QLabel("Audit log:", this)); + auditList_ = new QListWidget(this); + l->addWidget(auditList_); + auto* auditBtn = new QPushButton("Refresh Audit Log", this); + l->addWidget(auditBtn); + + l->addWidget(new QLabel("Config (JSON):", this)); + configEdit_ = new QTextEdit(this); + l->addWidget(configEdit_); + auto* cfgRow = new QHBoxLayout(); + auto* getCfg = new QPushButton("Get", this); + auto* setCfg = new QPushButton("Apply", this); + auto* reloadCfg = new QPushButton("Reload", this); + cfgRow->addWidget(getCfg); + cfgRow->addWidget(setCfg); + cfgRow->addWidget(reloadCfg); + l->addLayout(cfgRow); + + connect(refreshInfo, &QPushButton::clicked, this, + &MainWindow::refreshServerInfo); + connect(auditBtn, &QPushButton::clicked, this, + &MainWindow::refreshAuditLog); + connect(hotReload, &QPushButton::clicked, this, + [this]() { client_->call("HotReload", QJsonObject{}); }); + connect(shutdown, &QPushButton::clicked, this, [this]() { + if (QMessageBox::question(this, "Shutdown", + "Shut down the bot?") == + QMessageBox::Yes) { + client_->call("Shutdown", QJsonObject{}); + } + }); + connect(getCfg, &QPushButton::clicked, this, [this]() { + client_->call( + "GetConfig", QJsonObject{}, [this](const QJsonObject& r) { + if (r["success"].toBool()) { + configEdit_->setPlainText( + QString::fromUtf8(QJsonDocument(r["data"] + .toObject()) + .toJson())); + } else { + configEdit_->setPlainText(r["message"].toString( + "Permission denied")); + } + }); + }); + connect(setCfg, &QPushButton::clicked, this, [this]() { + client_->setConfig(configEdit_->toPlainText()); + }); + connect(reloadCfg, &QPushButton::clicked, client_, + &CoreClient::reloadConfig); + return w; } void setupConnections() { + connect(connectBtn_, &QPushButton::clicked, this, + &MainWindow::onConnectClicked); + connect(requestTokenBtn_, &QPushButton::clicked, this, + &MainWindow::onRequestTokenClicked); + connect(authBtn_, &QPushButton::clicked, this, + &MainWindow::onAuthClicked); + connect(client_, &CoreClient::connected, this, - &SimpleMainWindow::onConnected); + &MainWindow::onConnected); connect(client_, &CoreClient::disconnected, this, - &SimpleMainWindow::onDisconnected); + &MainWindow::onDisconnected); connect(client_, &CoreClient::authTokenRequested, this, - &SimpleMainWindow::onAuthTokenRequested); + &MainWindow::onAuthTokenRequested); connect(client_, &CoreClient::authenticated, this, - &SimpleMainWindow::onAuthenticated); + &MainWindow::onAuthenticated); connect(client_, &CoreClient::authFailed, this, - &SimpleMainWindow::onAuthFailed); + &MainWindow::onAuthFailed); connect(client_, &CoreClient::eventReceived, this, - &SimpleMainWindow::onEventReceived); + &MainWindow::onEventReceived); + connect(client_, &CoreClient::reconnecting, this, + [this](int attempt) { + statusBar()->showMessage( + QString("Reconnecting (attempt %1)...") + .arg(attempt)); + }); + connect(client_, &CoreClient::reconnectExhausted, this, [this]() { + const auto choice = QMessageBox::warning( + this, "Connection lost", + "Automatic reconnection failed. Retry?", + QMessageBox::Retry | QMessageBox::Cancel); + if (choice == QMessageBox::Retry) { + onConnectClicked(); + } + }); } + void setControlsEnabled(bool on) { tabs_->setEnabled(on); } + CoreClient* client_; - QLineEdit *hostEdit, *portEdit, *nicknameEdit, *tokenEdit; - QPushButton *connectBtn, *requestTokenBtn, *authBtn; - QLabel *connectionStatus, *authStatus, *currentTrackLabel, *artistLabel, - *playbackStatus; + + // Connection / auth + QLineEdit *hostEdit_, *portEdit_, *nicknameEdit_, *tokenEdit_; + QPushButton *connectBtn_, *requestTokenBtn_, *authBtn_; + QLabel *connectionStatus_, *authStatus_; + + QTabWidget* tabs_; + + // Now Playing + QLabel *trackTitle_, *trackArtist_, *playbackStatus_, *timeLabel_; + QSlider *seekSlider_, *volumeSlider_; + QLineEdit* playQueryEdit_; + QPushButton *shuffleBtn_, *repeatBtn_; + + // Queue / Search / Playlists / History + QListWidget *queueList_, *searchList_, *playlistList_, *historyList_; + QLabel* historyStats_; + QLineEdit* searchEdit_; + QNetworkAccessManager thumbnailFetcher_; + bool applyingQueueUpdate_ = false; + + // Admin + QLabel* serverInfo_; + QListWidget* auditList_; + QTextEdit* configEdit_; }; int main(int argc, char* argv[]) { QApplication app(argc, argv); - app.setApplicationName("Echoion Desktop"); app.setOrganizationName("Echoion"); CoreClient coreClient; - - // Load settings and attempt auto-connect coreClient.loadSettings(); - SimpleMainWindow window(&coreClient); + MainWindow window(&coreClient); window.show(); - // Start auto-connect if enabled QTimer::singleShot(100, &coreClient, &CoreClient::startAutoConnect); return app.exec();