Merge branch 'eventbust' into 'main'
Bump CMake minimum to 4.0 for VoidLibrary toolchain See merge request void/echoiondesktop!1
This commit is contained in:
commit
bf1cd8e08d
12 files changed
+1784
-1208
No files matched your search
+5
-9
@@ -1,4 +1,4 @@
|
|||||||
cmake_minimum_required(VERSION 3.28)
|
cmake_minimum_required(VERSION 4.0.0)
|
||||||
project(EchoionDesktop VERSION 1.0.0 LANGUAGES CXX)
|
project(EchoionDesktop VERSION 1.0.0 LANGUAGES CXX)
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 26)
|
set(CMAKE_CXX_STANDARD 26)
|
||||||
@@ -11,15 +11,11 @@ set(CMAKE_AUTOUIC ON)
|
|||||||
|
|
||||||
find_package(Qt6 REQUIRED COMPONENTS Core Widgets Network WebSockets)
|
find_package(Qt6 REQUIRED COMPONENTS Core Widgets Network WebSockets)
|
||||||
|
|
||||||
add_executable(EchoionDesktop
|
file(GLOB_RECURSE DESKTOP_SOURCES
|
||||||
src/main.cpp
|
CONFIGURE_DEPENDS
|
||||||
src/MainWindow.cpp
|
"src/**.cpp"
|
||||||
src/MainWindow.hpp
|
|
||||||
src/LoginDialog.cpp
|
|
||||||
src/LoginDialog.hpp
|
|
||||||
src/CoreClient.cpp
|
|
||||||
src/CoreClient.hpp
|
|
||||||
)
|
)
|
||||||
|
add_executable(EchoionDesktop ${DESKTOP_SOURCES})
|
||||||
|
|
||||||
add_executable(Echoion::Desktop ALIAS EchoionDesktop)
|
add_executable(Echoion::Desktop ALIAS EchoionDesktop)
|
||||||
|
|
||||||
|
|||||||
+489
-389
@@ -1,439 +1,539 @@
|
|||||||
#include "CoreClient.hpp"
|
#include "CoreClient.hpp"
|
||||||
#include <QJsonDocument>
|
|
||||||
#include <QJsonArray>
|
#include <QJsonArray>
|
||||||
|
#include <QJsonDocument>
|
||||||
#include <QTimer>
|
#include <QTimer>
|
||||||
#include <QUuid>
|
#include <QtEndian>
|
||||||
#include <iostream>
|
|
||||||
|
|
||||||
namespace Echoion::Desktop {
|
namespace Echoion::Desktop
|
||||||
|
{
|
||||||
|
|
||||||
CoreClient::CoreClient(QObject* parent)
|
CoreClient::CoreClient(QObject* parent)
|
||||||
: QObject(parent)
|
: QObject(parent),
|
||||||
, socket_(new QWebSocket(QString(), QWebSocketProtocol::VersionLatest, this)) {
|
socket_(new QWebSocket(QString(), QWebSocketProtocol::VersionLatest,
|
||||||
|
this)),
|
||||||
connect(socket_, &QWebSocket::connected, this, &CoreClient::onConnected);
|
reconnectTimer_(new QTimer(this))
|
||||||
connect(socket_, &QWebSocket::disconnected, this, &CoreClient::onDisconnected);
|
{
|
||||||
connect(socket_, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
|
setupSocket();
|
||||||
this, &CoreClient::onError);
|
|
||||||
connect(socket_, &QWebSocket::textMessageReceived, this, &CoreClient::onMessageReceived);
|
|
||||||
connect(socket_, &QWebSocket::binaryMessageReceived, this, &CoreClient::onBinaryMessageReceived);
|
|
||||||
}
|
|
||||||
|
|
||||||
CoreClient::~CoreClient() {
|
reconnectTimer_->setSingleShot(true);
|
||||||
disconnectFromCore();
|
connect(reconnectTimer_, &QTimer::timeout, this,
|
||||||
}
|
&CoreClient::onReconnectTimer);
|
||||||
|
}
|
||||||
|
|
||||||
void CoreClient::connectToCore(const QString& host, int port) {
|
CoreClient::~CoreClient() { disconnectFromHost(); }
|
||||||
QString url = QString("ws://%1:%2/rpc").arg(host).arg(port);
|
|
||||||
socket_->open(QUrl(url));
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::disconnectFromCore() {
|
void CoreClient::setupSocket()
|
||||||
shouldReconnect_ = false;
|
{
|
||||||
if (socket_->state() != QAbstractSocket::UnconnectedState) {
|
connect(socket_, &QWebSocket::connected, this,
|
||||||
socket_->close();
|
&CoreClient::onSocketConnected);
|
||||||
}
|
connect(socket_, &QWebSocket::disconnected, this,
|
||||||
}
|
&CoreClient::onSocketDisconnected);
|
||||||
|
connect(socket_,
|
||||||
|
QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
|
||||||
|
this, &CoreClient::onSocketError);
|
||||||
|
connect(socket_, &QWebSocket::textMessageReceived, this,
|
||||||
|
&CoreClient::onTextMessageReceived);
|
||||||
|
}
|
||||||
|
|
||||||
bool CoreClient::isConnected() const {
|
void CoreClient::loadSettings() { settingsManager_.load(); }
|
||||||
return socket_->state() == QAbstractSocket::ConnectedState;
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::authenticate(const QString& username, const QString& password) {
|
void CoreClient::saveSettings() { settingsManager_.save(); }
|
||||||
QJsonObject params;
|
|
||||||
params["username"] = username;
|
|
||||||
params["password"] = password;
|
|
||||||
|
|
||||||
sendRpcRequest("auth.login", params, [this](const QJsonObject& result) {
|
|
||||||
if (result["success"].toBool()) {
|
|
||||||
authToken_ = result["token"].toString();
|
|
||||||
emit authenticationSuccess(authToken_);
|
|
||||||
} else {
|
|
||||||
emit authenticationFailed(result["error"].toString("Unknown error"));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::logout() {
|
void CoreClient::enableAutoConnect(bool enabled)
|
||||||
sendRpcRequest("auth.logout");
|
{
|
||||||
authToken_.clear();
|
autoConnectEnabled_ = enabled;
|
||||||
emit loggedOut();
|
settingsManager_.settings().autoConnect = enabled;
|
||||||
}
|
settingsManager_.save();
|
||||||
|
}
|
||||||
|
|
||||||
bool CoreClient::isAuthenticated() const {
|
bool CoreClient::autoConnectEnabled() const { return autoConnectEnabled_; }
|
||||||
return !authToken_.isEmpty();
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::play(const QString& query) {
|
void CoreClient::startAutoConnect()
|
||||||
QJsonObject params;
|
{
|
||||||
params["query"] = query;
|
if (!autoConnectEnabled_) {
|
||||||
sendRpcRequest("playback.play", params);
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::pause() {
|
auto profile = settingsManager_.getDefaultProfile();
|
||||||
sendRpcRequest("playback.pause");
|
if (profile) {
|
||||||
}
|
currentHost_ = profile->host;
|
||||||
|
currentPort_ = profile->port;
|
||||||
|
currentNickname_ = profile->nickname;
|
||||||
|
|
||||||
void CoreClient::resume() {
|
emit reconnecting(0);
|
||||||
sendRpcRequest("playback.resume");
|
connectToHost(profile->host, profile->port);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void CoreClient::stop() {
|
void CoreClient::connectToHost(const QString& host, int port)
|
||||||
sendRpcRequest("playback.stop");
|
{
|
||||||
}
|
currentHost_ = host;
|
||||||
|
currentPort_ = port;
|
||||||
|
|
||||||
void CoreClient::skip(int count) {
|
// Reset reconnection attempts for manual connection
|
||||||
QJsonObject params;
|
reconnectAttempts_ = 0;
|
||||||
params["count"] = count;
|
stopReconnectTimer();
|
||||||
sendRpcRequest("playback.skip", params);
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::seek(int positionMs) {
|
QString url = QString("ws://%1:%2").arg(host).arg(port);
|
||||||
QJsonObject params;
|
qDebug() << "Connecting to:" << url;
|
||||||
params["position"] = positionMs;
|
socket_->open(QUrl(url));
|
||||||
sendRpcRequest("playback.seek", params);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::setVolume(int volume) {
|
void CoreClient::disconnectFromHost()
|
||||||
QJsonObject params;
|
{
|
||||||
params["volume"] = qBound(0, volume, 100);
|
stopReconnectTimer();
|
||||||
sendRpcRequest("playback.setVolume", params);
|
cancelPendingRequests();
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::queueTrack(const QString& query) {
|
if (socket_->state() != QAbstractSocket::UnconnectedState) {
|
||||||
QJsonObject params;
|
socket_->close();
|
||||||
params["query"] = query;
|
}
|
||||||
sendRpcRequest("queue.add", params, [this](const QJsonObject& result) {
|
}
|
||||||
if (result["success"].toBool()) {
|
|
||||||
auto track = parseTrackInfo(result["track"].toObject());
|
|
||||||
emit trackQueued(track, result["position"].toInt());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::removeFromQueue(int position) {
|
bool CoreClient::isConnected() const
|
||||||
QJsonObject params;
|
{
|
||||||
params["position"] = position;
|
return socket_->state() == QAbstractSocket::ConnectedState;
|
||||||
sendRpcRequest("queue.remove", params, [this, position](const QJsonObject& result) {
|
}
|
||||||
if (result["success"].toBool()) {
|
|
||||||
emit trackRemoved(position);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::clearQueue() {
|
void CoreClient::requestAuthToken(const QString& nickname)
|
||||||
sendRpcRequest("queue.clear");
|
{
|
||||||
}
|
currentNickname_ = nickname;
|
||||||
|
|
||||||
void CoreClient::moveInQueue(int from, int to) {
|
QJsonObject params;
|
||||||
QJsonObject params;
|
params["nickname"] = nickname;
|
||||||
params["from"] = from;
|
|
||||||
params["to"] = to;
|
|
||||||
sendRpcRequest("queue.move", params);
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::shuffle() {
|
call("Authenticate", params, [this](const QJsonObject& result) {
|
||||||
sendRpcRequest("queue.shuffle");
|
if (result["success"].toBool()) {
|
||||||
}
|
emit authTokenRequested();
|
||||||
|
} else {
|
||||||
|
emit authFailed(result["message"].toString("Unknown error"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
void CoreClient::toggleRepeat() {
|
void CoreClient::authenticate(const QString& token)
|
||||||
sendRpcRequest("playback.toggleRepeat");
|
{
|
||||||
}
|
authToken_ = token;
|
||||||
|
|
||||||
void CoreClient::toggleShuffle() {
|
QJsonObject params;
|
||||||
sendRpcRequest("playback.toggleShuffle");
|
params["token"] = token;
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::search(const QString& query) {
|
call("Authenticate", params, [this](const QJsonObject& result) {
|
||||||
QJsonObject params;
|
if (result["success"].toBool()) {
|
||||||
params["query"] = query;
|
isAuthenticated_ = true;
|
||||||
sendRpcRequest("search.query", params, [this](const QJsonObject& result) {
|
emit authenticated();
|
||||||
auto searchResult = parseSearchResult(result);
|
|
||||||
emit searchResultsReceived(searchResult);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::loadPlaylist(const QString& playlistId) {
|
// Save token for auto-auth
|
||||||
QJsonObject params;
|
if (!currentHost_.isEmpty() && !currentNickname_.isEmpty()) {
|
||||||
params["playlistId"] = playlistId;
|
settingsManager_.saveToken(currentHost_, currentPort_,
|
||||||
sendRpcRequest("playlist.load", params, [this, playlistId](const QJsonObject& result) {
|
currentNickname_, authToken_);
|
||||||
emit playlistLoaded(playlistId, result["trackCount"].toInt());
|
emit tokenSaved(currentHost_, currentPort_);
|
||||||
});
|
}
|
||||||
}
|
} else {
|
||||||
|
isAuthenticated_ = false;
|
||||||
|
emit authFailed(
|
||||||
|
result["message"].toString("Authentication failed"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
void CoreClient::savePlaylist(const QString& name, const QString& description) {
|
void CoreClient::logout()
|
||||||
QJsonObject params;
|
{
|
||||||
params["name"] = name;
|
call("Logout");
|
||||||
params["description"] = description;
|
|
||||||
sendRpcRequest("playlist.save", params);
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::getUserPlaylists() {
|
isAuthenticated_ = false;
|
||||||
sendRpcRequest("playlist.list", {}, [this](const QJsonObject& result) {
|
authToken_.clear();
|
||||||
std::vector<Echoion::Api::PlaylistInfo> playlists;
|
emit loggedOut();
|
||||||
QJsonArray arr = result["playlists"].toArray();
|
}
|
||||||
for (const auto& item : arr) {
|
|
||||||
auto obj = item.toObject();
|
|
||||||
Echoion::Api::PlaylistInfo info;
|
|
||||||
info.id = obj["id"].toString().toStdString();
|
|
||||||
info.name = obj["name"].toString().toStdString();
|
|
||||||
playlists.push_back(info);
|
|
||||||
}
|
|
||||||
emit playlistsReceived(playlists);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::requestPlaybackState() {
|
bool CoreClient::isAuthenticated() const { return isAuthenticated_; }
|
||||||
sendRpcRequest("state.getPlayback", {}, [this](const QJsonObject& result) {
|
|
||||||
emit playbackStateReceived(parsePlaybackState(result));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::requestQueue() {
|
void CoreClient::clearCachedToken()
|
||||||
sendRpcRequest("queue.get", {}, [this](const QJsonObject& result) {
|
{
|
||||||
std::vector<Echoion::Api::QueueEntry> queue;
|
if (!currentHost_.isEmpty()) {
|
||||||
QJsonArray arr = result["queue"].toArray();
|
settingsManager_.deleteToken(currentHost_, currentPort_);
|
||||||
for (const auto& item : arr) {
|
}
|
||||||
queue.push_back(parseQueueEntry(item.toObject()));
|
logout();
|
||||||
}
|
}
|
||||||
emit queueReceived(queue);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::requestCurrentTrack() {
|
void CoreClient::call(const QString& method, const QJsonObject& params)
|
||||||
sendRpcRequest("state.getCurrentTrack", {}, [this](const QJsonObject& result) {
|
{
|
||||||
if (!result["track"].isNull()) {
|
call(method, params, nullptr);
|
||||||
emit trackStarted(parseTrackInfo(result["track"].toObject()));
|
}
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::reloadCore() {
|
int CoreClient::methodToInt(const QString& method) const
|
||||||
sendRpcRequest("system.reload");
|
{
|
||||||
}
|
// Map method names to RpcMethod enum values
|
||||||
|
static const QHash<QString, int> methodMap = {
|
||||||
|
{"Play", 0},
|
||||||
|
{"Pause", 1},
|
||||||
|
{"Resume", 2},
|
||||||
|
{"Stop", 3},
|
||||||
|
{"Skip", 4},
|
||||||
|
{"Seek", 5},
|
||||||
|
{"SetVolume", 6},
|
||||||
|
{"QueueTrack", 7},
|
||||||
|
{"RemoveFromQueue", 8},
|
||||||
|
{"ClearQueue", 9},
|
||||||
|
{"GetQueue", 10},
|
||||||
|
{"MoveInQueue", 11},
|
||||||
|
{"GetCurrentTrack", 12},
|
||||||
|
{"GetTrackInfo", 13},
|
||||||
|
{"SearchTracks", 14},
|
||||||
|
{"LoadPlaylist", 15},
|
||||||
|
{"SavePlaylist", 16},
|
||||||
|
{"GetPlaylists", 17},
|
||||||
|
{"DeletePlaylist", 18},
|
||||||
|
{"GetConfig", 19},
|
||||||
|
{"SetConfig", 20},
|
||||||
|
{"ReloadConfig", 21},
|
||||||
|
{"GetStatus", 22},
|
||||||
|
{"HotReload", 23},
|
||||||
|
{"Shutdown", 24},
|
||||||
|
{"Authenticate", 53},
|
||||||
|
{"Logout", 54},
|
||||||
|
{"GetAuditLog", 55},
|
||||||
|
{"ManageUsers", 56},
|
||||||
|
{"GetServerInfo", 57},
|
||||||
|
{"RequestLoginToken", 58},
|
||||||
|
{"ValidateLoginToken", 59}};
|
||||||
|
|
||||||
void CoreClient::onConnected() {
|
return methodMap.value(method, -1);
|
||||||
reconnectAttempts_ = 0;
|
}
|
||||||
emit connected();
|
|
||||||
|
|
||||||
// Re-authenticate if we had a token
|
|
||||||
if (!authToken_.isEmpty()) {
|
|
||||||
QJsonObject params;
|
|
||||||
params["token"] = authToken_;
|
|
||||||
sendRpcRequest("auth.validate", params);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start polling for state updates
|
|
||||||
requestPlaybackState();
|
|
||||||
requestQueue();
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::onDisconnected() {
|
void CoreClient::call(const QString& method, const QJsonObject& params,
|
||||||
emit disconnected();
|
RpcCallback callback)
|
||||||
|
{
|
||||||
// Attempt reconnection
|
if (!isConnected()) {
|
||||||
if (shouldReconnect_ && reconnectAttempts_ < MAX_RECONNECT_ATTEMPTS) {
|
if (callback) {
|
||||||
reconnectAttempts_++;
|
QJsonObject error;
|
||||||
QTimer::singleShot(1000 * reconnectAttempts_, [this]() {
|
error["success"] = false;
|
||||||
connectToCore();
|
error["message"] = "Not connected";
|
||||||
});
|
callback(error);
|
||||||
}
|
}
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
void CoreClient::onError(QAbstractSocket::SocketError error) {
|
int methodInt = methodToInt(method);
|
||||||
QString errorMsg;
|
if (methodInt < 0) {
|
||||||
switch (error) {
|
if (callback) {
|
||||||
case QAbstractSocket::ConnectionRefusedError:
|
QJsonObject error;
|
||||||
errorMsg = "Connection refused - is the core running?";
|
error["success"] = false;
|
||||||
break;
|
error["message"] = "Unknown method: " + method;
|
||||||
case QAbstractSocket::RemoteHostClosedError:
|
callback(error);
|
||||||
errorMsg = "Connection closed by server";
|
}
|
||||||
break;
|
return;
|
||||||
case QAbstractSocket::HostNotFoundError:
|
}
|
||||||
errorMsg = "Server not found";
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
errorMsg = QString("Socket error: %1").arg(socket_->errorString());
|
|
||||||
}
|
|
||||||
emit errorOccurred(errorMsg);
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::onMessageReceived(const QString& message) {
|
quint64 requestId = nextRequestId_++;
|
||||||
QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
|
|
||||||
if (doc.isNull() || !doc.isObject()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
QJsonObject obj = doc.object();
|
|
||||||
|
|
||||||
// Check if it's a response or an event
|
|
||||||
if (obj.contains("id")) {
|
|
||||||
handleRpcResponse(obj);
|
|
||||||
} else if (obj.contains("event")) {
|
|
||||||
handleEvent(obj);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::onBinaryMessageReceived(const QByteArray& data) {
|
QJsonObject request;
|
||||||
// Handle binary data if needed (e.g., album art)
|
request["id"] = static_cast<qint64>(requestId);
|
||||||
}
|
// 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;
|
||||||
|
|
||||||
void CoreClient::sendRpcRequest(const QString& method, const QJsonObject& params) {
|
if (!authToken_.isEmpty()) {
|
||||||
sendRpcRequest(method, params, nullptr);
|
request["authToken"] = authToken_;
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::sendRpcRequest(const QString& method, const QJsonObject& params, RpcCallback callback) {
|
if (callback) {
|
||||||
if (!isConnected()) {
|
PendingRequest pending;
|
||||||
return;
|
pending.method = method;
|
||||||
}
|
pending.params = params;
|
||||||
|
pending.callback = callback;
|
||||||
QJsonObject request;
|
pending.retryCount = 0;
|
||||||
QString id = QUuid::createUuid().toString();
|
pendingRequests_[requestId] = std::move(pending);
|
||||||
|
}
|
||||||
request["jsonrpc"] = "2.0";
|
|
||||||
request["id"] = id;
|
|
||||||
request["method"] = method;
|
|
||||||
request["params"] = params;
|
|
||||||
|
|
||||||
if (!authToken_.isEmpty()) {
|
|
||||||
request["auth"] = authToken_;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (callback) {
|
|
||||||
pendingRequests_[id] = callback;
|
|
||||||
}
|
|
||||||
|
|
||||||
QJsonDocument doc(request);
|
|
||||||
socket_->sendTextMessage(QString::fromUtf8(doc.toJson(QJsonDocument::Compact)));
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::handleRpcResponse(const QJsonObject& response) {
|
QJsonDocument doc(request);
|
||||||
QString id = response["id"].toString();
|
socket_->sendTextMessage(doc.toJson(QJsonDocument::Compact));
|
||||||
|
}
|
||||||
auto it = pendingRequests_.find(id);
|
|
||||||
if (it != pendingRequests_.end()) {
|
|
||||||
if (it->second) {
|
|
||||||
QJsonObject result = response.contains("result")
|
|
||||||
? response["result"].toObject()
|
|
||||||
: QJsonObject();
|
|
||||||
if (response.contains("error")) {
|
|
||||||
result["error"] = response["error"];
|
|
||||||
result["success"] = false;
|
|
||||||
} else {
|
|
||||||
result["success"] = true;
|
|
||||||
}
|
|
||||||
it->second(result);
|
|
||||||
}
|
|
||||||
pendingRequests_.erase(it);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::handleEvent(const QJsonObject& event) {
|
void CoreClient::retryRequest(quint64 requestId)
|
||||||
QString eventType = event["event"].toString();
|
{
|
||||||
QJsonObject data = event["data"].toObject();
|
auto it = pendingRequests_.find(requestId);
|
||||||
|
if (it == pendingRequests_.end()) {
|
||||||
if (eventType == "playback.stateChanged") {
|
return;
|
||||||
emit playbackStateReceived(parsePlaybackState(data));
|
}
|
||||||
} else if (eventType == "playback.trackStarted") {
|
|
||||||
emit trackStarted(parseTrackInfo(data["track"].toObject()));
|
|
||||||
} else if (eventType == "playback.trackFinished") {
|
|
||||||
emit trackFinished(parseTrackInfo(data["track"].toObject()));
|
|
||||||
} else if (eventType == "playback.paused") {
|
|
||||||
emit playbackPaused();
|
|
||||||
} else if (eventType == "playback.resumed") {
|
|
||||||
emit playbackResumed();
|
|
||||||
} else if (eventType == "playback.volumeChanged") {
|
|
||||||
emit volumeChanged(data["volume"].toInt());
|
|
||||||
} else if (eventType == "queue.updated") {
|
|
||||||
requestQueue();
|
|
||||||
} else if (eventType == "queue.trackAdded") {
|
|
||||||
auto track = parseTrackInfo(data["track"].toObject());
|
|
||||||
emit trackQueued(track, data["position"].toInt());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Echoion::Api::PlaybackState CoreClient::parsePlaybackState(const QJsonObject& obj) {
|
auto& pending = it->second;
|
||||||
Echoion::Api::PlaybackState state;
|
|
||||||
|
|
||||||
state.isPlaying = obj["isPlaying"].toBool();
|
|
||||||
state.isPaused = obj["isPaused"].toBool();
|
|
||||||
state.volume = static_cast<float>(obj["volume"].toDouble(0.5));
|
|
||||||
state.repeat = obj["repeat"].toBool();
|
|
||||||
state.shuffle = obj["shuffle"].toBool();
|
|
||||||
state.position = std::chrono::milliseconds(obj["position"].toInt());
|
|
||||||
|
|
||||||
if (!obj["currentTrack"].isNull()) {
|
|
||||||
state.currentTrack = parseQueueEntry(obj["currentTrack"].toObject());
|
|
||||||
}
|
|
||||||
|
|
||||||
return state;
|
|
||||||
}
|
|
||||||
|
|
||||||
Echoion::Api::TrackInfo CoreClient::parseTrackInfo(const QJsonObject& obj) {
|
if (pending.retryCount >= MAX_RETRIES) {
|
||||||
Echoion::Api::TrackInfo track;
|
// Max retries reached, fail the request
|
||||||
|
if (pending.callback) {
|
||||||
track.title = obj["title"].toString().toStdString();
|
QJsonObject error;
|
||||||
track.artist = obj["artist"].toString().toStdString();
|
error["success"] = false;
|
||||||
track.originalUrl = obj["originalUrl"].toString().toStdString();
|
error["message"] = "Max retries exceeded";
|
||||||
track.source = static_cast<Echoion::Api::TrackSource>(obj["source"].toInt());
|
pending.callback(error);
|
||||||
|
}
|
||||||
if (!obj["streamUrl"].isNull()) {
|
pendingRequests_.erase(it);
|
||||||
track.streamUrl = obj["streamUrl"].toString().toStdString();
|
return;
|
||||||
}
|
}
|
||||||
if (!obj["thumbnailUrl"].isNull()) {
|
|
||||||
track.thumbnailUrl = obj["thumbnailUrl"].toString().toStdString();
|
|
||||||
}
|
|
||||||
if (!obj["duration"].isNull()) {
|
|
||||||
track.duration = std::chrono::milliseconds(obj["duration"].toInt());
|
|
||||||
}
|
|
||||||
|
|
||||||
return track;
|
|
||||||
}
|
|
||||||
|
|
||||||
Echoion::Api::QueueEntry CoreClient::parseQueueEntry(const QJsonObject& obj) {
|
pending.retryCount++;
|
||||||
Echoion::Api::QueueEntry entry;
|
|
||||||
|
|
||||||
entry.queueId = static_cast<uint64_t>(obj["queueId"].toDouble());
|
|
||||||
entry.track = parseTrackInfo(obj["track"].toObject());
|
|
||||||
entry.addedBy = obj["addedBy"].toString().toStdString();
|
|
||||||
entry.isPlaying = obj["isPlaying"].toBool();
|
|
||||||
|
|
||||||
if (!obj["position"].isNull()) {
|
|
||||||
entry.position = std::chrono::milliseconds(obj["position"].toInt());
|
|
||||||
}
|
|
||||||
|
|
||||||
return entry;
|
|
||||||
}
|
|
||||||
|
|
||||||
Echoion::Api::SearchResult CoreClient::parseSearchResult(const QJsonObject& obj) {
|
// Retry after delay
|
||||||
Echoion::Api::SearchResult result;
|
QTimer::singleShot(
|
||||||
|
RETRY_DELAY_MS * pending.retryCount, this, [this, requestId]() {
|
||||||
result.query = obj["query"].toString().toStdString();
|
auto it = pendingRequests_.find(requestId);
|
||||||
|
if (it == pendingRequests_.end()) {
|
||||||
QJsonArray tracks = obj["tracks"].toArray();
|
return;
|
||||||
for (const auto& item : tracks) {
|
}
|
||||||
result.tracks.push_back(parseTrackInfo(item.toObject()));
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
QJsonObject CoreClient::trackInfoToJson(const Echoion::Api::TrackInfo& track) {
|
auto& pending = it->second;
|
||||||
QJsonObject obj;
|
|
||||||
obj["title"] = QString::fromStdString(track.title);
|
quint64 newRequestId = nextRequestId_++;
|
||||||
obj["artist"] = QString::fromStdString(track.artist);
|
|
||||||
obj["originalUrl"] = QString::fromStdString(track.originalUrl);
|
QJsonObject request;
|
||||||
obj["source"] = static_cast<int>(track.source);
|
request["id"] = static_cast<qint64>(newRequestId);
|
||||||
if (track.streamUrl) {
|
request["method"] = pending.method;
|
||||||
obj["streamUrl"] = QString::fromStdString(*track.streamUrl);
|
request["params"] = pending.params;
|
||||||
}
|
|
||||||
if (track.thumbnailUrl) {
|
if (!authToken_.isEmpty()) {
|
||||||
obj["thumbnailUrl"] = QString::fromStdString(*track.thumbnailUrl);
|
request["authToken"] = authToken_;
|
||||||
}
|
}
|
||||||
if (track.duration) {
|
|
||||||
obj["duration"] = static_cast<int>(track.duration->count());
|
// Move callback to new request ID
|
||||||
}
|
PendingRequest newPending = std::move(pending);
|
||||||
return obj;
|
pendingRequests_.erase(it);
|
||||||
}
|
pendingRequests_[newRequestId] = std::move(newPending);
|
||||||
|
|
||||||
|
QJsonDocument doc(request);
|
||||||
|
socket_->sendTextMessage(doc.toJson(QJsonDocument::Compact));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::cancelPendingRequests()
|
||||||
|
{
|
||||||
|
for (auto& [id, pending] : pendingRequests_) {
|
||||||
|
if (pending.callback) {
|
||||||
|
QJsonObject error;
|
||||||
|
error["success"] = false;
|
||||||
|
error["message"] = "Connection closed";
|
||||||
|
pending.callback(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pendingRequests_.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::onSocketConnected()
|
||||||
|
{
|
||||||
|
qDebug() << "Socket connected successfully";
|
||||||
|
reconnectAttempts_ = 0;
|
||||||
|
emit connected();
|
||||||
|
|
||||||
|
// Attempt auto-auth if enabled and we have a cached token
|
||||||
|
if (autoAuthEnabled_ && !currentHost_.isEmpty()) {
|
||||||
|
attemptAutoAuth();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::attemptAutoAuth()
|
||||||
|
{
|
||||||
|
QString nickname;
|
||||||
|
auto token =
|
||||||
|
settingsManager_.loadToken(currentHost_, currentPort_, nickname);
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
currentNickname_ = nickname;
|
||||||
|
authenticate(*token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::onSocketDisconnected()
|
||||||
|
{
|
||||||
|
qDebug() << "Socket disconnected";
|
||||||
|
isAuthenticated_ = false;
|
||||||
|
emit disconnected();
|
||||||
|
|
||||||
|
// Start reconnection if enabled
|
||||||
|
if (autoConnectEnabled_ &&
|
||||||
|
reconnectAttempts_ < MAX_RECONNECT_ATTEMPTS) {
|
||||||
|
startReconnectTimer();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::onSocketError(QAbstractSocket::SocketError error)
|
||||||
|
{
|
||||||
|
QString errorMsg = socket_->errorString();
|
||||||
|
qDebug() << "Socket error:" << error << "-" << errorMsg;
|
||||||
|
emit connectionError(errorMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::startReconnectTimer()
|
||||||
|
{
|
||||||
|
if (reconnectAttempts_ >= MAX_RECONNECT_ATTEMPTS) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
reconnectAttempts_++;
|
||||||
|
int delay =
|
||||||
|
INITIAL_RECONNECT_DELAY_MS * (1 << (reconnectAttempts_ - 1));
|
||||||
|
|
||||||
|
emit reconnecting(reconnectAttempts_);
|
||||||
|
reconnectTimer_->start(delay);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::stopReconnectTimer() { reconnectTimer_->stop(); }
|
||||||
|
|
||||||
|
void CoreClient::onReconnectTimer()
|
||||||
|
{
|
||||||
|
if (!currentHost_.isEmpty()) {
|
||||||
|
connectToHost(currentHost_, currentPort_);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::onTextMessageReceived(const QString& message)
|
||||||
|
{
|
||||||
|
QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
|
||||||
|
if (doc.isNull() || !doc.isObject()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
QJsonObject obj = doc.object();
|
||||||
|
|
||||||
|
if (obj.contains("event")) {
|
||||||
|
handleEvent(obj);
|
||||||
|
} else if (obj.contains("id")) {
|
||||||
|
handleRpcResponse(obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::handleRpcResponse(const QJsonObject& response)
|
||||||
|
{
|
||||||
|
quint64 requestId = response["id"].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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::handleEvent(const QJsonObject& event)
|
||||||
|
{
|
||||||
|
QString eventName = event["event"].toString();
|
||||||
|
QJsonObject data = event["data"].toObject();
|
||||||
|
|
||||||
|
emit eventReceived(eventName, data);
|
||||||
|
|
||||||
|
// Emit specific signals for common events
|
||||||
|
if (eventName == "playback.started") {
|
||||||
|
emit playbackStarted(data);
|
||||||
|
} else if (eventName == "playback.paused") {
|
||||||
|
emit playbackPaused(data);
|
||||||
|
} else if (eventName == "playback.resumed") {
|
||||||
|
emit playbackResumed(data);
|
||||||
|
} else if (eventName == "playback.stopped") {
|
||||||
|
emit playbackStopped(data);
|
||||||
|
} else if (eventName == "playback.finished") {
|
||||||
|
emit playbackFinished(data);
|
||||||
|
} else if (eventName == "playback.volumeChanged") {
|
||||||
|
emit volumeChanged(data);
|
||||||
|
} else if (eventName.startsWith("queue.")) {
|
||||||
|
emit queueUpdated(data);
|
||||||
|
} else if (eventName.startsWith("playlist.")) {
|
||||||
|
emit playlistEvent(eventName, data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Playback control methods
|
||||||
|
void CoreClient::play(const QString& query)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["query"] = query;
|
||||||
|
call("Play", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::pause() { call("Pause"); }
|
||||||
|
void CoreClient::resume() { call("Resume"); }
|
||||||
|
void CoreClient::stop() { call("Stop"); }
|
||||||
|
|
||||||
|
void CoreClient::skip(int count)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["count"] = count;
|
||||||
|
call("Skip", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::seek(int positionMs)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["position"] = positionMs;
|
||||||
|
call("Seek", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::setVolume(int volume)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["volume"] = volume;
|
||||||
|
call("SetVolume", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Queue management methods
|
||||||
|
void CoreClient::queueTrack(const QString& query)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["query"] = query;
|
||||||
|
call("QueueTrack", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::removeFromQueue(int position)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["position"] = position;
|
||||||
|
call("RemoveFromQueue", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::clearQueue() { call("ClearQueue"); }
|
||||||
|
|
||||||
|
void CoreClient::moveInQueue(int from, int to)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["from"] = from;
|
||||||
|
params["to"] = to;
|
||||||
|
call("MoveInQueue", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::shuffle() { call("Shuffle"); }
|
||||||
|
void CoreClient::toggleRepeat() { call("ToggleRepeat"); }
|
||||||
|
void CoreClient::toggleShuffle() { call("ToggleShuffle"); }
|
||||||
|
|
||||||
|
// Search
|
||||||
|
void CoreClient::search(const QString& query)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["query"] = query;
|
||||||
|
call("Search", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Playlist management
|
||||||
|
void CoreClient::loadPlaylist(const QString& playlistId)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["playlistId"] = playlistId;
|
||||||
|
call("LoadPlaylist", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::savePlaylist(const QString& name,
|
||||||
|
const QString& description)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["name"] = name;
|
||||||
|
params["description"] = description;
|
||||||
|
call("SavePlaylist", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::getUserPlaylists() { call("GetPlaylists"); }
|
||||||
|
|
||||||
|
// Data requests
|
||||||
|
void CoreClient::requestPlaybackState() { call("GetPlaybackState"); }
|
||||||
|
void CoreClient::requestQueue() { call("GetQueue"); }
|
||||||
|
void CoreClient::requestCurrentTrack() { call("GetCurrentTrack"); }
|
||||||
|
|
||||||
} // namespace Echoion::Desktop
|
} // namespace Echoion::Desktop
|
||||||
+146
-109
@@ -1,132 +1,169 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <QObject>
|
#include "storage/SettingsManager.hpp"
|
||||||
#include <QString>
|
|
||||||
#include <QWebSocket>
|
|
||||||
#include <QJsonObject>
|
#include <QJsonObject>
|
||||||
#include <QJsonArray>
|
#include <QObject>
|
||||||
#include <QUuid>
|
#include <QTimer>
|
||||||
#include <echoion/api.hpp>
|
#include <QWebSocket>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <unordered_map>
|
|
||||||
#include <optional>
|
#include <optional>
|
||||||
|
#include <unordered_map>
|
||||||
|
|
||||||
namespace Echoion::Desktop {
|
namespace Echoion::Desktop
|
||||||
|
{
|
||||||
|
|
||||||
// RPC request/response handling
|
// RPC request/response handling
|
||||||
using RpcCallback = std::function<void(const QJsonObject&)>;
|
using RpcCallback = std::function<void(const QJsonObject&)>;
|
||||||
|
|
||||||
class CoreClient : public QObject {
|
class CoreClient : public QObject
|
||||||
Q_OBJECT
|
{
|
||||||
|
Q_OBJECT
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit CoreClient(QObject* parent = nullptr);
|
|
||||||
~CoreClient() override;
|
|
||||||
|
|
||||||
// Connection management
|
explicit CoreClient(QObject* parent = nullptr);
|
||||||
void connectToCore(const QString& host = "localhost", int port = 8765);
|
~CoreClient() override;
|
||||||
void disconnectFromCore();
|
|
||||||
[[nodiscard]] bool isConnected() const;
|
|
||||||
|
|
||||||
// Authentication
|
// Settings integration
|
||||||
void authenticate(const QString& username, const QString& password);
|
void loadSettings();
|
||||||
void logout();
|
void saveSettings();
|
||||||
[[nodiscard]] bool isAuthenticated() const;
|
SettingsManager* settingsManager() { return &settingsManager_; }
|
||||||
|
|
||||||
// Playback control
|
// Auto-connect on startup
|
||||||
void play(const QString& query);
|
void enableAutoConnect(bool enabled);
|
||||||
void pause();
|
bool autoConnectEnabled() const;
|
||||||
void resume();
|
void startAutoConnect();
|
||||||
void stop();
|
|
||||||
void skip(int count = 1);
|
|
||||||
void seek(int positionMs);
|
|
||||||
void setVolume(int volume); // 0-100
|
|
||||||
|
|
||||||
// Queue management
|
// Connection management
|
||||||
void queueTrack(const QString& query);
|
void connectToHost(const QString& host, int port);
|
||||||
void removeFromQueue(int position);
|
void disconnectFromHost();
|
||||||
void clearQueue();
|
[[nodiscard]] bool isConnected() const;
|
||||||
void moveInQueue(int from, int to);
|
|
||||||
void shuffle();
|
|
||||||
void toggleRepeat();
|
|
||||||
void toggleShuffle();
|
|
||||||
|
|
||||||
// Search
|
// Authentication with auto-auth support
|
||||||
void search(const QString& query);
|
void requestAuthToken(const QString& nickname);
|
||||||
|
void authenticate(const QString& token);
|
||||||
|
void logout();
|
||||||
|
[[nodiscard]] bool isAuthenticated() const;
|
||||||
|
void clearCachedToken();
|
||||||
|
|
||||||
// Playlist management
|
// Generic RPC with automatic retry
|
||||||
void loadPlaylist(const QString& playlistId);
|
void call(const QString& method, const QJsonObject& params = {});
|
||||||
void savePlaylist(const QString& name, const QString& description);
|
void call(const QString& method, const QJsonObject& params,
|
||||||
void getUserPlaylists();
|
RpcCallback callback);
|
||||||
|
|
||||||
// Data requests
|
// Playback control
|
||||||
void requestPlaybackState();
|
void play(const QString& query);
|
||||||
void requestQueue();
|
void pause();
|
||||||
void requestCurrentTrack();
|
void resume();
|
||||||
|
void stop();
|
||||||
|
void skip(int count = 1);
|
||||||
|
void seek(int positionMs);
|
||||||
|
void setVolume(int volume);
|
||||||
|
|
||||||
// Hot reload
|
// Queue management
|
||||||
void reloadCore();
|
void queueTrack(const QString& query);
|
||||||
|
void removeFromQueue(int position);
|
||||||
|
void clearQueue();
|
||||||
|
void moveInQueue(int from, int to);
|
||||||
|
void shuffle();
|
||||||
|
void toggleRepeat();
|
||||||
|
void toggleShuffle();
|
||||||
|
|
||||||
signals:
|
// Search
|
||||||
// Connection signals
|
void search(const QString& query);
|
||||||
void connected();
|
|
||||||
void disconnected();
|
|
||||||
void errorOccurred(const QString& error);
|
|
||||||
|
|
||||||
// Authentication signals
|
|
||||||
void authenticationSuccess(const QString& token);
|
|
||||||
void authenticationFailed(const QString& reason);
|
|
||||||
void loggedOut();
|
|
||||||
|
|
||||||
// Playback signals
|
|
||||||
void playbackStateReceived(const Echoion::Api::PlaybackState& state);
|
|
||||||
void trackStarted(const Echoion::Api::TrackInfo& track);
|
|
||||||
void trackFinished(const Echoion::Api::TrackInfo& track);
|
|
||||||
void playbackPaused();
|
|
||||||
void playbackResumed();
|
|
||||||
void volumeChanged(int volume);
|
|
||||||
|
|
||||||
// Queue signals
|
|
||||||
void queueReceived(const std::vector<Echoion::Api::QueueEntry>& queue);
|
|
||||||
void trackQueued(const Echoion::Api::TrackInfo& track, int position);
|
|
||||||
void trackRemoved(int position);
|
|
||||||
|
|
||||||
// Search signals
|
|
||||||
void searchResultsReceived(const Echoion::Api::SearchResult& results);
|
|
||||||
|
|
||||||
// Playlist signals
|
|
||||||
void playlistsReceived(const std::vector<Echoion::Api::PlaylistInfo>& playlists);
|
|
||||||
void playlistLoaded(const QString& playlistId, int trackCount);
|
|
||||||
|
|
||||||
private slots:
|
// Playlist management
|
||||||
void onConnected();
|
void loadPlaylist(const QString& playlistId);
|
||||||
void onDisconnected();
|
void savePlaylist(const QString& name, const QString& description);
|
||||||
void onError(QAbstractSocket::SocketError error);
|
void getUserPlaylists();
|
||||||
void onMessageReceived(const QString& message);
|
|
||||||
void onBinaryMessageReceived(const QByteArray& data);
|
|
||||||
|
|
||||||
private:
|
// Data requests (fetch on demand)
|
||||||
void sendRpcRequest(const QString& method, const QJsonObject& params = {});
|
void requestPlaybackState();
|
||||||
void sendRpcRequest(const QString& method, const QJsonObject& params, RpcCallback callback);
|
void requestQueue();
|
||||||
void handleRpcResponse(const QJsonObject& response);
|
void requestCurrentTrack();
|
||||||
void handleEvent(const QJsonObject& event);
|
|
||||||
|
|
||||||
// JSON conversion helpers
|
|
||||||
[[nodiscard]] Echoion::Api::PlaybackState parsePlaybackState(const QJsonObject& obj);
|
|
||||||
[[nodiscard]] Echoion::Api::TrackInfo parseTrackInfo(const QJsonObject& obj);
|
|
||||||
[[nodiscard]] Echoion::Api::QueueEntry parseQueueEntry(const QJsonObject& obj);
|
|
||||||
[[nodiscard]] Echoion::Api::SearchResult parseSearchResult(const QJsonObject& obj);
|
|
||||||
[[nodiscard]] QJsonObject trackInfoToJson(const Echoion::Api::TrackInfo& track);
|
|
||||||
|
|
||||||
QWebSocket* socket_ = nullptr;
|
signals:
|
||||||
QString authToken_;
|
|
||||||
std::unordered_map<QString, RpcCallback> pendingRequests_;
|
// Connection signals
|
||||||
quint64 requestId_ = 0;
|
void connected();
|
||||||
|
void disconnected();
|
||||||
// Reconnection
|
void reconnecting(int attempt);
|
||||||
bool shouldReconnect_ = true;
|
void connectionError(const QString& error);
|
||||||
int reconnectAttempts_ = 0;
|
void connectionFailed(const QString& reason);
|
||||||
static constexpr int MAX_RECONNECT_ATTEMPTS = 5;
|
|
||||||
};
|
// Authentication signals
|
||||||
|
void authTokenRequested(); // Nickname accepted, check PM
|
||||||
|
void authenticated();
|
||||||
|
void authFailed(const QString& reason);
|
||||||
|
void loggedOut();
|
||||||
|
void tokenSaved(const QString& host, int port);
|
||||||
|
|
||||||
|
// All events from Core (raw JSON for flexibility)
|
||||||
|
void eventReceived(const QString& event, const QJsonObject& data);
|
||||||
|
|
||||||
|
// Specific event signals
|
||||||
|
void playbackStarted(const QJsonObject& data);
|
||||||
|
void playbackPaused(const QJsonObject& data);
|
||||||
|
void playbackResumed(const QJsonObject& data);
|
||||||
|
void playbackStopped(const QJsonObject& data);
|
||||||
|
void playbackFinished(const QJsonObject& data);
|
||||||
|
void volumeChanged(const QJsonObject& data);
|
||||||
|
void trackChanged(const QJsonObject& data);
|
||||||
|
void queueUpdated(const QJsonObject& data);
|
||||||
|
void playlistEvent(const QString& event, const QJsonObject& data);
|
||||||
|
|
||||||
|
private slots:
|
||||||
|
|
||||||
|
void onSocketConnected();
|
||||||
|
void onSocketDisconnected();
|
||||||
|
void onSocketError(QAbstractSocket::SocketError error);
|
||||||
|
void onTextMessageReceived(const QString& message);
|
||||||
|
void onReconnectTimer();
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
void setupSocket();
|
||||||
|
void handleRpcResponse(const QJsonObject& response);
|
||||||
|
void handleEvent(const QJsonObject& event);
|
||||||
|
void startReconnectTimer();
|
||||||
|
void stopReconnectTimer();
|
||||||
|
void attemptAutoAuth();
|
||||||
|
void saveCurrentToken();
|
||||||
|
|
||||||
|
// Request tracking for retry logic
|
||||||
|
struct PendingRequest {
|
||||||
|
QString method;
|
||||||
|
QJsonObject params;
|
||||||
|
RpcCallback callback;
|
||||||
|
int retryCount = 0;
|
||||||
|
QTimer* retryTimer = nullptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
void retryRequest(quint64 requestId);
|
||||||
|
void cancelPendingRequests();
|
||||||
|
[[nodiscard]] int methodToInt(const QString& method) const;
|
||||||
|
|
||||||
|
SettingsManager settingsManager_;
|
||||||
|
QWebSocket* socket_ = nullptr;
|
||||||
|
QString currentHost_;
|
||||||
|
int currentPort_ = 8765;
|
||||||
|
QString currentNickname_;
|
||||||
|
QString authToken_;
|
||||||
|
bool isAuthenticated_ = false;
|
||||||
|
bool autoConnectEnabled_ = true;
|
||||||
|
bool autoAuthEnabled_ = true;
|
||||||
|
|
||||||
|
// Request tracking
|
||||||
|
std::unordered_map<quint64, PendingRequest> pendingRequests_;
|
||||||
|
quint64 nextRequestId_ = 1;
|
||||||
|
static constexpr int MAX_RETRIES = 3;
|
||||||
|
static constexpr int RETRY_DELAY_MS = 500;
|
||||||
|
|
||||||
|
// Reconnection
|
||||||
|
QTimer* reconnectTimer_ = nullptr;
|
||||||
|
int reconnectAttempts_ = 0;
|
||||||
|
static constexpr int MAX_RECONNECT_ATTEMPTS = 5;
|
||||||
|
static constexpr int INITIAL_RECONNECT_DELAY_MS = 1000;
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Desktop
|
} // namespace Echoion::Desktop
|
||||||
+70
-67
@@ -1,84 +1,87 @@
|
|||||||
#include "LoginDialog.hpp"
|
#include "LoginDialog.hpp"
|
||||||
|
|
||||||
namespace Echoion::Desktop {
|
namespace Echoion::Desktop
|
||||||
|
{
|
||||||
|
|
||||||
LoginDialog::LoginDialog(QWidget* parent) : QDialog(parent) {
|
LoginDialog::LoginDialog(QWidget* parent) : QDialog(parent)
|
||||||
setupUi();
|
{
|
||||||
setWindowTitle("Echoion - Admin Login");
|
setupUi();
|
||||||
setModal(true);
|
setWindowTitle("Echoion - Admin Login");
|
||||||
setFixedSize(350, 200);
|
setModal(true);
|
||||||
}
|
setFixedSize(350, 200);
|
||||||
|
}
|
||||||
|
|
||||||
void LoginDialog::setupUi() {
|
void LoginDialog::setupUi()
|
||||||
auto* mainLayout = new QVBoxLayout(this);
|
{
|
||||||
|
auto* mainLayout = new QVBoxLayout(this);
|
||||||
|
|
||||||
auto* titleLabel = new QLabel("Echoion Music Bot - Admin Login", this);
|
auto* titleLabel = new QLabel("Echoion Music Bot - Admin Login", this);
|
||||||
titleLabel->setAlignment(Qt::AlignCenter);
|
titleLabel->setAlignment(Qt::AlignCenter);
|
||||||
QFont titleFont = titleLabel->font();
|
QFont titleFont = titleLabel->font();
|
||||||
titleFont.setPointSize(14);
|
titleFont.setPointSize(14);
|
||||||
titleFont.setBold(true);
|
titleFont.setBold(true);
|
||||||
titleLabel->setFont(titleFont);
|
titleLabel->setFont(titleFont);
|
||||||
mainLayout->addWidget(titleLabel);
|
mainLayout->addWidget(titleLabel);
|
||||||
|
|
||||||
mainLayout->addSpacing(20);
|
mainLayout->addSpacing(20);
|
||||||
|
|
||||||
auto* usernameLayout = new QHBoxLayout();
|
auto* usernameLayout = new QHBoxLayout();
|
||||||
auto* usernameLabel = new QLabel("Username:", this);
|
auto* usernameLabel = new QLabel("Username:", this);
|
||||||
usernameLabel->setFixedWidth(80);
|
usernameLabel->setFixedWidth(80);
|
||||||
usernameEdit_ = new QLineEdit(this);
|
usernameEdit_ = new QLineEdit(this);
|
||||||
usernameEdit_->setPlaceholderText("Enter username");
|
usernameEdit_->setPlaceholderText("Enter username");
|
||||||
usernameLayout->addWidget(usernameLabel);
|
usernameLayout->addWidget(usernameLabel);
|
||||||
usernameLayout->addWidget(usernameEdit_);
|
usernameLayout->addWidget(usernameEdit_);
|
||||||
mainLayout->addLayout(usernameLayout);
|
mainLayout->addLayout(usernameLayout);
|
||||||
|
|
||||||
auto* passwordLayout = new QHBoxLayout();
|
auto* passwordLayout = new QHBoxLayout();
|
||||||
auto* passwordLabel = new QLabel("Password:", this);
|
auto* passwordLabel = new QLabel("Password:", this);
|
||||||
passwordLabel->setFixedWidth(80);
|
passwordLabel->setFixedWidth(80);
|
||||||
passwordEdit_ = new QLineEdit(this);
|
passwordEdit_ = new QLineEdit(this);
|
||||||
passwordEdit_->setEchoMode(QLineEdit::Password);
|
passwordEdit_->setEchoMode(QLineEdit::Password);
|
||||||
passwordEdit_->setPlaceholderText("Enter password");
|
passwordEdit_->setPlaceholderText("Enter password");
|
||||||
passwordLayout->addWidget(passwordLabel);
|
passwordLayout->addWidget(passwordLabel);
|
||||||
passwordLayout->addWidget(passwordEdit_);
|
passwordLayout->addWidget(passwordEdit_);
|
||||||
mainLayout->addLayout(passwordLayout);
|
mainLayout->addLayout(passwordLayout);
|
||||||
|
|
||||||
mainLayout->addSpacing(20);
|
mainLayout->addSpacing(20);
|
||||||
|
|
||||||
auto* buttonLayout = new QHBoxLayout();
|
auto* buttonLayout = new QHBoxLayout();
|
||||||
loginButton_ = new QPushButton("Login", this);
|
loginButton_ = new QPushButton("Login", this);
|
||||||
loginButton_->setDefault(true);
|
loginButton_->setDefault(true);
|
||||||
cancelButton_ = new QPushButton("Cancel", this);
|
cancelButton_ = new QPushButton("Cancel", this);
|
||||||
buttonLayout->addStretch();
|
buttonLayout->addStretch();
|
||||||
buttonLayout->addWidget(loginButton_);
|
buttonLayout->addWidget(loginButton_);
|
||||||
buttonLayout->addWidget(cancelButton_);
|
buttonLayout->addWidget(cancelButton_);
|
||||||
mainLayout->addLayout(buttonLayout);
|
mainLayout->addLayout(buttonLayout);
|
||||||
|
|
||||||
connect(loginButton_, &QPushButton::clicked, this, &LoginDialog::onLoginClicked);
|
connect(loginButton_, &QPushButton::clicked, this,
|
||||||
connect(cancelButton_, &QPushButton::clicked, this, &LoginDialog::onCancelClicked);
|
&LoginDialog::onLoginClicked);
|
||||||
connect(passwordEdit_, &QLineEdit::returnPressed, this, &LoginDialog::onLoginClicked);
|
connect(cancelButton_, &QPushButton::clicked, this,
|
||||||
}
|
&LoginDialog::onCancelClicked);
|
||||||
|
connect(passwordEdit_, &QLineEdit::returnPressed, this,
|
||||||
|
&LoginDialog::onLoginClicked);
|
||||||
|
}
|
||||||
|
|
||||||
QString LoginDialog::getUsername() const {
|
QString LoginDialog::getUsername() const { return usernameEdit_->text(); }
|
||||||
return usernameEdit_->text();
|
|
||||||
}
|
|
||||||
|
|
||||||
QString LoginDialog::getPassword() const {
|
QString LoginDialog::getPassword() const { return passwordEdit_->text(); }
|
||||||
return passwordEdit_->text();
|
|
||||||
}
|
|
||||||
|
|
||||||
void LoginDialog::onLoginClicked() {
|
void LoginDialog::onLoginClicked()
|
||||||
if (usernameEdit_->text().isEmpty()) {
|
{
|
||||||
QMessageBox::warning(this, "Login Error", "Please enter a username.");
|
if (usernameEdit_->text().isEmpty()) {
|
||||||
return;
|
QMessageBox::warning(this, "Login Error",
|
||||||
}
|
"Please enter a username.");
|
||||||
if (passwordEdit_->text().isEmpty()) {
|
return;
|
||||||
QMessageBox::warning(this, "Login Error", "Please enter a password.");
|
}
|
||||||
return;
|
if (passwordEdit_->text().isEmpty()) {
|
||||||
}
|
QMessageBox::warning(this, "Login Error",
|
||||||
accept();
|
"Please enter a password.");
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
accept();
|
||||||
|
}
|
||||||
|
|
||||||
void LoginDialog::onCancelClicked() {
|
void LoginDialog::onCancelClicked() { reject(); }
|
||||||
reject();
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Desktop
|
} // namespace Echoion::Desktop
|
||||||
+25
-21
@@ -1,35 +1,39 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <QDialog>
|
#include <QDialog>
|
||||||
#include <QLineEdit>
|
|
||||||
#include <QPushButton>
|
|
||||||
#include <QLabel>
|
|
||||||
#include <QVBoxLayout>
|
|
||||||
#include <QHBoxLayout>
|
#include <QHBoxLayout>
|
||||||
|
#include <QLabel>
|
||||||
|
#include <QLineEdit>
|
||||||
#include <QMessageBox>
|
#include <QMessageBox>
|
||||||
|
#include <QPushButton>
|
||||||
|
#include <QVBoxLayout>
|
||||||
|
|
||||||
namespace Echoion::Desktop {
|
namespace Echoion::Desktop
|
||||||
|
{
|
||||||
|
|
||||||
class LoginDialog : public QDialog {
|
class LoginDialog : public QDialog
|
||||||
Q_OBJECT
|
{
|
||||||
|
Q_OBJECT
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit LoginDialog(QWidget* parent = nullptr);
|
|
||||||
|
|
||||||
[[nodiscard]] QString getUsername() const;
|
explicit LoginDialog(QWidget* parent = nullptr);
|
||||||
[[nodiscard]] QString getPassword() const;
|
|
||||||
|
|
||||||
private slots:
|
[[nodiscard]] QString getUsername() const;
|
||||||
void onLoginClicked();
|
[[nodiscard]] QString getPassword() const;
|
||||||
void onCancelClicked();
|
|
||||||
|
|
||||||
private:
|
private slots:
|
||||||
void setupUi();
|
void onLoginClicked();
|
||||||
|
void onCancelClicked();
|
||||||
|
|
||||||
QLineEdit* usernameEdit_;
|
private:
|
||||||
QLineEdit* passwordEdit_;
|
|
||||||
QPushButton* loginButton_;
|
void setupUi();
|
||||||
QPushButton* cancelButton_;
|
|
||||||
};
|
QLineEdit* usernameEdit_;
|
||||||
|
QLineEdit* passwordEdit_;
|
||||||
|
QPushButton* loginButton_;
|
||||||
|
QPushButton* cancelButton_;
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Desktop
|
} // namespace Echoion::Desktop
|
||||||
@@ -1,419 +0,0 @@
|
|||||||
#include "MainWindow.hpp"
|
|
||||||
#include <format>
|
|
||||||
|
|
||||||
namespace Echoion::Desktop {
|
|
||||||
|
|
||||||
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
|
|
||||||
setupUi();
|
|
||||||
setupMenuBar();
|
|
||||||
updateButtonStates();
|
|
||||||
|
|
||||||
updateTimer_ = new QTimer(this);
|
|
||||||
connect(updateTimer_, &QTimer::timeout, this, &MainWindow::updatePlaybackDisplay);
|
|
||||||
updateTimer_->start(1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
MainWindow::~MainWindow() = default;
|
|
||||||
|
|
||||||
void MainWindow::setupUi() {
|
|
||||||
setWindowTitle("Echoion Music Bot");
|
|
||||||
resize(900, 700);
|
|
||||||
|
|
||||||
centralWidget_ = new QWidget(this);
|
|
||||||
setCentralWidget(centralWidget_);
|
|
||||||
|
|
||||||
mainLayout_ = new QVBoxLayout(centralWidget_);
|
|
||||||
|
|
||||||
setupPlaybackControls();
|
|
||||||
setupSearchPanel();
|
|
||||||
setupQueueView();
|
|
||||||
setupStatusBar();
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::setupMenuBar() {
|
|
||||||
auto* fileMenu = menuBar()->addMenu("&File");
|
|
||||||
|
|
||||||
loginAction_ = fileMenu->addAction("&Login", this, &MainWindow::onLoginLogoutClicked);
|
|
||||||
logoutAction_ = fileMenu->addAction("Log&out", this, &MainWindow::onLoginLogoutClicked);
|
|
||||||
logoutAction_->setEnabled(false);
|
|
||||||
fileMenu->addSeparator();
|
|
||||||
settingsAction_ = fileMenu->addAction("&Settings", this, &MainWindow::onSettingsClicked);
|
|
||||||
settingsAction_->setEnabled(false);
|
|
||||||
fileMenu->addSeparator();
|
|
||||||
exitAction_ = fileMenu->addAction("E&xit", this, &QWidget::close, QKeySequence::Quit);
|
|
||||||
|
|
||||||
auto* controlMenu = menuBar()->addMenu("&Control");
|
|
||||||
reloadAction_ = controlMenu->addAction("&Reload Core", this, &MainWindow::onReloadClicked);
|
|
||||||
reloadAction_->setEnabled(false);
|
|
||||||
|
|
||||||
auto* helpMenu = menuBar()->addMenu("&Help");
|
|
||||||
aboutAction_ = helpMenu->addAction("&About", [this]() {
|
|
||||||
QMessageBox::about(this, "About Echoion",
|
|
||||||
"Echoion Music Bot v1.0.0\n\n"
|
|
||||||
"A modern music bot for TeamSpeak.");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::setupPlaybackControls() {
|
|
||||||
auto* playbackGroup = new QGroupBox("Now Playing", this);
|
|
||||||
auto* playbackLayout = new QVBoxLayout(playbackGroup);
|
|
||||||
|
|
||||||
nowPlayingLabel_ = new QLabel("Nothing is playing", this);
|
|
||||||
QFont titleFont = nowPlayingLabel_->font();
|
|
||||||
titleFont.setPointSize(12);
|
|
||||||
titleFont.setBold(true);
|
|
||||||
nowPlayingLabel_->setFont(titleFont);
|
|
||||||
playbackLayout->addWidget(nowPlayingLabel_);
|
|
||||||
|
|
||||||
artistLabel_ = new QLabel("", this);
|
|
||||||
playbackLayout->addWidget(artistLabel_);
|
|
||||||
|
|
||||||
auto* progressLayout = new QHBoxLayout();
|
|
||||||
progressBar_ = new QProgressBar(this);
|
|
||||||
progressBar_->setRange(0, 100);
|
|
||||||
progressBar_->setValue(0);
|
|
||||||
progressBar_->setTextVisible(false);
|
|
||||||
progressLayout->addWidget(progressBar_);
|
|
||||||
|
|
||||||
timeLabel_ = new QLabel("0:00 / 0:00", this);
|
|
||||||
timeLabel_->setFixedWidth(100);
|
|
||||||
progressLayout->addWidget(timeLabel_);
|
|
||||||
playbackLayout->addLayout(progressLayout);
|
|
||||||
|
|
||||||
auto* controlsLayout = new QHBoxLayout();
|
|
||||||
|
|
||||||
playButton_ = new QPushButton("Play", this);
|
|
||||||
pauseButton_ = new QPushButton("Pause", this);
|
|
||||||
stopButton_ = new QPushButton("Stop", this);
|
|
||||||
skipButton_ = new QPushButton("Skip", this);
|
|
||||||
shuffleButton_ = new QPushButton("Shuffle: Off", this);
|
|
||||||
repeatButton_ = new QPushButton("Repeat: Off", this);
|
|
||||||
|
|
||||||
controlsLayout->addWidget(playButton_);
|
|
||||||
controlsLayout->addWidget(pauseButton_);
|
|
||||||
controlsLayout->addWidget(stopButton_);
|
|
||||||
controlsLayout->addWidget(skipButton_);
|
|
||||||
controlsLayout->addStretch();
|
|
||||||
controlsLayout->addWidget(shuffleButton_);
|
|
||||||
controlsLayout->addWidget(repeatButton_);
|
|
||||||
playbackLayout->addLayout(controlsLayout);
|
|
||||||
|
|
||||||
auto* volumeLayout = new QHBoxLayout();
|
|
||||||
auto* volumeTextLabel = new QLabel("Volume:", this);
|
|
||||||
volumeSlider_ = new QSlider(Qt::Horizontal, this);
|
|
||||||
volumeSlider_->setRange(0, 100);
|
|
||||||
volumeSlider_->setValue(50);
|
|
||||||
volumeLabel_ = new QLabel("50%", this);
|
|
||||||
volumeLabel_->setFixedWidth(40);
|
|
||||||
|
|
||||||
volumeLayout->addWidget(volumeTextLabel);
|
|
||||||
volumeLayout->addWidget(volumeSlider_);
|
|
||||||
volumeLayout->addWidget(volumeLabel_);
|
|
||||||
playbackLayout->addLayout(volumeLayout);
|
|
||||||
|
|
||||||
mainLayout_->addWidget(playbackGroup);
|
|
||||||
|
|
||||||
connect(playButton_, &QPushButton::clicked, this, &MainWindow::onPlayClicked);
|
|
||||||
connect(pauseButton_, &QPushButton::clicked, this, &MainWindow::onPauseClicked);
|
|
||||||
connect(stopButton_, &QPushButton::clicked, this, &MainWindow::onStopClicked);
|
|
||||||
connect(skipButton_, &QPushButton::clicked, this, &MainWindow::onSkipClicked);
|
|
||||||
connect(shuffleButton_, &QPushButton::clicked, this, &MainWindow::onShuffleClicked);
|
|
||||||
connect(repeatButton_, &QPushButton::clicked, this, &MainWindow::onRepeatClicked);
|
|
||||||
connect(volumeSlider_, &QSlider::valueChanged, this, &MainWindow::onVolumeChanged);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::setupSearchPanel() {
|
|
||||||
auto* searchGroup = new QGroupBox("Search", this);
|
|
||||||
auto* searchLayout = new QVBoxLayout(searchGroup);
|
|
||||||
|
|
||||||
auto* searchInputLayout = new QHBoxLayout();
|
|
||||||
searchEdit_ = new QLineEdit(this);
|
|
||||||
searchEdit_->setPlaceholderText("Enter search query or YouTube URL...");
|
|
||||||
searchButton_ = new QPushButton("Search", this);
|
|
||||||
searchInputLayout->addWidget(searchEdit_);
|
|
||||||
searchInputLayout->addWidget(searchButton_);
|
|
||||||
searchLayout->addLayout(searchInputLayout);
|
|
||||||
|
|
||||||
searchResults_ = new QListWidget(this);
|
|
||||||
searchResults_->setMaximumHeight(150);
|
|
||||||
searchLayout->addWidget(searchResults_);
|
|
||||||
|
|
||||||
mainLayout_->addWidget(searchGroup);
|
|
||||||
|
|
||||||
connect(searchButton_, &QPushButton::clicked, this, &MainWindow::onSearchClicked);
|
|
||||||
connect(searchEdit_, &QLineEdit::returnPressed, this, &MainWindow::onSearchClicked);
|
|
||||||
connect(searchResults_, &QListWidget::itemDoubleClicked, this, &MainWindow::onSearchResultDoubleClicked);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::setupQueueView() {
|
|
||||||
auto* queueGroup = new QGroupBox("Queue", this);
|
|
||||||
auto* queueLayout = new QVBoxLayout(queueGroup);
|
|
||||||
|
|
||||||
queueList_ = new QListWidget(this);
|
|
||||||
queueLayout->addWidget(queueList_);
|
|
||||||
|
|
||||||
auto* queueButtonsLayout = new QHBoxLayout();
|
|
||||||
clearQueueButton_ = new QPushButton("Clear Queue", this);
|
|
||||||
removeFromQueueButton_ = new QPushButton("Remove Selected", this);
|
|
||||||
queueButtonsLayout->addWidget(clearQueueButton_);
|
|
||||||
queueButtonsLayout->addWidget(removeFromQueueButton_);
|
|
||||||
queueButtonsLayout->addStretch();
|
|
||||||
queueLayout->addLayout(queueButtonsLayout);
|
|
||||||
|
|
||||||
mainLayout_->addWidget(queueGroup);
|
|
||||||
|
|
||||||
connect(clearQueueButton_, &QPushButton::clicked, this, &MainWindow::onClearQueueClicked);
|
|
||||||
connect(removeFromQueueButton_, &QPushButton::clicked, this, &MainWindow::onRemoveFromQueueClicked);
|
|
||||||
connect(queueList_, &QListWidget::itemDoubleClicked, this, &MainWindow::onQueueItemDoubleClicked);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::setupStatusBar() {
|
|
||||||
statusBar_ = new QStatusBar(this);
|
|
||||||
setStatusBar(statusBar_);
|
|
||||||
|
|
||||||
connectionStatusLabel_ = new QLabel("Disconnected", this);
|
|
||||||
statusBar_->addWidget(connectionStatusLabel_);
|
|
||||||
|
|
||||||
authStatusLabel_ = new QLabel("Not logged in", this);
|
|
||||||
statusBar_->addPermanentWidget(authStatusLabel_);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::setAuthToken(const QString& token) {
|
|
||||||
authToken_ = token;
|
|
||||||
authStatusLabel_->setText("Logged in as Admin");
|
|
||||||
loginAction_->setEnabled(false);
|
|
||||||
logoutAction_->setEnabled(true);
|
|
||||||
settingsAction_->setEnabled(true);
|
|
||||||
reloadAction_->setEnabled(true);
|
|
||||||
updateButtonStates();
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::clearAuthToken() {
|
|
||||||
authToken_.reset();
|
|
||||||
authStatusLabel_->setText("Not logged in");
|
|
||||||
loginAction_->setEnabled(true);
|
|
||||||
logoutAction_->setEnabled(false);
|
|
||||||
settingsAction_->setEnabled(false);
|
|
||||||
reloadAction_->setEnabled(false);
|
|
||||||
updateButtonStates();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool MainWindow::isAuthenticated() const {
|
|
||||||
return authToken_.has_value();
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onPlaybackStateChanged(const Api::PlaybackState& state) {
|
|
||||||
currentState_ = state;
|
|
||||||
updatePlaybackDisplay();
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onQueueUpdated(const std::vector<Api::QueueEntry>& queue) {
|
|
||||||
currentQueue_ = queue;
|
|
||||||
updateQueueDisplay();
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onConnectionStatusChanged(bool connected) {
|
|
||||||
connectedToCore_ = connected;
|
|
||||||
connectionStatusLabel_->setText(connected ? "Connected" : "Disconnected");
|
|
||||||
if (!connected) {
|
|
||||||
clearAuthToken();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onPlayClicked() {
|
|
||||||
if (!isAuthenticated()) {
|
|
||||||
QMessageBox::warning(this, "Authentication Required", "Please login first.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString query = searchEdit_->text();
|
|
||||||
if (!query.isEmpty()) {
|
|
||||||
emit playRequested(query);
|
|
||||||
} else if (!currentQueue_.empty()) {
|
|
||||||
// Play first item in queue
|
|
||||||
emit playFromQueueRequested(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onPauseClicked() {
|
|
||||||
if (!isAuthenticated()) return;
|
|
||||||
emit pauseRequested();
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onStopClicked() {
|
|
||||||
if (!isAuthenticated()) return;
|
|
||||||
emit stopRequested();
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onSkipClicked() {
|
|
||||||
if (!isAuthenticated()) return;
|
|
||||||
emit skipRequested();
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onVolumeChanged(int value) {
|
|
||||||
volumeLabel_->setText(QString("%1%").arg(value));
|
|
||||||
emit volumeChangeRequested(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onSeekSliderMoved(int value) {
|
|
||||||
if (!isAuthenticated()) return;
|
|
||||||
emit seekRequested(value * 1000); // Convert to ms
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onSearchClicked() {
|
|
||||||
if (!isAuthenticated()) {
|
|
||||||
QMessageBox::warning(this, "Authentication Required", "Please login first.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString query = searchEdit_->text();
|
|
||||||
if (query.isEmpty()) return;
|
|
||||||
|
|
||||||
searchResults_->clear();
|
|
||||||
emit searchRequested(query);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onSearchResultDoubleClicked(QListWidgetItem* item) {
|
|
||||||
if (!isAuthenticated() || !item) return;
|
|
||||||
|
|
||||||
int index = searchResults_->row(item);
|
|
||||||
emit addSearchResultToQueueRequested(index);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onQueueItemDoubleClicked(QListWidgetItem* item) {
|
|
||||||
if (!isAuthenticated() || !item) return;
|
|
||||||
|
|
||||||
int index = queueList_->row(item);
|
|
||||||
emit playFromQueueRequested(index);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onShuffleClicked() {
|
|
||||||
if (!isAuthenticated()) return;
|
|
||||||
emit toggleShuffleRequested();
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onRepeatClicked() {
|
|
||||||
if (!isAuthenticated()) return;
|
|
||||||
emit toggleRepeatRequested();
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onClearQueueClicked() {
|
|
||||||
if (!isAuthenticated()) return;
|
|
||||||
|
|
||||||
auto reply = QMessageBox::question(this, "Clear Queue",
|
|
||||||
"Are you sure you want to clear the queue?",
|
|
||||||
QMessageBox::Yes | QMessageBox::No);
|
|
||||||
|
|
||||||
if (reply == QMessageBox::Yes) {
|
|
||||||
emit clearQueueRequested();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onRemoveFromQueueClicked() {
|
|
||||||
if (!isAuthenticated()) return;
|
|
||||||
|
|
||||||
auto* item = queueList_->currentItem();
|
|
||||||
if (!item) return;
|
|
||||||
|
|
||||||
int index = queueList_->row(item);
|
|
||||||
emit removeFromQueueRequested(index);
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onSettingsClicked() {
|
|
||||||
if (!isAuthenticated()) return;
|
|
||||||
|
|
||||||
// TODO: Implement settings dialog
|
|
||||||
QMessageBox::information(this, "Settings", "Settings dialog will be implemented here.");
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onReloadClicked() {
|
|
||||||
if (!isAuthenticated()) return;
|
|
||||||
|
|
||||||
auto reply = QMessageBox::question(this, "Hot Reload",
|
|
||||||
"Are you sure you want to reload the core?\n\n"
|
|
||||||
"This will briefly interrupt playback.",
|
|
||||||
QMessageBox::Yes | QMessageBox::No);
|
|
||||||
|
|
||||||
if (reply == QMessageBox::Yes) {
|
|
||||||
emit reloadCoreRequested();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onLoginLogoutClicked() {
|
|
||||||
if (isAuthenticated()) {
|
|
||||||
clearAuthToken();
|
|
||||||
emit logoutRequested();
|
|
||||||
} else {
|
|
||||||
emit loginRequested();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::onSearchResultsReceived(const Echoion::Api::SearchResult& results) {
|
|
||||||
searchResults_->clear();
|
|
||||||
for (const auto& track : results.tracks) {
|
|
||||||
QString text = QString::fromStdString(track.title + " - " + track.artist);
|
|
||||||
searchResults_->addItem(text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::updatePlaybackDisplay() {
|
|
||||||
if (currentState_.currentTrack.has_value()) {
|
|
||||||
const auto& track = currentState_.currentTrack->track;
|
|
||||||
nowPlayingLabel_->setText(QString::fromStdString(track.title));
|
|
||||||
artistLabel_->setText(QString::fromStdString(track.artist));
|
|
||||||
|
|
||||||
if (track.duration.has_value()) {
|
|
||||||
auto totalMs = track.duration->count();
|
|
||||||
auto currentMs = currentState_.position.count();
|
|
||||||
progressBar_->setMaximum(static_cast<int>(totalMs / 1000));
|
|
||||||
progressBar_->setValue(static_cast<int>(currentMs / 1000));
|
|
||||||
|
|
||||||
timeLabel_->setText(QString("%1 / %2")
|
|
||||||
.arg(formatDuration(currentState_.position))
|
|
||||||
.arg(formatDuration(*track.duration)));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
nowPlayingLabel_->setText("Nothing is playing");
|
|
||||||
artistLabel_->setText("");
|
|
||||||
progressBar_->setValue(0);
|
|
||||||
timeLabel_->setText("0:00 / 0:00");
|
|
||||||
}
|
|
||||||
|
|
||||||
shuffleButton_->setText(currentState_.shuffle ? "Shuffle: On" : "Shuffle: Off");
|
|
||||||
repeatButton_->setText(currentState_.repeat ? "Repeat: On" : "Repeat: Off");
|
|
||||||
volumeSlider_->setValue(static_cast<int>(currentState_.volume * 100));
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::updateQueueDisplay() {
|
|
||||||
queueList_->clear();
|
|
||||||
for (size_t i = 0; i < currentQueue_.size(); ++i) {
|
|
||||||
const auto& entry = currentQueue_[i];
|
|
||||||
QString text = QString("%1. %2 - %3")
|
|
||||||
.arg(i + 1)
|
|
||||||
.arg(QString::fromStdString(entry.track.title))
|
|
||||||
.arg(QString::fromStdString(entry.track.artist));
|
|
||||||
queueList_->addItem(text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void MainWindow::updateButtonStates() {
|
|
||||||
bool hasAuth = isAuthenticated();
|
|
||||||
playButton_->setEnabled(hasAuth);
|
|
||||||
pauseButton_->setEnabled(hasAuth);
|
|
||||||
stopButton_->setEnabled(hasAuth);
|
|
||||||
skipButton_->setEnabled(hasAuth);
|
|
||||||
shuffleButton_->setEnabled(hasAuth);
|
|
||||||
repeatButton_->setEnabled(hasAuth);
|
|
||||||
searchButton_->setEnabled(hasAuth);
|
|
||||||
clearQueueButton_->setEnabled(hasAuth);
|
|
||||||
removeFromQueueButton_->setEnabled(hasAuth);
|
|
||||||
}
|
|
||||||
|
|
||||||
QString MainWindow::formatDuration(std::chrono::milliseconds ms) {
|
|
||||||
auto totalSeconds = ms.count() / 1000;
|
|
||||||
auto minutes = totalSeconds / 60;
|
|
||||||
auto seconds = totalSeconds % 60;
|
|
||||||
return QString("%1:%2").arg(minutes).arg(seconds, 2, 10, QChar('0'));
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Desktop
|
|
||||||
+53
-135
@@ -1,155 +1,73 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <QMainWindow>
|
#include "CoreClient.hpp"
|
||||||
#include <QWidget>
|
#include <QJsonObject>
|
||||||
#include <QVBoxLayout>
|
|
||||||
#include <QHBoxLayout>
|
|
||||||
#include <QPushButton>
|
|
||||||
#include <QLabel>
|
#include <QLabel>
|
||||||
#include <QSlider>
|
|
||||||
#include <QProgressBar>
|
|
||||||
#include <QLineEdit>
|
#include <QLineEdit>
|
||||||
#include <QListWidget>
|
#include <QMainWindow>
|
||||||
#include <QGroupBox>
|
#include <QPushButton>
|
||||||
#include <QStatusBar>
|
#include <QStatusBar>
|
||||||
#include <QMenuBar>
|
#include <QVBoxLayout>
|
||||||
#include <QAction>
|
#include <QWidget>
|
||||||
#include <QMessageBox>
|
|
||||||
#include <QTimer>
|
|
||||||
#include <optional>
|
|
||||||
#include <echoion/api.hpp>
|
|
||||||
|
|
||||||
namespace Echoion::Desktop {
|
namespace Echoion::Desktop
|
||||||
|
{
|
||||||
|
|
||||||
class MainWindow : public QMainWindow {
|
class MainWindow : public QMainWindow
|
||||||
Q_OBJECT
|
{
|
||||||
|
Q_OBJECT
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit MainWindow(QWidget* parent = nullptr);
|
|
||||||
~MainWindow() override;
|
|
||||||
|
|
||||||
// Authentication
|
explicit MainWindow(CoreClient* client, QWidget* parent = nullptr);
|
||||||
void setAuthToken(const QString& token);
|
~MainWindow() override;
|
||||||
void clearAuthToken();
|
|
||||||
[[nodiscard]] bool isAuthenticated() const;
|
|
||||||
|
|
||||||
// State updates
|
private slots:
|
||||||
void onPlaybackStateChanged(const Api::PlaybackState& state);
|
|
||||||
void onQueueUpdated(const std::vector<Api::QueueEntry>& queue);
|
|
||||||
void onConnectionStatusChanged(bool connected);
|
|
||||||
void onSearchResultsReceived(const Api::SearchResult& results);
|
|
||||||
|
|
||||||
signals:
|
void onConnectClicked();
|
||||||
// Connection signals
|
void onAuthClicked();
|
||||||
void loginRequested();
|
void onConnected();
|
||||||
void logoutRequested();
|
void onDisconnected();
|
||||||
|
void onAuthTokenRequested();
|
||||||
// Playback control signals
|
void onAuthenticated();
|
||||||
void playRequested(const QString& query);
|
void onAuthFailed(const QString& reason);
|
||||||
void playFromQueueRequested(int index);
|
void onEventReceived(const QString& event, const QJsonObject& data);
|
||||||
void pauseRequested();
|
void updateConnectionStatus();
|
||||||
void stopRequested();
|
void updatePlaybackInfo(const QJsonObject& data);
|
||||||
void resumeRequested();
|
void onPlayClicked();
|
||||||
void skipRequested();
|
void onPauseClicked();
|
||||||
void seekRequested(int positionMs);
|
void onSkipClicked();
|
||||||
void volumeChangeRequested(int volume);
|
|
||||||
void toggleShuffleRequested();
|
|
||||||
void toggleRepeatRequested();
|
|
||||||
|
|
||||||
// Queue signals
|
|
||||||
void clearQueueRequested();
|
|
||||||
void removeFromQueueRequested(int index);
|
|
||||||
void moveInQueueRequested(int from, int to);
|
|
||||||
|
|
||||||
// Search signals
|
|
||||||
void searchRequested(const QString& query);
|
|
||||||
void addSearchResultToQueueRequested(int index);
|
|
||||||
|
|
||||||
// System signals
|
|
||||||
void reloadCoreRequested();
|
|
||||||
void settingsRequested();
|
|
||||||
|
|
||||||
private slots:
|
private:
|
||||||
void onPlayClicked();
|
|
||||||
void onPauseClicked();
|
|
||||||
void onStopClicked();
|
|
||||||
void onSkipClicked();
|
|
||||||
void onVolumeChanged(int value);
|
|
||||||
void onSeekSliderMoved(int value);
|
|
||||||
void onSearchClicked();
|
|
||||||
void onSearchResultDoubleClicked(QListWidgetItem* item);
|
|
||||||
void onQueueItemDoubleClicked(QListWidgetItem* item);
|
|
||||||
void onShuffleClicked();
|
|
||||||
void onRepeatClicked();
|
|
||||||
void onClearQueueClicked();
|
|
||||||
void onRemoveFromQueueClicked();
|
|
||||||
void onSettingsClicked();
|
|
||||||
void onReloadClicked();
|
|
||||||
void onLoginLogoutClicked();
|
|
||||||
|
|
||||||
private:
|
void setupUI();
|
||||||
void setupUi();
|
void setupConnections();
|
||||||
void setupMenuBar();
|
|
||||||
void setupPlaybackControls();
|
|
||||||
void setupSearchPanel();
|
|
||||||
void setupQueueView();
|
|
||||||
void setupStatusBar();
|
|
||||||
void updatePlaybackDisplay();
|
|
||||||
void updateQueueDisplay();
|
|
||||||
void updateButtonStates();
|
|
||||||
|
|
||||||
[[nodiscard]] QString formatDuration(std::chrono::milliseconds ms);
|
|
||||||
|
|
||||||
// Central widget
|
CoreClient* client_ = nullptr;
|
||||||
QWidget* centralWidget_;
|
|
||||||
QVBoxLayout* mainLayout_;
|
|
||||||
|
|
||||||
// Playback controls
|
// Connection section
|
||||||
QLabel* nowPlayingLabel_;
|
QLineEdit* hostEdit_ = nullptr;
|
||||||
QLabel* artistLabel_;
|
QLineEdit* portEdit_ = nullptr;
|
||||||
QProgressBar* progressBar_;
|
QPushButton* connectBtn_ = nullptr;
|
||||||
QLabel* timeLabel_;
|
QLabel* connectionStatus_ = nullptr;
|
||||||
QPushButton* playButton_;
|
|
||||||
QPushButton* pauseButton_;
|
|
||||||
QPushButton* stopButton_;
|
|
||||||
QPushButton* skipButton_;
|
|
||||||
QPushButton* shuffleButton_;
|
|
||||||
QPushButton* repeatButton_;
|
|
||||||
QSlider* volumeSlider_;
|
|
||||||
QLabel* volumeLabel_;
|
|
||||||
|
|
||||||
// Search panel
|
// Auth section
|
||||||
QLineEdit* searchEdit_;
|
QLineEdit* nicknameEdit_ = nullptr;
|
||||||
QPushButton* searchButton_;
|
QLineEdit* tokenEdit_ = nullptr;
|
||||||
QListWidget* searchResults_;
|
QPushButton* requestTokenBtn_ = nullptr;
|
||||||
|
QPushButton* authBtn_ = nullptr;
|
||||||
|
QLabel* authStatus_ = nullptr;
|
||||||
|
|
||||||
// Queue view
|
// Playback section
|
||||||
QListWidget* queueList_;
|
QLabel* currentTrackLabel_ = nullptr;
|
||||||
QPushButton* clearQueueButton_;
|
QLabel* artistLabel_ = nullptr;
|
||||||
QPushButton* removeFromQueueButton_;
|
QLabel* statusLabel_ = nullptr;
|
||||||
|
QPushButton* playBtn_ = nullptr;
|
||||||
|
QPushButton* pauseBtn_ = nullptr;
|
||||||
|
QPushButton* skipBtn_ = nullptr;
|
||||||
|
|
||||||
// Status bar
|
// Status bar
|
||||||
QStatusBar* statusBar_;
|
QStatusBar* statusBar_ = nullptr;
|
||||||
QLabel* connectionStatusLabel_;
|
};
|
||||||
QLabel* authStatusLabel_;
|
|
||||||
|
|
||||||
// Menu actions
|
|
||||||
QAction* loginAction_;
|
|
||||||
QAction* logoutAction_;
|
|
||||||
QAction* settingsAction_;
|
|
||||||
QAction* reloadAction_;
|
|
||||||
QAction* exitAction_;
|
|
||||||
QAction* aboutAction_;
|
|
||||||
|
|
||||||
// State
|
|
||||||
QTimer* updateTimer_;
|
|
||||||
std::optional<QString> authToken_;
|
|
||||||
Api::PlaybackState currentState_;
|
|
||||||
std::vector<Api::QueueEntry> currentQueue_;
|
|
||||||
bool connectedToCore_ = false;
|
|
||||||
|
|
||||||
// Buttons for login/logout
|
|
||||||
QPushButton* loginLogoutButton_;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Echoion::Desktop
|
} // namespace Echoion::Desktop
|
||||||
+280
-59
@@ -1,78 +1,299 @@
|
|||||||
#include <QApplication>
|
|
||||||
#include <QMessageBox>
|
|
||||||
#include "MainWindow.hpp"
|
|
||||||
#include "LoginDialog.hpp"
|
|
||||||
#include "CoreClient.hpp"
|
#include "CoreClient.hpp"
|
||||||
#include <echoion/api.hpp>
|
#include <QApplication>
|
||||||
|
#include <QFormLayout>
|
||||||
|
#include <QGroupBox>
|
||||||
|
#include <QHBoxLayout>
|
||||||
|
#include <QLabel>
|
||||||
|
#include <QLineEdit>
|
||||||
|
#include <QMainWindow>
|
||||||
|
#include <QMessageBox>
|
||||||
|
#include <QPushButton>
|
||||||
|
#include <QStatusBar>
|
||||||
|
#include <QTimer>
|
||||||
|
#include <QVBoxLayout>
|
||||||
|
#include <QWidget>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
using namespace Echoion::Desktop;
|
using namespace Echoion::Desktop;
|
||||||
|
|
||||||
int main(int argc, char* argv[]) {
|
class SimpleMainWindow : public QMainWindow
|
||||||
QApplication app(argc, argv);
|
{
|
||||||
|
Q_OBJECT
|
||||||
app.setApplicationName("Echoion Desktop");
|
|
||||||
app.setOrganizationName("Echoion");
|
|
||||||
|
|
||||||
MainWindow mainWindow;
|
public:
|
||||||
CoreClient coreClient;
|
|
||||||
|
|
||||||
// Connect to Core RPC server
|
SimpleMainWindow(CoreClient* client, QWidget* parent = nullptr)
|
||||||
coreClient.connectToCore("localhost", 8765);
|
: QMainWindow(parent), client_(client)
|
||||||
|
{
|
||||||
|
setupUI();
|
||||||
|
setupConnections();
|
||||||
|
updateConnectionStatus();
|
||||||
|
}
|
||||||
|
|
||||||
QObject::connect(&mainWindow, &MainWindow::loginRequested, [&]() {
|
private slots:
|
||||||
LoginDialog loginDialog(&mainWindow);
|
|
||||||
if (loginDialog.exec() == QDialog::Accepted) {
|
|
||||||
QString username = loginDialog.getUsername();
|
|
||||||
QString password = loginDialog.getPassword();
|
|
||||||
|
|
||||||
coreClient.authenticate(username, password);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
QObject::connect(&mainWindow, &MainWindow::logoutRequested, [&]() {
|
void onConnectClicked()
|
||||||
coreClient.logout();
|
{
|
||||||
mainWindow.clearAuthToken();
|
QString host = hostEdit->text();
|
||||||
});
|
if (host.isEmpty()) {
|
||||||
|
host = "localhost";
|
||||||
|
}
|
||||||
|
|
||||||
QObject::connect(&coreClient, &CoreClient::authenticationSuccess,
|
int port = portEdit->text().toInt();
|
||||||
[&](const QString& token) {
|
if (port <= 0) {
|
||||||
mainWindow.setAuthToken(token);
|
port = 8765;
|
||||||
QMessageBox::information(&mainWindow, "Login Successful",
|
}
|
||||||
"You are now logged in as admin.");
|
|
||||||
});
|
|
||||||
|
|
||||||
QObject::connect(&coreClient, &CoreClient::authenticationFailed,
|
statusBar()->showMessage(
|
||||||
[&](const QString& error) {
|
QString("Connecting to %1:%2...").arg(host).arg(port));
|
||||||
QMessageBox::warning(&mainWindow, "Login Failed", error);
|
client_->connectToHost(host, port);
|
||||||
});
|
}
|
||||||
|
|
||||||
QObject::connect(&coreClient, &CoreClient::playbackStateReceived,
|
void onRequestTokenClicked()
|
||||||
[&](const Echoion::Api::PlaybackState& state) {
|
{
|
||||||
mainWindow.onPlaybackStateChanged(state);
|
QString nickname = nicknameEdit->text();
|
||||||
});
|
if (nickname.isEmpty()) {
|
||||||
|
QMessageBox::warning(this, "Error",
|
||||||
|
"Please enter your nickname");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
client_->requestAuthToken(nickname);
|
||||||
|
}
|
||||||
|
|
||||||
QObject::connect(&coreClient, &CoreClient::queueReceived,
|
void onAuthClicked()
|
||||||
[&](const std::vector<Echoion::Api::QueueEntry>& queue) {
|
{
|
||||||
mainWindow.onQueueUpdated(queue);
|
QString token = tokenEdit->text();
|
||||||
});
|
if (token.isEmpty()) {
|
||||||
|
QMessageBox::warning(this, "Error", "Please enter the token");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
client_->authenticate(token);
|
||||||
|
}
|
||||||
|
|
||||||
QObject::connect(&coreClient, &CoreClient::connected,
|
void onConnected()
|
||||||
[&]() {
|
{
|
||||||
mainWindow.onConnectionStatusChanged(true);
|
statusBar()->showMessage("Connected");
|
||||||
});
|
updateConnectionStatus();
|
||||||
|
}
|
||||||
|
|
||||||
QObject::connect(&coreClient, &CoreClient::disconnected,
|
void onDisconnected()
|
||||||
[&]() {
|
{
|
||||||
mainWindow.onConnectionStatusChanged(false);
|
statusBar()->showMessage("Disconnected");
|
||||||
});
|
updateConnectionStatus();
|
||||||
|
}
|
||||||
|
|
||||||
QObject::connect(&coreClient, &CoreClient::errorOccurred,
|
void onAuthTokenRequested()
|
||||||
[&](const QString& error) {
|
{
|
||||||
QMessageBox::critical(&mainWindow, "Error", error);
|
QMessageBox::information(
|
||||||
});
|
this, "Token Requested",
|
||||||
|
"Please check your TeamSpeak PM for the authentication token.");
|
||||||
|
authStatus->setText("Token requested - check PM");
|
||||||
|
authStatus->setStyleSheet("color: orange;");
|
||||||
|
}
|
||||||
|
|
||||||
mainWindow.show();
|
void onAuthenticated()
|
||||||
|
{
|
||||||
|
authStatus->setText("Authenticated");
|
||||||
|
authStatus->setStyleSheet("color: green;");
|
||||||
|
statusBar()->showMessage("Authenticated successfully");
|
||||||
|
client_->requestPlaybackState();
|
||||||
|
}
|
||||||
|
|
||||||
return app.exec();
|
void onAuthFailed(const QString& reason)
|
||||||
|
{
|
||||||
|
authStatus->setText("Auth failed");
|
||||||
|
authStatus->setStyleSheet("color: red;");
|
||||||
|
QMessageBox::warning(this, "Authentication Failed", reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
void onEventReceived(const QString& event, const QJsonObject& data)
|
||||||
|
{
|
||||||
|
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");
|
||||||
|
} else if (event == "playback.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("-");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
void setupUI()
|
||||||
|
{
|
||||||
|
setWindowTitle("Echoion Desktop Client");
|
||||||
|
setMinimumSize(600, 400);
|
||||||
|
|
||||||
|
auto* centralWidget = new QWidget(this);
|
||||||
|
setCentralWidget(centralWidget);
|
||||||
|
|
||||||
|
auto* mainLayout = new QVBoxLayout(centralWidget);
|
||||||
|
|
||||||
|
// Connection Section
|
||||||
|
auto* connGroup = new QGroupBox("Connection", this);
|
||||||
|
auto* connLayout = new QFormLayout(connGroup);
|
||||||
|
|
||||||
|
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");
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
connect(skipBtn, &QPushButton::clicked, this,
|
||||||
|
&SimpleMainWindow::onSkipClicked);
|
||||||
|
}
|
||||||
|
|
||||||
|
void setupConnections()
|
||||||
|
{
|
||||||
|
connect(client_, &CoreClient::connected, this,
|
||||||
|
&SimpleMainWindow::onConnected);
|
||||||
|
connect(client_, &CoreClient::disconnected, this,
|
||||||
|
&SimpleMainWindow::onDisconnected);
|
||||||
|
connect(client_, &CoreClient::authTokenRequested, this,
|
||||||
|
&SimpleMainWindow::onAuthTokenRequested);
|
||||||
|
connect(client_, &CoreClient::authenticated, this,
|
||||||
|
&SimpleMainWindow::onAuthenticated);
|
||||||
|
connect(client_, &CoreClient::authFailed, this,
|
||||||
|
&SimpleMainWindow::onAuthFailed);
|
||||||
|
connect(client_, &CoreClient::eventReceived, this,
|
||||||
|
&SimpleMainWindow::onEventReceived);
|
||||||
|
}
|
||||||
|
|
||||||
|
CoreClient* client_;
|
||||||
|
QLineEdit *hostEdit, *portEdit, *nicknameEdit, *tokenEdit;
|
||||||
|
QPushButton *connectBtn, *requestTokenBtn, *authBtn;
|
||||||
|
QLabel *connectionStatus, *authStatus, *currentTrackLabel, *artistLabel,
|
||||||
|
*playbackStatus;
|
||||||
|
};
|
||||||
|
|
||||||
|
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);
|
||||||
|
window.show();
|
||||||
|
|
||||||
|
// Start auto-connect if enabled
|
||||||
|
QTimer::singleShot(100, &coreClient, &CoreClient::startAutoConnect);
|
||||||
|
|
||||||
|
return app.exec();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#include "main.moc"
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
#include "storage/SecureStorage.hpp"
|
||||||
|
#include <QCoreApplication>
|
||||||
|
#include <QDateTime>
|
||||||
|
#include <QDir>
|
||||||
|
#include <QFileInfo>
|
||||||
|
#include <QStandardPaths>
|
||||||
|
#include <QtEndian>
|
||||||
|
|
||||||
|
namespace Echoion::Desktop
|
||||||
|
{
|
||||||
|
|
||||||
|
SecureStorage::SecureStorage() = default;
|
||||||
|
|
||||||
|
QString SecureStorage::getStorageDir()
|
||||||
|
{
|
||||||
|
QString appDir = QCoreApplication::applicationDirPath();
|
||||||
|
QString dataDir = appDir + "/data";
|
||||||
|
|
||||||
|
QDir dir(dataDir);
|
||||||
|
if (!dir.exists()) {
|
||||||
|
dir.mkpath(".");
|
||||||
|
}
|
||||||
|
|
||||||
|
return dataDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
QString SecureStorage::getSettingsPath()
|
||||||
|
{
|
||||||
|
return getStorageDir() + "/settings.dat";
|
||||||
|
}
|
||||||
|
|
||||||
|
QString SecureStorage::getTokensPath()
|
||||||
|
{
|
||||||
|
return getStorageDir() + "/tokens.dat";
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray SecureStorage::generateKey() const
|
||||||
|
{
|
||||||
|
if (!cachedKey_.isEmpty()) {
|
||||||
|
return cachedKey_;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate a deterministic key from machine-specific data
|
||||||
|
// This makes it harder to copy tokens to another machine
|
||||||
|
QString seed =
|
||||||
|
QCoreApplication::applicationDirPath() +
|
||||||
|
QCoreApplication::applicationName() +
|
||||||
|
QString::number(QDateTime::currentDateTime().date().year());
|
||||||
|
|
||||||
|
QByteArray hash =
|
||||||
|
QCryptographicHash::hash(seed.toUtf8(), QCryptographicHash::Sha256);
|
||||||
|
|
||||||
|
// Add some randomness but keep it deterministic for this machine
|
||||||
|
QRandomGenerator rng(qHash(seed));
|
||||||
|
for (int i = 0; i < hash.size(); ++i) {
|
||||||
|
hash[i] = hash[i] ^ static_cast<char>(rng.generate() & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
cachedKey_ = hash;
|
||||||
|
return hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray SecureStorage::xorEncrypt(const QByteArray& data,
|
||||||
|
const QByteArray& key) const
|
||||||
|
{
|
||||||
|
QByteArray result = data;
|
||||||
|
int keyLen = key.length();
|
||||||
|
|
||||||
|
for (int i = 0; i < result.length(); ++i) {
|
||||||
|
result[i] = result[i] ^ key[i % keyLen];
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray SecureStorage::encrypt(const QByteArray& data) const
|
||||||
|
{
|
||||||
|
QByteArray key = generateKey();
|
||||||
|
|
||||||
|
// Add simple header for validation
|
||||||
|
QByteArray header;
|
||||||
|
QDataStream headerStream(&header, QIODevice::WriteOnly);
|
||||||
|
headerStream << quint32(0x4543484F); // "ECHO" magic
|
||||||
|
headerStream << quint32(data.length());
|
||||||
|
|
||||||
|
QByteArray encrypted = xorEncrypt(data, key);
|
||||||
|
|
||||||
|
return header + encrypted;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray SecureStorage::decrypt(const QByteArray& data) const
|
||||||
|
{
|
||||||
|
if (data.length() < 8) {
|
||||||
|
return QByteArray(); // Too short
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify header
|
||||||
|
QDataStream headerStream(data);
|
||||||
|
quint32 magic;
|
||||||
|
quint32 dataLen;
|
||||||
|
headerStream >> magic >> dataLen;
|
||||||
|
|
||||||
|
if (magic != 0x4543484F) {
|
||||||
|
return QByteArray(); // Invalid magic
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray key = generateKey();
|
||||||
|
QByteArray encrypted = data.mid(8); // Skip header
|
||||||
|
|
||||||
|
return xorEncrypt(encrypted, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SecureStorage::saveToFile(const QString& filepath,
|
||||||
|
const QByteArray& data) const
|
||||||
|
{
|
||||||
|
// Create backup of existing file
|
||||||
|
if (QFile::exists(filepath)) {
|
||||||
|
createBackup(filepath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write to temp file first
|
||||||
|
QString tempPath = filepath + ".tmp";
|
||||||
|
QFile tempFile(tempPath);
|
||||||
|
|
||||||
|
if (!tempFile.open(QIODevice::WriteOnly)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tempFile.write(data) != data.length()) {
|
||||||
|
tempFile.close();
|
||||||
|
QFile::remove(tempPath);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
tempFile.close();
|
||||||
|
|
||||||
|
// Atomic rename
|
||||||
|
if (!QFile::rename(tempPath, filepath)) {
|
||||||
|
QFile::remove(tempPath);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray SecureStorage::loadFromFile(const QString& filepath) const
|
||||||
|
{
|
||||||
|
QFile file(filepath);
|
||||||
|
|
||||||
|
if (!file.open(QIODevice::ReadOnly)) {
|
||||||
|
// Try to restore from backup
|
||||||
|
if (restoreFromBackup(filepath)) {
|
||||||
|
return loadFromFile(filepath); // Retry
|
||||||
|
}
|
||||||
|
return QByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray data = file.readAll();
|
||||||
|
file.close();
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SecureStorage::createBackup(const QString& filepath) const
|
||||||
|
{
|
||||||
|
QString backupPath = filepath + ".backup";
|
||||||
|
QFile::remove(backupPath); // Remove old backup
|
||||||
|
QFile::copy(filepath, backupPath);
|
||||||
|
|
||||||
|
// Cleanup old backups (keep only last 3)
|
||||||
|
cleanupOldBackups(filepath, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SecureStorage::restoreFromBackup(const QString& filepath) const
|
||||||
|
{
|
||||||
|
QString backupPath = filepath + ".backup";
|
||||||
|
|
||||||
|
if (!QFile::exists(backupPath)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
QFile::remove(filepath);
|
||||||
|
return QFile::copy(backupPath, filepath);
|
||||||
|
}
|
||||||
|
|
||||||
|
void SecureStorage::cleanupOldBackups(const QString& filepath,
|
||||||
|
int maxBackups) const
|
||||||
|
{
|
||||||
|
QString basePath = filepath + ".backup";
|
||||||
|
QFileInfo info(basePath);
|
||||||
|
QDir dir = info.dir();
|
||||||
|
QString baseName = info.fileName();
|
||||||
|
|
||||||
|
// List all backup files
|
||||||
|
QStringList filters;
|
||||||
|
filters << baseName + "*";
|
||||||
|
|
||||||
|
QFileInfoList backups = dir.entryInfoList(filters, QDir::Files);
|
||||||
|
|
||||||
|
if (backups.size() <= maxBackups) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort by modification time (oldest first)
|
||||||
|
std::sort(backups.begin(), backups.end(),
|
||||||
|
[](const QFileInfo& a, const QFileInfo& b) {
|
||||||
|
return a.lastModified() < b.lastModified();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Remove oldest backups
|
||||||
|
for (int i = 0; i < backups.size() - maxBackups; ++i) {
|
||||||
|
QFile::remove(backups[i].absoluteFilePath());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Echoion::Desktop
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QCryptographicHash>
|
||||||
|
#include <QDataStream>
|
||||||
|
#include <QFile>
|
||||||
|
#include <QRandomGenerator>
|
||||||
|
#include <QString>
|
||||||
|
|
||||||
|
namespace Echoion::Desktop
|
||||||
|
{
|
||||||
|
|
||||||
|
class SecureStorage
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
SecureStorage();
|
||||||
|
|
||||||
|
// Encrypt/decrypt data using Qt crypto
|
||||||
|
[[nodiscard]] QByteArray encrypt(const QByteArray& data) const;
|
||||||
|
[[nodiscard]] QByteArray decrypt(const QByteArray& data) const;
|
||||||
|
|
||||||
|
// File operations with backup
|
||||||
|
[[nodiscard]] bool saveToFile(const QString& filepath,
|
||||||
|
const QByteArray& data) const;
|
||||||
|
|
||||||
|
[[nodiscard]] QByteArray
|
||||||
|
loadFromFile(const QString& filepath) const;
|
||||||
|
|
||||||
|
// Backup management
|
||||||
|
void createBackup(const QString& filepath) const;
|
||||||
|
bool restoreFromBackup(const QString& filepath) const;
|
||||||
|
void cleanupOldBackups(const QString& filepath,
|
||||||
|
int maxBackups = 3) const;
|
||||||
|
|
||||||
|
// Get storage directory (relative to executable)
|
||||||
|
[[nodiscard]] static QString getStorageDir();
|
||||||
|
[[nodiscard]] static QString getSettingsPath();
|
||||||
|
[[nodiscard]] static QString getTokensPath();
|
||||||
|
[[nodiscard]] static QString getCacheDir();
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
// Generate encryption key from machine-specific data
|
||||||
|
[[nodiscard]] QByteArray generateKey() const;
|
||||||
|
|
||||||
|
// Simple XOR encryption with SHA-256 derived key
|
||||||
|
[[nodiscard]] QByteArray xorEncrypt(const QByteArray& data,
|
||||||
|
const QByteArray& key) const;
|
||||||
|
|
||||||
|
mutable QByteArray cachedKey_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Echoion::Desktop
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
#include "storage/SecureStorage.hpp"
|
||||||
|
#include "storage/SettingsManager.hpp"
|
||||||
|
#include <QDataStream>
|
||||||
|
|
||||||
|
namespace Echoion::Desktop
|
||||||
|
{
|
||||||
|
|
||||||
|
SettingsManager::SettingsManager(QObject* parent) : QObject(parent) {}
|
||||||
|
|
||||||
|
bool SettingsManager::load()
|
||||||
|
{
|
||||||
|
bool settingsOk = loadSettings();
|
||||||
|
bool tokensOk = loadTokens();
|
||||||
|
|
||||||
|
if (settingsOk || tokensOk) {
|
||||||
|
emit settingsLoaded();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SettingsManager::save()
|
||||||
|
{
|
||||||
|
bool settingsOk = saveSettings();
|
||||||
|
bool tokensOk = saveTokens();
|
||||||
|
|
||||||
|
if (settingsOk && tokensOk) {
|
||||||
|
emit settingsSaved();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SettingsManager::loadSettings()
|
||||||
|
{
|
||||||
|
SecureStorage storage;
|
||||||
|
QString path = SecureStorage::getSettingsPath();
|
||||||
|
|
||||||
|
if (!QFile::exists(path)) {
|
||||||
|
// No settings file yet, use defaults
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray encrypted = storage.loadFromFile(path);
|
||||||
|
if (encrypted.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray decrypted = storage.decrypt(encrypted);
|
||||||
|
if (decrypted.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
QDataStream stream(decrypted);
|
||||||
|
stream >> settings_;
|
||||||
|
|
||||||
|
return stream.status() == QDataStream::Ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SettingsManager::saveSettings()
|
||||||
|
{
|
||||||
|
SecureStorage storage;
|
||||||
|
|
||||||
|
QByteArray data;
|
||||||
|
QDataStream stream(&data, QIODevice::WriteOnly);
|
||||||
|
stream << settings_;
|
||||||
|
|
||||||
|
if (stream.status() != QDataStream::Ok) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray encrypted = storage.encrypt(data);
|
||||||
|
return storage.saveToFile(SecureStorage::getSettingsPath(), encrypted);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SettingsManager::loadTokens()
|
||||||
|
{
|
||||||
|
SecureStorage storage;
|
||||||
|
QString path = SecureStorage::getTokensPath();
|
||||||
|
|
||||||
|
if (!QFile::exists(path)) {
|
||||||
|
// No tokens file yet
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray encrypted = storage.loadFromFile(path);
|
||||||
|
if (encrypted.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray decrypted = storage.decrypt(encrypted);
|
||||||
|
if (decrypted.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
QDataStream stream(decrypted);
|
||||||
|
stream >> tokens_;
|
||||||
|
|
||||||
|
return stream.status() == QDataStream::Ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SettingsManager::saveTokens()
|
||||||
|
{
|
||||||
|
SecureStorage storage;
|
||||||
|
|
||||||
|
QByteArray data;
|
||||||
|
QDataStream stream(&data, QIODevice::WriteOnly);
|
||||||
|
stream << tokens_;
|
||||||
|
|
||||||
|
if (stream.status() != QDataStream::Ok) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray encrypted = storage.encrypt(data);
|
||||||
|
return storage.saveToFile(SecureStorage::getTokensPath(), encrypted);
|
||||||
|
}
|
||||||
|
|
||||||
|
void SettingsManager::addProfile(const ConnectionProfile& profile)
|
||||||
|
{
|
||||||
|
// Remove existing profile with same name
|
||||||
|
removeProfile(profile.name);
|
||||||
|
|
||||||
|
settings_.profiles.append(profile);
|
||||||
|
|
||||||
|
// If this is the first profile or marked as default, update
|
||||||
|
// lastProfileName
|
||||||
|
if (settings_.profiles.size() == 1 || profile.isDefault) {
|
||||||
|
if (profile.isDefault) {
|
||||||
|
// Unset default on other profiles
|
||||||
|
for (auto& p : settings_.profiles) {
|
||||||
|
if (p.name != profile.name) {
|
||||||
|
p.isDefault = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
settings_.lastProfileName = profile.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
save();
|
||||||
|
emit profileAdded(profile.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
void SettingsManager::removeProfile(const QString& name)
|
||||||
|
{
|
||||||
|
auto it = std::remove_if(
|
||||||
|
settings_.profiles.begin(),
|
||||||
|
settings_.profiles.end(),
|
||||||
|
[&name](const ConnectionProfile& p) { return p.name == name; });
|
||||||
|
|
||||||
|
if (it != settings_.profiles.end()) {
|
||||||
|
settings_.profiles.erase(it, settings_.profiles.end());
|
||||||
|
|
||||||
|
// Update lastProfileName if needed
|
||||||
|
if (settings_.lastProfileName == name) {
|
||||||
|
if (!settings_.profiles.isEmpty()) {
|
||||||
|
settings_.lastProfileName = settings_.profiles.first().name;
|
||||||
|
} else {
|
||||||
|
settings_.lastProfileName.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
save();
|
||||||
|
emit profileRemoved(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void SettingsManager::updateProfile(const QString& name,
|
||||||
|
const ConnectionProfile& profile)
|
||||||
|
{
|
||||||
|
removeProfile(name);
|
||||||
|
addProfile(profile);
|
||||||
|
emit profileChanged(profile.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
QVector<ConnectionProfile> SettingsManager::profiles() const
|
||||||
|
{
|
||||||
|
return settings_.profiles;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ConnectionProfile>
|
||||||
|
SettingsManager::getProfile(const QString& name) const
|
||||||
|
{
|
||||||
|
for (const auto& profile : settings_.profiles) {
|
||||||
|
if (profile.name == name) {
|
||||||
|
return profile;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ConnectionProfile> SettingsManager::getDefaultProfile() const
|
||||||
|
{
|
||||||
|
// First try to find profile marked as default
|
||||||
|
for (const auto& profile : settings_.profiles) {
|
||||||
|
if (profile.isDefault) {
|
||||||
|
return profile;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then try last used profile
|
||||||
|
if (!settings_.lastProfileName.isEmpty()) {
|
||||||
|
auto profile = getProfile(settings_.lastProfileName);
|
||||||
|
if (profile) {
|
||||||
|
return profile;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finally return first profile
|
||||||
|
if (!settings_.profiles.isEmpty()) {
|
||||||
|
return settings_.profiles.first();
|
||||||
|
}
|
||||||
|
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SettingsManager::setDefaultProfile(const QString& name)
|
||||||
|
{
|
||||||
|
for (auto& profile : settings_.profiles) {
|
||||||
|
profile.isDefault = (profile.name == name);
|
||||||
|
}
|
||||||
|
|
||||||
|
settings_.lastProfileName = name;
|
||||||
|
save();
|
||||||
|
}
|
||||||
|
|
||||||
|
void SettingsManager::saveToken(const QString& host, int port,
|
||||||
|
const QString& nickname,
|
||||||
|
const QString& token)
|
||||||
|
{
|
||||||
|
// Remove existing token for this host:port
|
||||||
|
deleteToken(host, port);
|
||||||
|
|
||||||
|
CachedToken ct;
|
||||||
|
ct.host = host;
|
||||||
|
ct.port = port;
|
||||||
|
ct.nickname = nickname;
|
||||||
|
ct.token = token;
|
||||||
|
ct.savedAt = QDateTime::currentDateTime();
|
||||||
|
|
||||||
|
tokens_.append(ct);
|
||||||
|
saveTokens();
|
||||||
|
|
||||||
|
emit tokenSaved(host, port);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<QString> SettingsManager::loadToken(
|
||||||
|
const QString& host, int port, QString& outNickname) const
|
||||||
|
{
|
||||||
|
for (const auto& ct : tokens_) {
|
||||||
|
if (ct.host == host && ct.port == port) {
|
||||||
|
outNickname = ct.nickname;
|
||||||
|
return ct.token;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SettingsManager::deleteToken(const QString& host, int port)
|
||||||
|
{
|
||||||
|
auto it = std::remove_if(tokens_.begin(), tokens_.end(),
|
||||||
|
[&host, port](const CachedToken& ct) {
|
||||||
|
return ct.host == host && ct.port == port;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (it != tokens_.end()) {
|
||||||
|
tokens_.erase(it, tokens_.end());
|
||||||
|
saveTokens();
|
||||||
|
emit tokenDeleted(host, port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void SettingsManager::clearAllTokens()
|
||||||
|
{
|
||||||
|
tokens_.clear();
|
||||||
|
saveTokens();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SettingsManager::hasToken(const QString& host, int port) const
|
||||||
|
{
|
||||||
|
for (const auto& ct : tokens_) {
|
||||||
|
if (ct.host == host && ct.port == port) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
AppSettings& SettingsManager::settings() { return settings_; }
|
||||||
|
|
||||||
|
const AppSettings& SettingsManager::settings() const { return settings_; }
|
||||||
|
|
||||||
|
} // namespace Echoion::Desktop
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QDataStream>
|
||||||
|
#include <QDateTime>
|
||||||
|
#include <QObject>
|
||||||
|
#include <QString>
|
||||||
|
#include <QVector>
|
||||||
|
|
||||||
|
namespace Echoion::Desktop
|
||||||
|
{
|
||||||
|
|
||||||
|
struct ConnectionProfile {
|
||||||
|
QString name;
|
||||||
|
QString host;
|
||||||
|
int port = 8765;
|
||||||
|
QString nickname;
|
||||||
|
bool autoConnect = false;
|
||||||
|
bool autoAuth = false;
|
||||||
|
bool isDefault = false;
|
||||||
|
|
||||||
|
// Serialization
|
||||||
|
friend QDataStream& operator<<(QDataStream& out,
|
||||||
|
const ConnectionProfile& profile)
|
||||||
|
{
|
||||||
|
out << profile.name << profile.host << profile.port
|
||||||
|
<< profile.nickname << profile.autoConnect
|
||||||
|
<< profile.autoAuth << profile.isDefault;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
friend QDataStream& operator>>(QDataStream& in,
|
||||||
|
ConnectionProfile& profile)
|
||||||
|
{
|
||||||
|
in >> profile.name >> profile.host >> profile.port >>
|
||||||
|
profile.nickname >> profile.autoConnect >>
|
||||||
|
profile.autoAuth >> profile.isDefault;
|
||||||
|
return in;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CachedToken {
|
||||||
|
QString host;
|
||||||
|
int port;
|
||||||
|
QString nickname;
|
||||||
|
QString token;
|
||||||
|
QDateTime savedAt;
|
||||||
|
|
||||||
|
// Serialization
|
||||||
|
friend QDataStream& operator<<(QDataStream& out,
|
||||||
|
const CachedToken& token)
|
||||||
|
{
|
||||||
|
out << token.host << token.port << token.nickname << token.token
|
||||||
|
<< token.savedAt;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
friend QDataStream& operator>>(QDataStream& in, CachedToken& token)
|
||||||
|
{
|
||||||
|
in >> token.host >> token.port >> token.nickname >>
|
||||||
|
token.token >> token.savedAt;
|
||||||
|
return in;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct AppSettings {
|
||||||
|
QVector<ConnectionProfile> profiles;
|
||||||
|
QString lastProfileName;
|
||||||
|
bool autoConnect = true;
|
||||||
|
bool autoAuth = true;
|
||||||
|
bool autoReconnect = true;
|
||||||
|
int maxReconnectAttempts = 5;
|
||||||
|
int requestTimeoutMs = 10000;
|
||||||
|
|
||||||
|
// Serialization
|
||||||
|
friend QDataStream& operator<<(QDataStream& out,
|
||||||
|
const AppSettings& settings)
|
||||||
|
{
|
||||||
|
out << settings.profiles << settings.lastProfileName
|
||||||
|
<< settings.autoConnect << settings.autoAuth
|
||||||
|
<< settings.autoReconnect << settings.maxReconnectAttempts
|
||||||
|
<< settings.requestTimeoutMs;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
friend QDataStream& operator>>(QDataStream& in,
|
||||||
|
AppSettings& settings)
|
||||||
|
{
|
||||||
|
in >> settings.profiles >> settings.lastProfileName >>
|
||||||
|
settings.autoConnect >> settings.autoAuth >>
|
||||||
|
settings.autoReconnect >> settings.maxReconnectAttempts >>
|
||||||
|
settings.requestTimeoutMs;
|
||||||
|
return in;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
class SettingsManager : public QObject
|
||||||
|
{
|
||||||
|
Q_OBJECT
|
||||||
|
|
||||||
|
public:
|
||||||
|
|
||||||
|
explicit SettingsManager(QObject* parent = nullptr);
|
||||||
|
|
||||||
|
// Load/save all settings
|
||||||
|
bool load();
|
||||||
|
bool save();
|
||||||
|
|
||||||
|
// Connection profiles
|
||||||
|
void addProfile(const ConnectionProfile& profile);
|
||||||
|
void removeProfile(const QString& name);
|
||||||
|
void updateProfile(const QString& name,
|
||||||
|
const ConnectionProfile& profile);
|
||||||
|
QVector<ConnectionProfile> profiles() const;
|
||||||
|
std::optional<ConnectionProfile>
|
||||||
|
getProfile(const QString& name) const;
|
||||||
|
std::optional<ConnectionProfile> getDefaultProfile() const;
|
||||||
|
void setDefaultProfile(const QString& name);
|
||||||
|
|
||||||
|
// Token management
|
||||||
|
void saveToken(const QString& host, int port,
|
||||||
|
const QString& nickname, const QString& token);
|
||||||
|
std::optional<QString> loadToken(const QString& host, int port,
|
||||||
|
QString& outNickname) const;
|
||||||
|
void deleteToken(const QString& host, int port);
|
||||||
|
void clearAllTokens();
|
||||||
|
bool hasToken(const QString& host, int port) const;
|
||||||
|
|
||||||
|
// Settings accessors
|
||||||
|
AppSettings& settings();
|
||||||
|
const AppSettings& settings() const;
|
||||||
|
|
||||||
|
signals:
|
||||||
|
|
||||||
|
void settingsLoaded();
|
||||||
|
void settingsSaved();
|
||||||
|
void profileAdded(const QString& name);
|
||||||
|
void profileRemoved(const QString& name);
|
||||||
|
void profileChanged(const QString& name);
|
||||||
|
void tokenSaved(const QString& host, int port);
|
||||||
|
void tokenDeleted(const QString& host, int port);
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
bool loadSettings();
|
||||||
|
bool saveSettings();
|
||||||
|
bool loadTokens();
|
||||||
|
bool saveTokens();
|
||||||
|
|
||||||
|
AppSettings settings_;
|
||||||
|
QVector<CachedToken> tokens_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Echoion::Desktop
|
||||||
Reference in new issue
Block a user