diff --git a/CMakeLists.txt b/CMakeLists.txt index 8883333..e05ad8e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) set(CMAKE_CXX_STANDARD 26) @@ -11,15 +11,11 @@ set(CMAKE_AUTOUIC ON) find_package(Qt6 REQUIRED COMPONENTS Core Widgets Network WebSockets) -add_executable(EchoionDesktop - src/main.cpp - src/MainWindow.cpp - src/MainWindow.hpp - src/LoginDialog.cpp - src/LoginDialog.hpp - src/CoreClient.cpp - src/CoreClient.hpp +file(GLOB_RECURSE DESKTOP_SOURCES + CONFIGURE_DEPENDS + "src/**.cpp" ) +add_executable(EchoionDesktop ${DESKTOP_SOURCES}) add_executable(Echoion::Desktop ALIAS EchoionDesktop) diff --git a/src/CoreClient.cpp b/src/CoreClient.cpp index a86f9a7..59e909c 100644 --- a/src/CoreClient.cpp +++ b/src/CoreClient.cpp @@ -1,439 +1,539 @@ #include "CoreClient.hpp" -#include #include +#include #include -#include -#include +#include -namespace Echoion::Desktop { +namespace Echoion::Desktop +{ -CoreClient::CoreClient(QObject* parent) - : QObject(parent) - , socket_(new QWebSocket(QString(), QWebSocketProtocol::VersionLatest, this)) { - - connect(socket_, &QWebSocket::connected, this, &CoreClient::onConnected); - connect(socket_, &QWebSocket::disconnected, this, &CoreClient::onDisconnected); - connect(socket_, QOverload::of(&QWebSocket::error), - this, &CoreClient::onError); - connect(socket_, &QWebSocket::textMessageReceived, this, &CoreClient::onMessageReceived); - connect(socket_, &QWebSocket::binaryMessageReceived, this, &CoreClient::onBinaryMessageReceived); -} + CoreClient::CoreClient(QObject* parent) + : QObject(parent), + socket_(new QWebSocket(QString(), QWebSocketProtocol::VersionLatest, + this)), + reconnectTimer_(new QTimer(this)) + { + setupSocket(); -CoreClient::~CoreClient() { - disconnectFromCore(); -} + reconnectTimer_->setSingleShot(true); + connect(reconnectTimer_, &QTimer::timeout, this, + &CoreClient::onReconnectTimer); + } -void CoreClient::connectToCore(const QString& host, int port) { - QString url = QString("ws://%1:%2/rpc").arg(host).arg(port); - socket_->open(QUrl(url)); -} + CoreClient::~CoreClient() { disconnectFromHost(); } -void CoreClient::disconnectFromCore() { - shouldReconnect_ = false; - if (socket_->state() != QAbstractSocket::UnconnectedState) { - socket_->close(); - } -} + void CoreClient::setupSocket() + { + connect(socket_, &QWebSocket::connected, this, + &CoreClient::onSocketConnected); + connect(socket_, &QWebSocket::disconnected, this, + &CoreClient::onSocketDisconnected); + connect(socket_, + QOverload::of(&QWebSocket::error), + this, &CoreClient::onSocketError); + connect(socket_, &QWebSocket::textMessageReceived, this, + &CoreClient::onTextMessageReceived); + } -bool CoreClient::isConnected() const { - return socket_->state() == QAbstractSocket::ConnectedState; -} + void CoreClient::loadSettings() { settingsManager_.load(); } -void CoreClient::authenticate(const QString& username, const QString& password) { - 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::saveSettings() { settingsManager_.save(); } -void CoreClient::logout() { - sendRpcRequest("auth.logout"); - authToken_.clear(); - emit loggedOut(); -} + void CoreClient::enableAutoConnect(bool enabled) + { + autoConnectEnabled_ = enabled; + settingsManager_.settings().autoConnect = enabled; + settingsManager_.save(); + } -bool CoreClient::isAuthenticated() const { - return !authToken_.isEmpty(); -} + bool CoreClient::autoConnectEnabled() const { return autoConnectEnabled_; } -void CoreClient::play(const QString& query) { - QJsonObject params; - params["query"] = query; - sendRpcRequest("playback.play", params); -} + void CoreClient::startAutoConnect() + { + if (!autoConnectEnabled_) { + return; + } -void CoreClient::pause() { - sendRpcRequest("playback.pause"); -} + auto profile = settingsManager_.getDefaultProfile(); + if (profile) { + currentHost_ = profile->host; + currentPort_ = profile->port; + currentNickname_ = profile->nickname; -void CoreClient::resume() { - sendRpcRequest("playback.resume"); -} + emit reconnecting(0); + connectToHost(profile->host, profile->port); + } + } -void CoreClient::stop() { - sendRpcRequest("playback.stop"); -} + void CoreClient::connectToHost(const QString& host, int port) + { + currentHost_ = host; + currentPort_ = port; -void CoreClient::skip(int count) { - QJsonObject params; - params["count"] = count; - sendRpcRequest("playback.skip", params); -} + // Reset reconnection attempts for manual connection + reconnectAttempts_ = 0; + stopReconnectTimer(); -void CoreClient::seek(int positionMs) { - QJsonObject params; - params["position"] = positionMs; - sendRpcRequest("playback.seek", params); -} + QString url = QString("ws://%1:%2").arg(host).arg(port); + qDebug() << "Connecting to:" << url; + socket_->open(QUrl(url)); + } -void CoreClient::setVolume(int volume) { - QJsonObject params; - params["volume"] = qBound(0, volume, 100); - sendRpcRequest("playback.setVolume", params); -} + void CoreClient::disconnectFromHost() + { + stopReconnectTimer(); + cancelPendingRequests(); -void CoreClient::queueTrack(const QString& query) { - QJsonObject params; - 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()); - } - }); -} + if (socket_->state() != QAbstractSocket::UnconnectedState) { + socket_->close(); + } + } -void CoreClient::removeFromQueue(int position) { - QJsonObject params; - params["position"] = position; - sendRpcRequest("queue.remove", params, [this, position](const QJsonObject& result) { - if (result["success"].toBool()) { - emit trackRemoved(position); - } - }); -} + bool CoreClient::isConnected() const + { + return socket_->state() == QAbstractSocket::ConnectedState; + } -void CoreClient::clearQueue() { - sendRpcRequest("queue.clear"); -} + void CoreClient::requestAuthToken(const QString& nickname) + { + currentNickname_ = nickname; -void CoreClient::moveInQueue(int from, int to) { - QJsonObject params; - params["from"] = from; - params["to"] = to; - sendRpcRequest("queue.move", params); -} + QJsonObject params; + params["nickname"] = nickname; -void CoreClient::shuffle() { - sendRpcRequest("queue.shuffle"); -} + call("Authenticate", params, [this](const QJsonObject& result) { + if (result["success"].toBool()) { + emit authTokenRequested(); + } else { + emit authFailed(result["message"].toString("Unknown error")); + } + }); + } -void CoreClient::toggleRepeat() { - sendRpcRequest("playback.toggleRepeat"); -} + void CoreClient::authenticate(const QString& token) + { + authToken_ = token; -void CoreClient::toggleShuffle() { - sendRpcRequest("playback.toggleShuffle"); -} + QJsonObject params; + params["token"] = token; -void CoreClient::search(const QString& query) { - QJsonObject params; - params["query"] = query; - sendRpcRequest("search.query", params, [this](const QJsonObject& result) { - auto searchResult = parseSearchResult(result); - emit searchResultsReceived(searchResult); - }); -} + call("Authenticate", params, [this](const QJsonObject& result) { + if (result["success"].toBool()) { + isAuthenticated_ = true; + emit authenticated(); -void CoreClient::loadPlaylist(const QString& playlistId) { - QJsonObject params; - params["playlistId"] = playlistId; - sendRpcRequest("playlist.load", params, [this, playlistId](const QJsonObject& result) { - emit playlistLoaded(playlistId, result["trackCount"].toInt()); - }); -} + // Save token for auto-auth + if (!currentHost_.isEmpty() && !currentNickname_.isEmpty()) { + settingsManager_.saveToken(currentHost_, currentPort_, + currentNickname_, authToken_); + emit tokenSaved(currentHost_, currentPort_); + } + } else { + isAuthenticated_ = false; + emit authFailed( + result["message"].toString("Authentication failed")); + } + }); + } -void CoreClient::savePlaylist(const QString& name, const QString& description) { - QJsonObject params; - params["name"] = name; - params["description"] = description; - sendRpcRequest("playlist.save", params); -} + void CoreClient::logout() + { + call("Logout"); -void CoreClient::getUserPlaylists() { - sendRpcRequest("playlist.list", {}, [this](const QJsonObject& result) { - std::vector playlists; - 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); - }); -} + isAuthenticated_ = false; + authToken_.clear(); + emit loggedOut(); + } -void CoreClient::requestPlaybackState() { - sendRpcRequest("state.getPlayback", {}, [this](const QJsonObject& result) { - emit playbackStateReceived(parsePlaybackState(result)); - }); -} + bool CoreClient::isAuthenticated() const { return isAuthenticated_; } -void CoreClient::requestQueue() { - sendRpcRequest("queue.get", {}, [this](const QJsonObject& result) { - std::vector queue; - QJsonArray arr = result["queue"].toArray(); - for (const auto& item : arr) { - queue.push_back(parseQueueEntry(item.toObject())); - } - emit queueReceived(queue); - }); -} + void CoreClient::clearCachedToken() + { + if (!currentHost_.isEmpty()) { + settingsManager_.deleteToken(currentHost_, currentPort_); + } + logout(); + } -void CoreClient::requestCurrentTrack() { - sendRpcRequest("state.getCurrentTrack", {}, [this](const QJsonObject& result) { - if (!result["track"].isNull()) { - emit trackStarted(parseTrackInfo(result["track"].toObject())); - } - }); -} + void CoreClient::call(const QString& method, const QJsonObject& params) + { + call(method, params, nullptr); + } -void CoreClient::reloadCore() { - sendRpcRequest("system.reload"); -} + int CoreClient::methodToInt(const QString& method) const + { + // Map method names to RpcMethod enum values + static const QHash 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() { - 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(); -} + return methodMap.value(method, -1); + } -void CoreClient::onDisconnected() { - emit disconnected(); - - // Attempt reconnection - if (shouldReconnect_ && reconnectAttempts_ < MAX_RECONNECT_ATTEMPTS) { - reconnectAttempts_++; - QTimer::singleShot(1000 * reconnectAttempts_, [this]() { - connectToCore(); - }); - } -} + void CoreClient::call(const QString& method, const QJsonObject& params, + RpcCallback callback) + { + if (!isConnected()) { + if (callback) { + QJsonObject error; + error["success"] = false; + error["message"] = "Not connected"; + callback(error); + } + return; + } -void CoreClient::onError(QAbstractSocket::SocketError error) { - QString errorMsg; - switch (error) { - case QAbstractSocket::ConnectionRefusedError: - errorMsg = "Connection refused - is the core running?"; - break; - case QAbstractSocket::RemoteHostClosedError: - errorMsg = "Connection closed by server"; - break; - case QAbstractSocket::HostNotFoundError: - errorMsg = "Server not found"; - break; - default: - errorMsg = QString("Socket error: %1").arg(socket_->errorString()); - } - emit errorOccurred(errorMsg); -} + int methodInt = methodToInt(method); + if (methodInt < 0) { + if (callback) { + QJsonObject error; + error["success"] = false; + error["message"] = "Unknown method: " + method; + callback(error); + } + return; + } -void CoreClient::onMessageReceived(const QString& message) { - 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); - } -} + quint64 requestId = nextRequestId_++; -void CoreClient::onBinaryMessageReceived(const QByteArray& data) { - // Handle binary data if needed (e.g., album art) -} + QJsonObject request; + request["id"] = static_cast(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) { - sendRpcRequest(method, params, nullptr); -} + if (!authToken_.isEmpty()) { + request["authToken"] = authToken_; + } -void CoreClient::sendRpcRequest(const QString& method, const QJsonObject& params, RpcCallback callback) { - if (!isConnected()) { - return; - } - - QJsonObject request; - QString id = QUuid::createUuid().toString(); - - 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))); -} + if (callback) { + PendingRequest pending; + pending.method = method; + pending.params = params; + pending.callback = callback; + pending.retryCount = 0; + pendingRequests_[requestId] = std::move(pending); + } -void CoreClient::handleRpcResponse(const QJsonObject& response) { - QString id = response["id"].toString(); - - 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); - } -} + QJsonDocument doc(request); + socket_->sendTextMessage(doc.toJson(QJsonDocument::Compact)); + } -void CoreClient::handleEvent(const QJsonObject& event) { - QString eventType = event["event"].toString(); - QJsonObject data = event["data"].toObject(); - - if (eventType == "playback.stateChanged") { - 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()); - } -} + void CoreClient::retryRequest(quint64 requestId) + { + auto it = pendingRequests_.find(requestId); + if (it == pendingRequests_.end()) { + return; + } -Echoion::Api::PlaybackState CoreClient::parsePlaybackState(const QJsonObject& obj) { - Echoion::Api::PlaybackState state; - - state.isPlaying = obj["isPlaying"].toBool(); - state.isPaused = obj["isPaused"].toBool(); - state.volume = static_cast(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; -} + auto& pending = it->second; -Echoion::Api::TrackInfo CoreClient::parseTrackInfo(const QJsonObject& obj) { - Echoion::Api::TrackInfo track; - - track.title = obj["title"].toString().toStdString(); - track.artist = obj["artist"].toString().toStdString(); - track.originalUrl = obj["originalUrl"].toString().toStdString(); - track.source = static_cast(obj["source"].toInt()); - - if (!obj["streamUrl"].isNull()) { - track.streamUrl = obj["streamUrl"].toString().toStdString(); - } - if (!obj["thumbnailUrl"].isNull()) { - track.thumbnailUrl = obj["thumbnailUrl"].toString().toStdString(); - } - if (!obj["duration"].isNull()) { - track.duration = std::chrono::milliseconds(obj["duration"].toInt()); - } - - return track; -} + if (pending.retryCount >= MAX_RETRIES) { + // Max retries reached, fail the request + if (pending.callback) { + QJsonObject error; + error["success"] = false; + error["message"] = "Max retries exceeded"; + pending.callback(error); + } + pendingRequests_.erase(it); + return; + } -Echoion::Api::QueueEntry CoreClient::parseQueueEntry(const QJsonObject& obj) { - Echoion::Api::QueueEntry entry; - - entry.queueId = static_cast(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; -} + pending.retryCount++; -Echoion::Api::SearchResult CoreClient::parseSearchResult(const QJsonObject& obj) { - Echoion::Api::SearchResult result; - - result.query = obj["query"].toString().toStdString(); - - QJsonArray tracks = obj["tracks"].toArray(); - for (const auto& item : tracks) { - result.tracks.push_back(parseTrackInfo(item.toObject())); - } - - return result; -} + // Retry after delay + QTimer::singleShot( + RETRY_DELAY_MS * pending.retryCount, this, [this, requestId]() { + auto it = pendingRequests_.find(requestId); + if (it == pendingRequests_.end()) { + return; + } -QJsonObject CoreClient::trackInfoToJson(const Echoion::Api::TrackInfo& track) { - QJsonObject obj; - obj["title"] = QString::fromStdString(track.title); - obj["artist"] = QString::fromStdString(track.artist); - obj["originalUrl"] = QString::fromStdString(track.originalUrl); - obj["source"] = static_cast(track.source); - if (track.streamUrl) { - obj["streamUrl"] = QString::fromStdString(*track.streamUrl); - } - if (track.thumbnailUrl) { - obj["thumbnailUrl"] = QString::fromStdString(*track.thumbnailUrl); - } - if (track.duration) { - obj["duration"] = static_cast(track.duration->count()); - } - return obj; -} + auto& pending = it->second; + + quint64 newRequestId = nextRequestId_++; + + QJsonObject request; + request["id"] = static_cast(newRequestId); + request["method"] = pending.method; + request["params"] = pending.params; + + if (!authToken_.isEmpty()) { + request["authToken"] = authToken_; + } + + // Move callback to new request ID + PendingRequest newPending = std::move(pending); + 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 diff --git a/src/CoreClient.hpp b/src/CoreClient.hpp index f1c9da2..8bcff64 100644 --- a/src/CoreClient.hpp +++ b/src/CoreClient.hpp @@ -1,132 +1,169 @@ #pragma once -#include -#include -#include +#include "storage/SettingsManager.hpp" #include -#include -#include -#include +#include +#include +#include #include -#include #include +#include -namespace Echoion::Desktop { +namespace Echoion::Desktop +{ -// RPC request/response handling -using RpcCallback = std::function; + // RPC request/response handling + using RpcCallback = std::function; -class CoreClient : public QObject { - Q_OBJECT + class CoreClient : public QObject + { + Q_OBJECT -public: - explicit CoreClient(QObject* parent = nullptr); - ~CoreClient() override; + public: - // Connection management - void connectToCore(const QString& host = "localhost", int port = 8765); - void disconnectFromCore(); - [[nodiscard]] bool isConnected() const; + explicit CoreClient(QObject* parent = nullptr); + ~CoreClient() override; - // Authentication - void authenticate(const QString& username, const QString& password); - void logout(); - [[nodiscard]] bool isAuthenticated() const; + // Settings integration + void loadSettings(); + void saveSettings(); + SettingsManager* settingsManager() { return &settingsManager_; } - // Playback control - void play(const QString& query); - void pause(); - void resume(); - void stop(); - void skip(int count = 1); - void seek(int positionMs); - void setVolume(int volume); // 0-100 + // Auto-connect on startup + void enableAutoConnect(bool enabled); + bool autoConnectEnabled() const; + void startAutoConnect(); - // Queue management - void queueTrack(const QString& query); - void removeFromQueue(int position); - void clearQueue(); - void moveInQueue(int from, int to); - void shuffle(); - void toggleRepeat(); - void toggleShuffle(); + // Connection management + void connectToHost(const QString& host, int port); + void disconnectFromHost(); + [[nodiscard]] bool isConnected() const; - // Search - void search(const QString& query); + // Authentication with auto-auth support + void requestAuthToken(const QString& nickname); + void authenticate(const QString& token); + void logout(); + [[nodiscard]] bool isAuthenticated() const; + void clearCachedToken(); - // Playlist management - void loadPlaylist(const QString& playlistId); - void savePlaylist(const QString& name, const QString& description); - void getUserPlaylists(); + // Generic RPC with automatic retry + void call(const QString& method, const QJsonObject& params = {}); + void call(const QString& method, const QJsonObject& params, + RpcCallback callback); - // Data requests - void requestPlaybackState(); - void requestQueue(); - void requestCurrentTrack(); + // Playback control + void play(const QString& query); + void pause(); + void resume(); + void stop(); + void skip(int count = 1); + void seek(int positionMs); + void setVolume(int volume); - // Hot reload - void reloadCore(); + // Queue management + void queueTrack(const QString& query); + void removeFromQueue(int position); + void clearQueue(); + void moveInQueue(int from, int to); + void shuffle(); + void toggleRepeat(); + void toggleShuffle(); -signals: - // Connection signals - 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& 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& playlists); - void playlistLoaded(const QString& playlistId, int trackCount); + // Search + void search(const QString& query); -private slots: - void onConnected(); - void onDisconnected(); - void onError(QAbstractSocket::SocketError error); - void onMessageReceived(const QString& message); - void onBinaryMessageReceived(const QByteArray& data); + // Playlist management + void loadPlaylist(const QString& playlistId); + void savePlaylist(const QString& name, const QString& description); + void getUserPlaylists(); -private: - void sendRpcRequest(const QString& method, const QJsonObject& params = {}); - void sendRpcRequest(const QString& method, const QJsonObject& params, RpcCallback callback); - void handleRpcResponse(const QJsonObject& response); - 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); + // Data requests (fetch on demand) + void requestPlaybackState(); + void requestQueue(); + void requestCurrentTrack(); - QWebSocket* socket_ = nullptr; - QString authToken_; - std::unordered_map pendingRequests_; - quint64 requestId_ = 0; - - // Reconnection - bool shouldReconnect_ = true; - int reconnectAttempts_ = 0; - static constexpr int MAX_RECONNECT_ATTEMPTS = 5; -}; + signals: + + // Connection signals + void connected(); + void disconnected(); + void reconnecting(int attempt); + void connectionError(const QString& error); + void connectionFailed(const QString& reason); + + // 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 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 diff --git a/src/LoginDialog.cpp b/src/LoginDialog.cpp index 3a13596..a9a429a 100644 --- a/src/LoginDialog.cpp +++ b/src/LoginDialog.cpp @@ -1,84 +1,87 @@ #include "LoginDialog.hpp" -namespace Echoion::Desktop { +namespace Echoion::Desktop +{ -LoginDialog::LoginDialog(QWidget* parent) : QDialog(parent) { - setupUi(); - setWindowTitle("Echoion - Admin Login"); - setModal(true); - setFixedSize(350, 200); -} + LoginDialog::LoginDialog(QWidget* parent) : QDialog(parent) + { + setupUi(); + setWindowTitle("Echoion - Admin Login"); + setModal(true); + setFixedSize(350, 200); + } -void LoginDialog::setupUi() { - auto* mainLayout = new QVBoxLayout(this); + void LoginDialog::setupUi() + { + auto* mainLayout = new QVBoxLayout(this); - auto* titleLabel = new QLabel("Echoion Music Bot - Admin Login", this); - titleLabel->setAlignment(Qt::AlignCenter); - QFont titleFont = titleLabel->font(); - titleFont.setPointSize(14); - titleFont.setBold(true); - titleLabel->setFont(titleFont); - mainLayout->addWidget(titleLabel); + auto* titleLabel = new QLabel("Echoion Music Bot - Admin Login", this); + titleLabel->setAlignment(Qt::AlignCenter); + QFont titleFont = titleLabel->font(); + titleFont.setPointSize(14); + titleFont.setBold(true); + titleLabel->setFont(titleFont); + mainLayout->addWidget(titleLabel); - mainLayout->addSpacing(20); + mainLayout->addSpacing(20); - auto* usernameLayout = new QHBoxLayout(); - auto* usernameLabel = new QLabel("Username:", this); - usernameLabel->setFixedWidth(80); - usernameEdit_ = new QLineEdit(this); - usernameEdit_->setPlaceholderText("Enter username"); - usernameLayout->addWidget(usernameLabel); - usernameLayout->addWidget(usernameEdit_); - mainLayout->addLayout(usernameLayout); + auto* usernameLayout = new QHBoxLayout(); + auto* usernameLabel = new QLabel("Username:", this); + usernameLabel->setFixedWidth(80); + usernameEdit_ = new QLineEdit(this); + usernameEdit_->setPlaceholderText("Enter username"); + usernameLayout->addWidget(usernameLabel); + usernameLayout->addWidget(usernameEdit_); + mainLayout->addLayout(usernameLayout); - auto* passwordLayout = new QHBoxLayout(); - auto* passwordLabel = new QLabel("Password:", this); - passwordLabel->setFixedWidth(80); - passwordEdit_ = new QLineEdit(this); - passwordEdit_->setEchoMode(QLineEdit::Password); - passwordEdit_->setPlaceholderText("Enter password"); - passwordLayout->addWidget(passwordLabel); - passwordLayout->addWidget(passwordEdit_); - mainLayout->addLayout(passwordLayout); + auto* passwordLayout = new QHBoxLayout(); + auto* passwordLabel = new QLabel("Password:", this); + passwordLabel->setFixedWidth(80); + passwordEdit_ = new QLineEdit(this); + passwordEdit_->setEchoMode(QLineEdit::Password); + passwordEdit_->setPlaceholderText("Enter password"); + passwordLayout->addWidget(passwordLabel); + passwordLayout->addWidget(passwordEdit_); + mainLayout->addLayout(passwordLayout); - mainLayout->addSpacing(20); + mainLayout->addSpacing(20); - auto* buttonLayout = new QHBoxLayout(); - loginButton_ = new QPushButton("Login", this); - loginButton_->setDefault(true); - cancelButton_ = new QPushButton("Cancel", this); - buttonLayout->addStretch(); - buttonLayout->addWidget(loginButton_); - buttonLayout->addWidget(cancelButton_); - mainLayout->addLayout(buttonLayout); + auto* buttonLayout = new QHBoxLayout(); + loginButton_ = new QPushButton("Login", this); + loginButton_->setDefault(true); + cancelButton_ = new QPushButton("Cancel", this); + buttonLayout->addStretch(); + buttonLayout->addWidget(loginButton_); + buttonLayout->addWidget(cancelButton_); + mainLayout->addLayout(buttonLayout); - connect(loginButton_, &QPushButton::clicked, this, &LoginDialog::onLoginClicked); - connect(cancelButton_, &QPushButton::clicked, this, &LoginDialog::onCancelClicked); - connect(passwordEdit_, &QLineEdit::returnPressed, this, &LoginDialog::onLoginClicked); -} + connect(loginButton_, &QPushButton::clicked, this, + &LoginDialog::onLoginClicked); + connect(cancelButton_, &QPushButton::clicked, this, + &LoginDialog::onCancelClicked); + connect(passwordEdit_, &QLineEdit::returnPressed, this, + &LoginDialog::onLoginClicked); + } -QString LoginDialog::getUsername() const { - return usernameEdit_->text(); -} + QString LoginDialog::getUsername() const { return usernameEdit_->text(); } -QString LoginDialog::getPassword() const { - return passwordEdit_->text(); -} + QString LoginDialog::getPassword() const { return passwordEdit_->text(); } -void LoginDialog::onLoginClicked() { - if (usernameEdit_->text().isEmpty()) { - QMessageBox::warning(this, "Login Error", "Please enter a username."); - return; - } - if (passwordEdit_->text().isEmpty()) { - QMessageBox::warning(this, "Login Error", "Please enter a password."); - return; - } - accept(); -} + void LoginDialog::onLoginClicked() + { + if (usernameEdit_->text().isEmpty()) { + QMessageBox::warning(this, "Login Error", + "Please enter a username."); + return; + } + if (passwordEdit_->text().isEmpty()) { + QMessageBox::warning(this, "Login Error", + "Please enter a password."); + return; + } + accept(); + } -void LoginDialog::onCancelClicked() { - reject(); -} + void LoginDialog::onCancelClicked() { reject(); } } // namespace Echoion::Desktop diff --git a/src/LoginDialog.hpp b/src/LoginDialog.hpp index 31769d7..56aff1b 100644 --- a/src/LoginDialog.hpp +++ b/src/LoginDialog.hpp @@ -1,35 +1,39 @@ #pragma once #include -#include -#include -#include -#include #include +#include +#include #include +#include +#include -namespace Echoion::Desktop { +namespace Echoion::Desktop +{ -class LoginDialog : public QDialog { - Q_OBJECT + class LoginDialog : public QDialog + { + Q_OBJECT -public: - explicit LoginDialog(QWidget* parent = nullptr); + public: - [[nodiscard]] QString getUsername() const; - [[nodiscard]] QString getPassword() const; + explicit LoginDialog(QWidget* parent = nullptr); -private slots: - void onLoginClicked(); - void onCancelClicked(); + [[nodiscard]] QString getUsername() const; + [[nodiscard]] QString getPassword() const; -private: - void setupUi(); + private slots: + void onLoginClicked(); + void onCancelClicked(); - QLineEdit* usernameEdit_; - QLineEdit* passwordEdit_; - QPushButton* loginButton_; - QPushButton* cancelButton_; -}; + private: + + void setupUi(); + + QLineEdit* usernameEdit_; + QLineEdit* passwordEdit_; + QPushButton* loginButton_; + QPushButton* cancelButton_; + }; } // namespace Echoion::Desktop diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp deleted file mode 100644 index 6a2ba42..0000000 --- a/src/MainWindow.cpp +++ /dev/null @@ -1,419 +0,0 @@ -#include "MainWindow.hpp" -#include - -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& 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(totalMs / 1000)); - progressBar_->setValue(static_cast(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(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 diff --git a/src/MainWindow.hpp b/src/MainWindow.hpp index 0b4d80a..4b33110 100644 --- a/src/MainWindow.hpp +++ b/src/MainWindow.hpp @@ -1,155 +1,73 @@ #pragma once -#include -#include -#include -#include -#include +#include "CoreClient.hpp" +#include #include -#include -#include #include -#include -#include +#include +#include #include -#include -#include -#include -#include -#include -#include +#include +#include -namespace Echoion::Desktop { +namespace Echoion::Desktop +{ -class MainWindow : public QMainWindow { - Q_OBJECT + class MainWindow : public QMainWindow + { + Q_OBJECT -public: - explicit MainWindow(QWidget* parent = nullptr); - ~MainWindow() override; + public: - // Authentication - void setAuthToken(const QString& token); - void clearAuthToken(); - [[nodiscard]] bool isAuthenticated() const; + explicit MainWindow(CoreClient* client, QWidget* parent = nullptr); + ~MainWindow() override; - // State updates - void onPlaybackStateChanged(const Api::PlaybackState& state); - void onQueueUpdated(const std::vector& queue); - void onConnectionStatusChanged(bool connected); - void onSearchResultsReceived(const Api::SearchResult& results); + private slots: -signals: - // Connection signals - void loginRequested(); - void logoutRequested(); - - // Playback control signals - void playRequested(const QString& query); - void playFromQueueRequested(int index); - void pauseRequested(); - void stopRequested(); - void resumeRequested(); - void skipRequested(); - void seekRequested(int positionMs); - 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(); + void onConnectClicked(); + void onAuthClicked(); + void onConnected(); + void onDisconnected(); + void onAuthTokenRequested(); + void onAuthenticated(); + void onAuthFailed(const QString& reason); + void onEventReceived(const QString& event, const QJsonObject& data); + void updateConnectionStatus(); + void updatePlaybackInfo(const QJsonObject& data); + void onPlayClicked(); + void onPauseClicked(); + void onSkipClicked(); -private slots: - 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: -private: - void setupUi(); - void setupMenuBar(); - void setupPlaybackControls(); - void setupSearchPanel(); - void setupQueueView(); - void setupStatusBar(); - void updatePlaybackDisplay(); - void updateQueueDisplay(); - void updateButtonStates(); - - [[nodiscard]] QString formatDuration(std::chrono::milliseconds ms); + void setupUI(); + void setupConnections(); - // Central widget - QWidget* centralWidget_; - QVBoxLayout* mainLayout_; + CoreClient* client_ = nullptr; - // Playback controls - QLabel* nowPlayingLabel_; - QLabel* artistLabel_; - QProgressBar* progressBar_; - QLabel* timeLabel_; - QPushButton* playButton_; - QPushButton* pauseButton_; - QPushButton* stopButton_; - QPushButton* skipButton_; - QPushButton* shuffleButton_; - QPushButton* repeatButton_; - QSlider* volumeSlider_; - QLabel* volumeLabel_; + // Connection section + QLineEdit* hostEdit_ = nullptr; + QLineEdit* portEdit_ = nullptr; + QPushButton* connectBtn_ = nullptr; + QLabel* connectionStatus_ = nullptr; - // Search panel - QLineEdit* searchEdit_; - QPushButton* searchButton_; - QListWidget* searchResults_; + // Auth section + QLineEdit* nicknameEdit_ = nullptr; + QLineEdit* tokenEdit_ = nullptr; + QPushButton* requestTokenBtn_ = nullptr; + QPushButton* authBtn_ = nullptr; + QLabel* authStatus_ = nullptr; - // Queue view - QListWidget* queueList_; - QPushButton* clearQueueButton_; - QPushButton* removeFromQueueButton_; + // Playback section + QLabel* currentTrackLabel_ = nullptr; + QLabel* artistLabel_ = nullptr; + QLabel* statusLabel_ = nullptr; + QPushButton* playBtn_ = nullptr; + QPushButton* pauseBtn_ = nullptr; + QPushButton* skipBtn_ = nullptr; - // Status bar - QStatusBar* statusBar_; - QLabel* connectionStatusLabel_; - QLabel* authStatusLabel_; - - // Menu actions - QAction* loginAction_; - QAction* logoutAction_; - QAction* settingsAction_; - QAction* reloadAction_; - QAction* exitAction_; - QAction* aboutAction_; - - // State - QTimer* updateTimer_; - std::optional authToken_; - Api::PlaybackState currentState_; - std::vector currentQueue_; - bool connectedToCore_ = false; - - // Buttons for login/logout - QPushButton* loginLogoutButton_; -}; + // Status bar + QStatusBar* statusBar_ = nullptr; + }; } // namespace Echoion::Desktop diff --git a/src/main.cpp b/src/main.cpp index 5853176..f2970d6 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,78 +1,299 @@ -#include -#include -#include "MainWindow.hpp" -#include "LoginDialog.hpp" #include "CoreClient.hpp" -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include using namespace Echoion::Desktop; -int main(int argc, char* argv[]) { - QApplication app(argc, argv); - - app.setApplicationName("Echoion Desktop"); - app.setOrganizationName("Echoion"); +class SimpleMainWindow : public QMainWindow +{ + Q_OBJECT - MainWindow mainWindow; - CoreClient coreClient; + public: - // Connect to Core RPC server - coreClient.connectToCore("localhost", 8765); + SimpleMainWindow(CoreClient* client, QWidget* parent = nullptr) + : QMainWindow(parent), client_(client) + { + setupUI(); + setupConnections(); + updateConnectionStatus(); + } - QObject::connect(&mainWindow, &MainWindow::loginRequested, [&]() { - LoginDialog loginDialog(&mainWindow); - if (loginDialog.exec() == QDialog::Accepted) { - QString username = loginDialog.getUsername(); - QString password = loginDialog.getPassword(); - - coreClient.authenticate(username, password); - } - }); + private slots: - QObject::connect(&mainWindow, &MainWindow::logoutRequested, [&]() { - coreClient.logout(); - mainWindow.clearAuthToken(); - }); + void onConnectClicked() + { + QString host = hostEdit->text(); + if (host.isEmpty()) { + host = "localhost"; + } - QObject::connect(&coreClient, &CoreClient::authenticationSuccess, - [&](const QString& token) { - mainWindow.setAuthToken(token); - QMessageBox::information(&mainWindow, "Login Successful", - "You are now logged in as admin."); - }); + int port = portEdit->text().toInt(); + if (port <= 0) { + port = 8765; + } - QObject::connect(&coreClient, &CoreClient::authenticationFailed, - [&](const QString& error) { - QMessageBox::warning(&mainWindow, "Login Failed", error); - }); + statusBar()->showMessage( + QString("Connecting to %1:%2...").arg(host).arg(port)); + client_->connectToHost(host, port); + } - QObject::connect(&coreClient, &CoreClient::playbackStateReceived, - [&](const Echoion::Api::PlaybackState& state) { - mainWindow.onPlaybackStateChanged(state); - }); + void onRequestTokenClicked() + { + QString nickname = nicknameEdit->text(); + if (nickname.isEmpty()) { + QMessageBox::warning(this, "Error", + "Please enter your nickname"); + return; + } + client_->requestAuthToken(nickname); + } - QObject::connect(&coreClient, &CoreClient::queueReceived, - [&](const std::vector& queue) { - mainWindow.onQueueUpdated(queue); - }); + void onAuthClicked() + { + QString token = tokenEdit->text(); + if (token.isEmpty()) { + QMessageBox::warning(this, "Error", "Please enter the token"); + return; + } + client_->authenticate(token); + } - QObject::connect(&coreClient, &CoreClient::connected, - [&]() { - mainWindow.onConnectionStatusChanged(true); - }); + void onConnected() + { + statusBar()->showMessage("Connected"); + updateConnectionStatus(); + } - QObject::connect(&coreClient, &CoreClient::disconnected, - [&]() { - mainWindow.onConnectionStatusChanged(false); - }); + void onDisconnected() + { + statusBar()->showMessage("Disconnected"); + updateConnectionStatus(); + } - QObject::connect(&coreClient, &CoreClient::errorOccurred, - [&](const QString& error) { - QMessageBox::critical(&mainWindow, "Error", error); - }); + void onAuthTokenRequested() + { + QMessageBox::information( + this, "Token Requested", + "Please check your TeamSpeak PM for the authentication token."); + authStatus->setText("Token requested - check PM"); + authStatus->setStyleSheet("color: orange;"); + } - 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" diff --git a/src/storage/SecureStorage.cpp b/src/storage/SecureStorage.cpp new file mode 100644 index 0000000..191309f --- /dev/null +++ b/src/storage/SecureStorage.cpp @@ -0,0 +1,216 @@ +#include "storage/SecureStorage.hpp" +#include +#include +#include +#include +#include +#include + +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(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 diff --git a/src/storage/SecureStorage.hpp b/src/storage/SecureStorage.hpp new file mode 100644 index 0000000..aca1a9f --- /dev/null +++ b/src/storage/SecureStorage.hpp @@ -0,0 +1,53 @@ +#pragma once + +#include +#include +#include +#include +#include + +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 diff --git a/src/storage/SettingsManager.cpp b/src/storage/SettingsManager.cpp new file mode 100644 index 0000000..40c2276 --- /dev/null +++ b/src/storage/SettingsManager.cpp @@ -0,0 +1,294 @@ +#include "storage/SecureStorage.hpp" +#include "storage/SettingsManager.hpp" +#include + +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 SettingsManager::profiles() const + { + return settings_.profiles; + } + + std::optional + SettingsManager::getProfile(const QString& name) const + { + for (const auto& profile : settings_.profiles) { + if (profile.name == name) { + return profile; + } + } + return std::nullopt; + } + + std::optional 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 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 diff --git a/src/storage/SettingsManager.hpp b/src/storage/SettingsManager.hpp new file mode 100644 index 0000000..fac42d5 --- /dev/null +++ b/src/storage/SettingsManager.hpp @@ -0,0 +1,153 @@ +#pragma once + +#include +#include +#include +#include +#include + +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 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 profiles() const; + std::optional + getProfile(const QString& name) const; + std::optional getDefaultProfile() const; + void setDefaultProfile(const QString& name); + + // Token management + void saveToken(const QString& host, int port, + const QString& nickname, const QString& token); + std::optional 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 tokens_; + }; + +} // namespace Echoion::Desktop