Compare commits
10
Commits
6238a79854
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bae23b7abc | ||
|
|
88cfb1d443 | ||
|
|
8ef805debd | ||
|
|
2956ef29e9 | ||
|
|
1fc5aaecfe | ||
|
|
2aa44fae9e | ||
|
|
6e789fd83f | ||
|
|
bf1cd8e08d | ||
|
|
bcf4f4770a | ||
|
|
e646080683 |
No files matched your search
@@ -0,0 +1,55 @@
|
|||||||
|
name: Independent component release
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: [v*]
|
||||||
|
schedule:
|
||||||
|
- cron: '17 2 * * *'
|
||||||
|
workflow_dispatch:
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: echoion-release-serial
|
||||||
|
steps:
|
||||||
|
- name: Check out component
|
||||||
|
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
persist-credentials: false
|
||||||
|
- name: Check out pinned public release tools
|
||||||
|
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||||
|
with:
|
||||||
|
repository: Void/Echoion
|
||||||
|
ref: ${{ vars.ECHOION_RELEASE_TOOLS_REF }}
|
||||||
|
path: .echoion-release-tools
|
||||||
|
fetch-depth: 0
|
||||||
|
persist-credentials: false
|
||||||
|
- name: Build, publish, and merge feed transaction
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
AWS_ACCESS_KEY_ID: ${{ secrets.COMPONENT_OBJECT_STORAGE_ACCESS_KEY }}
|
||||||
|
AWS_SECRET_ACCESS_KEY: ${{ secrets.COMPONENT_OBJECT_STORAGE_SECRET_KEY }}
|
||||||
|
AWS_DEFAULT_REGION: ${{ vars.COMPONENT_OBJECT_STORAGE_REGION }}
|
||||||
|
ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
|
||||||
|
ECHOION_DISTRIBUTION_BACKEND: ${{ vars.ECHOION_DISTRIBUTION_BACKEND }}
|
||||||
|
ECHOION_DISTRIBUTION_BASE_URL: ${{ vars.ECHOION_DISTRIBUTION_BASE_URL }}
|
||||||
|
ECHOION_FEED_BASE_URL: ${{ vars.ECHOION_FEED_BASE_URL }}
|
||||||
|
ECHOION_FEED_COMMIT_SIGNING_KEY: ${{ secrets.RELEASE_FEED_GIT_SIGNING_KEY }}
|
||||||
|
ECHOION_FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }}
|
||||||
|
ECHOION_FEED_REPOSITORY: ssh://gitea@git.faumaray.ru/Void/Echoion.git
|
||||||
|
ECHOION_FEED_SIGNING_KEY_ID: ${{ vars.ECHOION_FEED_SIGNING_KEY_ID }}
|
||||||
|
ECHOION_OBJECT_STORAGE_BUCKET: ${{ vars.COMPONENT_OBJECT_STORAGE_BUCKET }}
|
||||||
|
ECHOION_OBJECT_STORAGE_ENDPOINT: ${{ vars.COMPONENT_OBJECT_STORAGE_ENDPOINT }}
|
||||||
|
ECHOION_OBJECT_STORAGE_PREFIX: ${{ vars.COMPONENT_OBJECT_STORAGE_PREFIX }}
|
||||||
|
ECHOION_RELEASE_TAG_ALLOWED_SIGNERS: ${{ secrets.RELEASE_TAG_ALLOWED_SIGNERS }}
|
||||||
|
GITEA_API_URL: ${{ gitea.api_url }}
|
||||||
|
GITEA_EVENT_NAME: ${{ gitea.event_name }}
|
||||||
|
GITEA_REF_NAME: ${{ gitea.ref_name }}
|
||||||
|
GITEA_RUN_NUMBER: ${{ gitea.run_number }}
|
||||||
|
GITEA_SHA: ${{ gitea.sha }}
|
||||||
|
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||||
|
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||||
|
RELEASE_TOOLS_REF: ${{ vars.ECHOION_RELEASE_TOOLS_REF }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
[[ "$RELEASE_TOOLS_REF" =~ ^[0-9a-f]{40}$ ]]
|
||||||
|
test "$(git -C .echoion-release-tools rev-parse HEAD)" = "$RELEASE_TOOLS_REF"
|
||||||
|
.echoion-release-tools/scripts/release-component.sh component.release.json
|
||||||
+44
-21
@@ -1,5 +1,33 @@
|
|||||||
cmake_minimum_required(VERSION 3.28)
|
cmake_minimum_required(VERSION 4.0.0)
|
||||||
project(EchoionDesktop VERSION 1.0.0 LANGUAGES CXX)
|
if(NOT DEFINED ECHOION_PRODUCT_VERSION)
|
||||||
|
set(ECHOION_PRODUCT_VERSION 0.0.0)
|
||||||
|
endif()
|
||||||
|
if(NOT DEFINED ECHOION_COMPONENT_VERSION)
|
||||||
|
set(ECHOION_COMPONENT_VERSION "${ECHOION_PRODUCT_VERSION}")
|
||||||
|
endif()
|
||||||
|
project(EchoionDesktop VERSION "${ECHOION_COMPONENT_VERSION}" LANGUAGES CXX)
|
||||||
|
|
||||||
|
if(PROJECT_IS_TOP_LEVEL)
|
||||||
|
file(DOWNLOAD
|
||||||
|
https://github.com/cpm-cmake/CPM.cmake/releases/download/v0.40.8/CPM.cmake
|
||||||
|
"${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake"
|
||||||
|
EXPECTED_HASH
|
||||||
|
SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791)
|
||||||
|
include("${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake")
|
||||||
|
CPMAddPackage(
|
||||||
|
NAME Void
|
||||||
|
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidlibrary.git
|
||||||
|
GIT_TAG main
|
||||||
|
OPTIONS "VOID_ENABLE_TESTING OFF")
|
||||||
|
CPMAddPackage(
|
||||||
|
NAME EchoionApi
|
||||||
|
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/echoionapi.git
|
||||||
|
GIT_TAG main)
|
||||||
|
CPMAddPackage(
|
||||||
|
NAME PackageProject.cmake
|
||||||
|
GITHUB_REPOSITORY TheLartians/PackageProject.cmake
|
||||||
|
VERSION 1.11.2)
|
||||||
|
endif()
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 26)
|
set(CMAKE_CXX_STANDARD 26)
|
||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
@@ -11,15 +39,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)
|
||||||
|
|
||||||
@@ -29,6 +53,7 @@ target_include_directories(EchoionDesktop PRIVATE
|
|||||||
|
|
||||||
target_link_libraries(EchoionDesktop PRIVATE
|
target_link_libraries(EchoionDesktop PRIVATE
|
||||||
Echoion::Api
|
Echoion::Api
|
||||||
|
Void::Security
|
||||||
Qt6::Core
|
Qt6::Core
|
||||||
Qt6::Widgets
|
Qt6::Widgets
|
||||||
Qt6::Network
|
Qt6::Network
|
||||||
@@ -48,15 +73,13 @@ set_target_properties(EchoionDesktop PROPERTIES
|
|||||||
MACOSX_BUNDLE TRUE
|
MACOSX_BUNDLE TRUE
|
||||||
)
|
)
|
||||||
|
|
||||||
include(GNUInstallDirs)
|
# PackageProject.cmake configuration
|
||||||
install(TARGETS EchoionDesktop
|
packageProject(
|
||||||
EXPORT EchoionDesktopTargets
|
NAME EchoionDesktop
|
||||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
VERSION ${PROJECT_VERSION}
|
||||||
BUNDLE DESTINATION ${CMAKE_INSTALL_BINDIR}
|
BINARY_DIR ${PROJECT_BINARY_DIR}
|
||||||
)
|
INCLUDE_DIR ${PROJECT_SOURCE_DIR}/src
|
||||||
|
INCLUDE_DESTINATION include
|
||||||
install(EXPORT EchoionDesktopTargets
|
COMPATIBILITY SameMajorVersion
|
||||||
FILE EchoionDesktopTargets.cmake
|
DISABLE_VERSION_SUFFIX YES
|
||||||
NAMESPACE Echoion::
|
|
||||||
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/EchoionDesktop
|
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"schemaVersion": 1,
|
||||||
|
"componentId": "EchoionDesktop",
|
||||||
|
"productCompatibility": ">=2.0.0 <3.0.0",
|
||||||
|
"publishNightly": true,
|
||||||
|
"cmakeOptions": {}
|
||||||
|
}
|
||||||
+528
-321
@@ -1,264 +1,455 @@
|
|||||||
#include "CoreClient.hpp"
|
#include "CoreClient.hpp"
|
||||||
#include <QJsonDocument>
|
|
||||||
#include <QJsonArray>
|
#include <QJsonArray>
|
||||||
|
#include <QJsonDocument>
|
||||||
#include <QTimer>
|
#include <QTimer>
|
||||||
#include <QUuid>
|
#include <QtEndian>
|
||||||
#include <iostream>
|
#include <algorithm>
|
||||||
|
|
||||||
namespace Echoion::Desktop {
|
namespace Echoion::Desktop
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
// The server double-encodes payloads: RpcResponse.result / .error and
|
||||||
|
// RpcNotification.data are JSON *strings*. Decode such a string value
|
||||||
|
// into its object/array form (pass-through if already structured).
|
||||||
|
QJsonValue decodeEmbedded(const QJsonValue& v)
|
||||||
|
{
|
||||||
|
if (!v.isString()) {
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
QJsonDocument d = QJsonDocument::fromJson(v.toString().toUtf8());
|
||||||
|
if (d.isObject()) {
|
||||||
|
return d.object();
|
||||||
|
}
|
||||||
|
if (d.isArray()) {
|
||||||
|
return d.array();
|
||||||
|
}
|
||||||
|
return QJsonValue();
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
CoreClient::CoreClient(QObject* parent)
|
CoreClient::CoreClient(QObject* parent)
|
||||||
: QObject(parent)
|
: QObject(parent),
|
||||||
, socket_(new QWebSocket(QString(), QWebSocketProtocol::VersionLatest, this)) {
|
socket_(new QWebSocket(QString(), QWebSocketProtocol::VersionLatest,
|
||||||
|
this)),
|
||||||
|
reconnectTimer_(new QTimer(this))
|
||||||
|
{
|
||||||
|
setupSocket();
|
||||||
|
|
||||||
connect(socket_, &QWebSocket::connected, this, &CoreClient::onConnected);
|
reconnectTimer_->setSingleShot(true);
|
||||||
connect(socket_, &QWebSocket::disconnected, this, &CoreClient::onDisconnected);
|
connect(reconnectTimer_, &QTimer::timeout, this,
|
||||||
connect(socket_, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
|
&CoreClient::onReconnectTimer);
|
||||||
this, &CoreClient::onError);
|
|
||||||
connect(socket_, &QWebSocket::textMessageReceived, this, &CoreClient::onMessageReceived);
|
|
||||||
connect(socket_, &QWebSocket::binaryMessageReceived, this, &CoreClient::onBinaryMessageReceived);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
CoreClient::~CoreClient() {
|
CoreClient::~CoreClient() { disconnectFromHost(); }
|
||||||
disconnectFromCore();
|
|
||||||
|
void CoreClient::setupSocket()
|
||||||
|
{
|
||||||
|
connect(socket_, &QWebSocket::connected, this,
|
||||||
|
&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);
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::connectToCore(const QString& host, int port) {
|
void CoreClient::loadSettings() { settingsManager_.load(); }
|
||||||
QString url = QString("ws://%1:%2/rpc").arg(host).arg(port);
|
|
||||||
|
void CoreClient::saveSettings() { settingsManager_.save(); }
|
||||||
|
|
||||||
|
void CoreClient::enableAutoConnect(bool enabled)
|
||||||
|
{
|
||||||
|
autoConnectEnabled_ = enabled;
|
||||||
|
settingsManager_.settings().autoConnect = enabled;
|
||||||
|
settingsManager_.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CoreClient::autoConnectEnabled() const { return autoConnectEnabled_; }
|
||||||
|
|
||||||
|
void CoreClient::startAutoConnect()
|
||||||
|
{
|
||||||
|
if (!autoConnectEnabled_) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto profile = settingsManager_.getDefaultProfile();
|
||||||
|
if (profile) {
|
||||||
|
currentHost_ = profile->host;
|
||||||
|
currentPort_ = profile->port;
|
||||||
|
currentNickname_ = profile->nickname;
|
||||||
|
|
||||||
|
emit reconnecting(0);
|
||||||
|
connectToHost(profile->host, profile->port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void CoreClient::connectToHost(const QString& host, int port)
|
||||||
|
{
|
||||||
|
currentHost_ = host;
|
||||||
|
currentPort_ = port;
|
||||||
|
|
||||||
|
// Reset reconnection attempts for manual connection
|
||||||
|
reconnectAttempts_ = 0;
|
||||||
|
stopReconnectTimer();
|
||||||
|
|
||||||
|
QString url = QString("ws://%1:%2").arg(host).arg(port);
|
||||||
|
qDebug() << "Connecting to:" << url;
|
||||||
socket_->open(QUrl(url));
|
socket_->open(QUrl(url));
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::disconnectFromCore() {
|
void CoreClient::disconnectFromHost()
|
||||||
shouldReconnect_ = false;
|
{
|
||||||
if (socket_->state() != QAbstractSocket::UnconnectedState) {
|
stopReconnectTimer();
|
||||||
|
cancelPendingRequests();
|
||||||
|
|
||||||
|
if (socket_ &&
|
||||||
|
socket_->state() != QAbstractSocket::UnconnectedState) {
|
||||||
socket_->close();
|
socket_->close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CoreClient::isConnected() const {
|
bool CoreClient::isConnected() const
|
||||||
return socket_->state() == QAbstractSocket::ConnectedState;
|
{
|
||||||
|
return socket_ &&
|
||||||
|
socket_->state() == QAbstractSocket::ConnectedState;
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::authenticate(const QString& username, const QString& password) {
|
void CoreClient::requestAuthToken(const QString& nickname)
|
||||||
QJsonObject params;
|
{
|
||||||
params["username"] = username;
|
currentNickname_ = nickname;
|
||||||
params["password"] = password;
|
|
||||||
|
|
||||||
sendRpcRequest("auth.login", params, [this](const QJsonObject& result) {
|
QJsonObject params;
|
||||||
|
params["nickname"] = nickname;
|
||||||
|
|
||||||
|
call("Authenticate", params, [this](const QJsonObject& result) {
|
||||||
if (result["success"].toBool()) {
|
if (result["success"].toBool()) {
|
||||||
authToken_ = result["token"].toString();
|
emit authTokenRequested();
|
||||||
emit authenticationSuccess(authToken_);
|
|
||||||
} else {
|
} else {
|
||||||
emit authenticationFailed(result["error"].toString("Unknown error"));
|
emit authFailed(result["message"].toString("Unknown error"));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::logout() {
|
void CoreClient::authenticate(const QString& token)
|
||||||
sendRpcRequest("auth.logout");
|
{
|
||||||
|
authToken_ = token;
|
||||||
|
|
||||||
|
QJsonObject params;
|
||||||
|
params["token"] = token;
|
||||||
|
|
||||||
|
call("Authenticate", params, [this](const QJsonObject& result) {
|
||||||
|
if (result["success"].toBool()) {
|
||||||
|
isAuthenticated_ = true;
|
||||||
|
emit authenticated();
|
||||||
|
|
||||||
|
// 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::logout()
|
||||||
|
{
|
||||||
|
call("Logout");
|
||||||
|
|
||||||
|
isAuthenticated_ = false;
|
||||||
authToken_.clear();
|
authToken_.clear();
|
||||||
emit loggedOut();
|
emit loggedOut();
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CoreClient::isAuthenticated() const {
|
bool CoreClient::isAuthenticated() const { return isAuthenticated_; }
|
||||||
return !authToken_.isEmpty();
|
|
||||||
|
void CoreClient::clearCachedToken()
|
||||||
|
{
|
||||||
|
if (!currentHost_.isEmpty()) {
|
||||||
|
settingsManager_.deleteToken(currentHost_, currentPort_);
|
||||||
|
}
|
||||||
|
logout();
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::play(const QString& query) {
|
void CoreClient::call(const QString& method, const QJsonObject& params)
|
||||||
QJsonObject params;
|
{
|
||||||
params["query"] = query;
|
call(method, params, nullptr);
|
||||||
sendRpcRequest("playback.play", params);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::pause() {
|
int CoreClient::methodToInt(const QString& method) const
|
||||||
sendRpcRequest("playback.pause");
|
{
|
||||||
|
// 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},
|
||||||
|
{"ToggleShuffle", 60},
|
||||||
|
{"ToggleRepeat", 61},
|
||||||
|
{"ShuffleQueue", 62}};
|
||||||
|
|
||||||
|
// Values above are only used to reject locally-unknown methods; the wire
|
||||||
|
// contract is the method NAME (Core decodes RpcMethod by name).
|
||||||
|
return methodMap.value(method, -1);
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::resume() {
|
void CoreClient::call(const QString& method, const QJsonObject& params,
|
||||||
sendRpcRequest("playback.resume");
|
RpcCallback callback)
|
||||||
|
{
|
||||||
|
if (!isConnected()) {
|
||||||
|
if (callback) {
|
||||||
|
QJsonObject error;
|
||||||
|
error["success"] = false;
|
||||||
|
error["message"] = "Not connected";
|
||||||
|
callback(error);
|
||||||
|
}
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::stop() {
|
int methodInt = methodToInt(method);
|
||||||
sendRpcRequest("playback.stop");
|
if (methodInt < 0) {
|
||||||
|
if (callback) {
|
||||||
|
QJsonObject error;
|
||||||
|
error["success"] = false;
|
||||||
|
error["message"] = "Unknown method: " + method;
|
||||||
|
callback(error);
|
||||||
|
}
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::skip(int count) {
|
quint64 requestId = nextRequestId_++;
|
||||||
QJsonObject params;
|
|
||||||
params["count"] = count;
|
QJsonObject request;
|
||||||
sendRpcRequest("playback.skip", params);
|
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;
|
||||||
|
// RpcRequest.params is a JSON-encoded STRING on the server (handlers
|
||||||
|
// re-parse it via Void::Json::parse). Reflection rejects an object for a
|
||||||
|
// string field, so the params object must be serialized to a string
|
||||||
|
// here — otherwise the whole request fails to decode.
|
||||||
|
request["params"] = QString::fromUtf8(
|
||||||
|
QJsonDocument(params).toJson(QJsonDocument::Compact));
|
||||||
|
|
||||||
|
if (!authToken_.isEmpty()) {
|
||||||
|
request["authToken"] = authToken_;
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::seek(int positionMs) {
|
if (callback) {
|
||||||
QJsonObject params;
|
PendingRequest pending;
|
||||||
params["position"] = positionMs;
|
pending.method = method;
|
||||||
sendRpcRequest("playback.seek", params);
|
pending.params = params;
|
||||||
|
pending.callback = callback;
|
||||||
|
pending.retryCount = 0;
|
||||||
|
pendingRequests_[requestId] = std::move(pending);
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::setVolume(int volume) {
|
QJsonDocument doc(request);
|
||||||
QJsonObject params;
|
socket_->sendTextMessage(doc.toJson(QJsonDocument::Compact));
|
||||||
params["volume"] = qBound(0, volume, 100);
|
|
||||||
sendRpcRequest("playback.setVolume", params);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::queueTrack(const QString& query) {
|
void CoreClient::retryRequest(quint64 requestId)
|
||||||
QJsonObject params;
|
{
|
||||||
params["query"] = query;
|
auto it = pendingRequests_.find(requestId);
|
||||||
sendRpcRequest("queue.add", params, [this](const QJsonObject& result) {
|
if (it == pendingRequests_.end()) {
|
||||||
if (result["success"].toBool()) {
|
return;
|
||||||
auto track = parseTrackInfo(result["track"].toObject());
|
|
||||||
emit trackQueued(track, result["position"].toInt());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
auto& pending = it->second;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
pending.retryCount++;
|
||||||
|
|
||||||
|
// Owned, cancellable retry timer. A fire-and-forget QTimer::singleShot
|
||||||
|
// would still fire after a disconnect and resend on a dead/reconnected
|
||||||
|
// socket; cancelPendingRequests() stops these on teardown.
|
||||||
|
auto* timer = new QTimer(this);
|
||||||
|
timer->setSingleShot(true);
|
||||||
|
pending.retryTimer = timer;
|
||||||
|
const int delay = RETRY_DELAY_MS * pending.retryCount;
|
||||||
|
connect(timer, &QTimer::timeout, this, [this, requestId, timer]() {
|
||||||
|
timer->deleteLater();
|
||||||
|
|
||||||
|
auto it = pendingRequests_.find(requestId);
|
||||||
|
if (it == pendingRequests_.end()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
it->second.retryTimer = nullptr; // spent; don't touch in cancel
|
||||||
|
|
||||||
|
// The socket may have dropped between scheduling and firing. Never
|
||||||
|
// resend on a closed or reconnecting socket.
|
||||||
|
if (!socket_ ||
|
||||||
|
socket_->state() != QAbstractSocket::ConnectedState) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto& pending = it->second;
|
||||||
|
|
||||||
|
quint64 newRequestId = nextRequestId_++;
|
||||||
|
|
||||||
|
QJsonObject request;
|
||||||
|
request["id"] = static_cast<qint64>(newRequestId);
|
||||||
|
request["method"] = pending.method;
|
||||||
|
// Same wire format as sendRequest: the server's
|
||||||
|
// RpcRequest.params is a JSON-encoded STRING; a raw object
|
||||||
|
// here made every retried request fail to decode.
|
||||||
|
request["params"] = QString::fromUtf8(
|
||||||
|
QJsonDocument(pending.params).toJson(QJsonDocument::Compact));
|
||||||
|
|
||||||
|
if (!authToken_.isEmpty()) {
|
||||||
|
request["authToken"] = authToken_;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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));
|
||||||
});
|
});
|
||||||
|
timer->start(delay);
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::removeFromQueue(int position) {
|
void CoreClient::cancelPendingRequests()
|
||||||
QJsonObject params;
|
{
|
||||||
params["position"] = position;
|
for (auto& [id, pending] : pendingRequests_) {
|
||||||
sendRpcRequest("queue.remove", params, [this, position](const QJsonObject& result) {
|
// Stop any scheduled retry so it can't fire after the connection
|
||||||
if (result["success"].toBool()) {
|
// is gone and resend on a stale socket.
|
||||||
emit trackRemoved(position);
|
if (pending.retryTimer) {
|
||||||
|
pending.retryTimer->stop();
|
||||||
|
pending.retryTimer->deleteLater();
|
||||||
|
pending.retryTimer = nullptr;
|
||||||
}
|
}
|
||||||
});
|
if (pending.callback) {
|
||||||
|
QJsonObject error;
|
||||||
|
error["success"] = false;
|
||||||
|
error["message"] = "Connection closed";
|
||||||
|
pending.callback(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pendingRequests_.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::clearQueue() {
|
void CoreClient::onSocketConnected()
|
||||||
sendRpcRequest("queue.clear");
|
{
|
||||||
}
|
qDebug() << "Socket connected successfully";
|
||||||
|
|
||||||
void CoreClient::moveInQueue(int from, int to) {
|
|
||||||
QJsonObject params;
|
|
||||||
params["from"] = from;
|
|
||||||
params["to"] = to;
|
|
||||||
sendRpcRequest("queue.move", params);
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::shuffle() {
|
|
||||||
sendRpcRequest("queue.shuffle");
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::toggleRepeat() {
|
|
||||||
sendRpcRequest("playback.toggleRepeat");
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::toggleShuffle() {
|
|
||||||
sendRpcRequest("playback.toggleShuffle");
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
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());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::savePlaylist(const QString& name, const QString& description) {
|
|
||||||
QJsonObject params;
|
|
||||||
params["name"] = name;
|
|
||||||
params["description"] = description;
|
|
||||||
sendRpcRequest("playlist.save", params);
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::getUserPlaylists() {
|
|
||||||
sendRpcRequest("playlist.list", {}, [this](const QJsonObject& result) {
|
|
||||||
std::vector<Echoion::Api::PlaylistInfo> 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);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::requestPlaybackState() {
|
|
||||||
sendRpcRequest("state.getPlayback", {}, [this](const QJsonObject& result) {
|
|
||||||
emit playbackStateReceived(parsePlaybackState(result));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::requestQueue() {
|
|
||||||
sendRpcRequest("queue.get", {}, [this](const QJsonObject& result) {
|
|
||||||
std::vector<Echoion::Api::QueueEntry> queue;
|
|
||||||
QJsonArray arr = result["queue"].toArray();
|
|
||||||
for (const auto& item : arr) {
|
|
||||||
queue.push_back(parseQueueEntry(item.toObject()));
|
|
||||||
}
|
|
||||||
emit queueReceived(queue);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::requestCurrentTrack() {
|
|
||||||
sendRpcRequest("state.getCurrentTrack", {}, [this](const QJsonObject& result) {
|
|
||||||
if (!result["track"].isNull()) {
|
|
||||||
emit trackStarted(parseTrackInfo(result["track"].toObject()));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::reloadCore() {
|
|
||||||
sendRpcRequest("system.reload");
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::onConnected() {
|
|
||||||
reconnectAttempts_ = 0;
|
reconnectAttempts_ = 0;
|
||||||
emit connected();
|
emit connected();
|
||||||
|
|
||||||
// Re-authenticate if we had a token
|
// Attempt auto-auth if enabled and we have a cached token
|
||||||
if (!authToken_.isEmpty()) {
|
if (autoAuthEnabled_ && !currentHost_.isEmpty()) {
|
||||||
QJsonObject params;
|
attemptAutoAuth();
|
||||||
params["token"] = authToken_;
|
}
|
||||||
sendRpcRequest("auth.validate", params);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start polling for state updates
|
void CoreClient::attemptAutoAuth()
|
||||||
requestPlaybackState();
|
{
|
||||||
requestQueue();
|
QString nickname;
|
||||||
|
auto token =
|
||||||
|
settingsManager_.loadToken(currentHost_, currentPort_, nickname);
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
currentNickname_ = nickname;
|
||||||
|
authenticate(*token);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::onDisconnected() {
|
void CoreClient::onSocketDisconnected()
|
||||||
|
{
|
||||||
|
qDebug() << "Socket disconnected";
|
||||||
|
isAuthenticated_ = false;
|
||||||
emit disconnected();
|
emit disconnected();
|
||||||
|
|
||||||
// Attempt reconnection
|
// Start reconnection if enabled
|
||||||
if (shouldReconnect_ && reconnectAttempts_ < MAX_RECONNECT_ATTEMPTS) {
|
if (autoConnectEnabled_ &&
|
||||||
|
reconnectAttempts_ < MAX_RECONNECT_ATTEMPTS) {
|
||||||
|
startReconnectTimer();
|
||||||
|
} else if (autoConnectEnabled_) {
|
||||||
|
// Attempts exhausted: hand control back to the user (the UI
|
||||||
|
// shows a manual Reconnect action).
|
||||||
|
emit reconnectExhausted();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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_++;
|
reconnectAttempts_++;
|
||||||
QTimer::singleShot(1000 * reconnectAttempts_, [this]() {
|
int delay =
|
||||||
connectToCore();
|
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::onError(QAbstractSocket::SocketError error) {
|
void CoreClient::onTextMessageReceived(const QString& message)
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
void CoreClient::onMessageReceived(const QString& message) {
|
|
||||||
QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
|
QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
|
||||||
if (doc.isNull() || !doc.isObject()) {
|
if (doc.isNull() || !doc.isObject()) {
|
||||||
return;
|
return;
|
||||||
@@ -266,174 +457,190 @@ void CoreClient::onMessageReceived(const QString& message) {
|
|||||||
|
|
||||||
QJsonObject obj = doc.object();
|
QJsonObject obj = doc.object();
|
||||||
|
|
||||||
// Check if it's a response or an event
|
if (obj.contains("event")) {
|
||||||
if (obj.contains("id")) {
|
|
||||||
handleRpcResponse(obj);
|
|
||||||
} else if (obj.contains("event")) {
|
|
||||||
handleEvent(obj);
|
handleEvent(obj);
|
||||||
|
} else if (obj.contains("requestId")) {
|
||||||
|
handleRpcResponse(obj);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::onBinaryMessageReceived(const QByteArray& data) {
|
void CoreClient::handleRpcResponse(const QJsonObject& response)
|
||||||
// Handle binary data if needed (e.g., album art)
|
{
|
||||||
}
|
quint64 requestId =
|
||||||
|
response["requestId"].toVariant().toULongLong();
|
||||||
|
|
||||||
void CoreClient::sendRpcRequest(const QString& method, const QJsonObject& params) {
|
auto it = pendingRequests_.find(requestId);
|
||||||
sendRpcRequest(method, params, nullptr);
|
if (it == pendingRequests_.end()) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
auto callback = std::move(it->second.callback);
|
||||||
void CoreClient::sendRpcRequest(const QString& method, const QJsonObject& params, RpcCallback callback) {
|
pendingRequests_.erase(it);
|
||||||
if (!isConnected()) {
|
if (!callback) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
QJsonObject request;
|
// Normalise into a flat object the callbacks can read directly:
|
||||||
QString id = QUuid::createUuid().toString();
|
// success (bool), data (decoded result payload), error, and a
|
||||||
|
// convenience message pulled from result/error.
|
||||||
|
const bool success = response["success"].toBool();
|
||||||
|
QJsonValue data = decodeEmbedded(response.value("result"));
|
||||||
|
QJsonValue error = decodeEmbedded(response.value("error"));
|
||||||
|
|
||||||
request["jsonrpc"] = "2.0";
|
QString message;
|
||||||
request["id"] = id;
|
if (data.isObject() && data.toObject().contains("message")) {
|
||||||
request["method"] = method;
|
message = data.toObject()["message"].toString();
|
||||||
request["params"] = params;
|
} else if (error.isObject() && error.toObject().contains("message")) {
|
||||||
|
message = error.toObject()["message"].toString();
|
||||||
if (!authToken_.isEmpty()) {
|
|
||||||
request["auth"] = authToken_;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (callback) {
|
QJsonObject cb;
|
||||||
pendingRequests_[id] = callback;
|
cb["success"] = success;
|
||||||
|
cb["data"] = data;
|
||||||
|
cb["error"] = error;
|
||||||
|
cb["message"] = message;
|
||||||
|
callback(cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
QJsonDocument doc(request);
|
void CoreClient::handleEvent(const QJsonObject& event)
|
||||||
socket_->sendTextMessage(QString::fromUtf8(doc.toJson(QJsonDocument::Compact)));
|
{
|
||||||
}
|
QString eventName = event["event"].toString();
|
||||||
|
QJsonObject data = decodeEmbedded(event.value("data")).toObject();
|
||||||
|
|
||||||
void CoreClient::handleRpcResponse(const QJsonObject& response) {
|
emit eventReceived(eventName, data);
|
||||||
QString id = response["id"].toString();
|
|
||||||
|
|
||||||
auto it = pendingRequests_.find(id);
|
// Emit specific signals for common events
|
||||||
if (it != pendingRequests_.end()) {
|
if (eventName == "playback.started") {
|
||||||
if (it->second) {
|
emit playbackStarted(data);
|
||||||
QJsonObject result = response.contains("result")
|
} else if (eventName == "playback.paused") {
|
||||||
? response["result"].toObject()
|
emit playbackPaused(data);
|
||||||
: QJsonObject();
|
} else if (eventName == "playback.resumed") {
|
||||||
if (response.contains("error")) {
|
emit playbackResumed(data);
|
||||||
result["error"] = response["error"];
|
} else if (eventName == "playback.stopped") {
|
||||||
result["success"] = false;
|
emit playbackStopped(data);
|
||||||
} else {
|
} else if (eventName == "playback.finished") {
|
||||||
result["success"] = true;
|
emit playbackFinished(data);
|
||||||
}
|
} else if (eventName == "playback.volumeChanged") {
|
||||||
it->second(result);
|
emit volumeChanged(data);
|
||||||
}
|
} else if (eventName.startsWith("queue.")) {
|
||||||
pendingRequests_.erase(it);
|
emit queueUpdated(data);
|
||||||
|
} else if (eventName.startsWith("playlist.")) {
|
||||||
|
emit playlistEvent(eventName, data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreClient::handleEvent(const QJsonObject& event) {
|
// Playback control methods
|
||||||
QString eventType = event["event"].toString();
|
void CoreClient::play(const QString& query)
|
||||||
QJsonObject data = event["data"].toObject();
|
{
|
||||||
|
QJsonObject params;
|
||||||
if (eventType == "playback.stateChanged") {
|
params["query"] = query;
|
||||||
emit playbackStateReceived(parsePlaybackState(data));
|
call("Play", params);
|
||||||
} 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) {
|
void CoreClient::pause() { call("Pause"); }
|
||||||
Echoion::Api::PlaybackState state;
|
void CoreClient::resume() { call("Resume"); }
|
||||||
|
void CoreClient::stop() { call("Stop"); }
|
||||||
|
|
||||||
state.isPlaying = obj["isPlaying"].toBool();
|
void CoreClient::skip(int count)
|
||||||
state.isPaused = obj["isPaused"].toBool();
|
{
|
||||||
state.volume = static_cast<float>(obj["volume"].toDouble(0.5));
|
QJsonObject params;
|
||||||
state.repeat = obj["repeat"].toBool();
|
params["count"] = count;
|
||||||
state.shuffle = obj["shuffle"].toBool();
|
call("Skip", params);
|
||||||
state.position = std::chrono::milliseconds(obj["position"].toInt());
|
|
||||||
|
|
||||||
if (!obj["currentTrack"].isNull()) {
|
|
||||||
state.currentTrack = parseQueueEntry(obj["currentTrack"].toObject());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return state;
|
void CoreClient::seek(int positionMs)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["position"] = positionMs;
|
||||||
|
call("Seek", params);
|
||||||
}
|
}
|
||||||
|
|
||||||
Echoion::Api::TrackInfo CoreClient::parseTrackInfo(const QJsonObject& obj) {
|
void CoreClient::setVolume(int volume)
|
||||||
Echoion::Api::TrackInfo track;
|
{
|
||||||
|
// UI uses 0-100; the server's volume model is normalised 0.0-1.0.
|
||||||
track.title = obj["title"].toString().toStdString();
|
QJsonObject params;
|
||||||
track.artist = obj["artist"].toString().toStdString();
|
params["volume"] = std::clamp(volume, 0, 100) / 100.0;
|
||||||
track.originalUrl = obj["originalUrl"].toString().toStdString();
|
call("SetVolume", params);
|
||||||
track.source = static_cast<Echoion::Api::TrackSource>(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;
|
// Queue management methods
|
||||||
|
void CoreClient::queueTrack(const QString& query)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["query"] = query;
|
||||||
|
call("QueueTrack", params);
|
||||||
}
|
}
|
||||||
|
|
||||||
Echoion::Api::QueueEntry CoreClient::parseQueueEntry(const QJsonObject& obj) {
|
void CoreClient::removeFromQueue(quint64 queueId)
|
||||||
Echoion::Api::QueueEntry entry;
|
{
|
||||||
|
QJsonObject params;
|
||||||
entry.queueId = static_cast<uint64_t>(obj["queueId"].toDouble());
|
params["queueId"] = static_cast<qint64>(queueId);
|
||||||
entry.track = parseTrackInfo(obj["track"].toObject());
|
call("RemoveFromQueue", params);
|
||||||
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;
|
void CoreClient::clearQueue() { call("ClearQueue"); }
|
||||||
|
|
||||||
|
void CoreClient::moveInQueue(quint64 queueId, int newPosition)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["queueId"] = static_cast<qint64>(queueId);
|
||||||
|
params["newPosition"] = newPosition;
|
||||||
|
call("MoveInQueue", params);
|
||||||
}
|
}
|
||||||
|
|
||||||
Echoion::Api::SearchResult CoreClient::parseSearchResult(const QJsonObject& obj) {
|
void CoreClient::shuffle() { call("ShuffleQueue"); }
|
||||||
Echoion::Api::SearchResult result;
|
void CoreClient::toggleRepeat() { call("ToggleRepeat"); }
|
||||||
|
void CoreClient::toggleShuffle() { call("ToggleShuffle"); }
|
||||||
|
|
||||||
result.query = obj["query"].toString().toStdString();
|
// Search
|
||||||
|
void CoreClient::search(const QString& query)
|
||||||
QJsonArray tracks = obj["tracks"].toArray();
|
{
|
||||||
for (const auto& item : tracks) {
|
QJsonObject params;
|
||||||
result.tracks.push_back(parseTrackInfo(item.toObject()));
|
params["query"] = query;
|
||||||
|
call("SearchTracks", params);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
// Playlist management
|
||||||
|
void CoreClient::loadPlaylist(const QString& playlistId)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["playlistId"] = playlistId;
|
||||||
|
call("LoadPlaylist", params);
|
||||||
}
|
}
|
||||||
|
|
||||||
QJsonObject CoreClient::trackInfoToJson(const Echoion::Api::TrackInfo& track) {
|
void CoreClient::savePlaylist(const QString& name,
|
||||||
QJsonObject obj;
|
const QString& description)
|
||||||
obj["title"] = QString::fromStdString(track.title);
|
{
|
||||||
obj["artist"] = QString::fromStdString(track.artist);
|
QJsonObject params;
|
||||||
obj["originalUrl"] = QString::fromStdString(track.originalUrl);
|
params["name"] = name;
|
||||||
obj["source"] = static_cast<int>(track.source);
|
params["description"] = description;
|
||||||
if (track.streamUrl) {
|
call("SavePlaylist", params);
|
||||||
obj["streamUrl"] = QString::fromStdString(*track.streamUrl);
|
|
||||||
}
|
}
|
||||||
if (track.thumbnailUrl) {
|
|
||||||
obj["thumbnailUrl"] = QString::fromStdString(*track.thumbnailUrl);
|
void CoreClient::deletePlaylist(const QString& playlistId)
|
||||||
|
{
|
||||||
|
QJsonObject params;
|
||||||
|
params["playlistId"] = playlistId;
|
||||||
|
call("DeletePlaylist", params);
|
||||||
}
|
}
|
||||||
if (track.duration) {
|
|
||||||
obj["duration"] = static_cast<int>(track.duration->count());
|
void CoreClient::getUserPlaylists() { call("GetPlaylists"); }
|
||||||
}
|
|
||||||
return obj;
|
// Configuration
|
||||||
|
void CoreClient::getConfig() { call("GetConfig"); }
|
||||||
|
|
||||||
|
void CoreClient::setConfig(const QString& configJson)
|
||||||
|
{
|
||||||
|
// configJson is the full config object; forwarded as the params payload.
|
||||||
|
QJsonObject params =
|
||||||
|
QJsonDocument::fromJson(configJson.toUtf8()).object();
|
||||||
|
call("SetConfig", params);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void CoreClient::reloadConfig() { call("ReloadConfig"); }
|
||||||
|
|
||||||
|
// Data requests
|
||||||
|
void CoreClient::requestPlaybackState() { call("GetStatus"); }
|
||||||
|
void CoreClient::requestQueue() { call("GetQueue"); }
|
||||||
|
void CoreClient::requestCurrentTrack() { call("GetCurrentTrack"); }
|
||||||
|
|
||||||
} // namespace Echoion::Desktop
|
} // namespace Echoion::Desktop
|
||||||
+108
-59
@@ -1,37 +1,56 @@
|
|||||||
#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 <QPointer>
|
||||||
#include <echoion/api.hpp>
|
#include <QTimer>
|
||||||
|
#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);
|
explicit CoreClient(QObject* parent = nullptr);
|
||||||
~CoreClient() override;
|
~CoreClient() override;
|
||||||
|
|
||||||
|
// Settings integration
|
||||||
|
void loadSettings();
|
||||||
|
void saveSettings();
|
||||||
|
SettingsManager* settingsManager() { return &settingsManager_; }
|
||||||
|
|
||||||
|
// Auto-connect on startup
|
||||||
|
void enableAutoConnect(bool enabled);
|
||||||
|
bool autoConnectEnabled() const;
|
||||||
|
void startAutoConnect();
|
||||||
|
|
||||||
// Connection management
|
// Connection management
|
||||||
void connectToCore(const QString& host = "localhost", int port = 8765);
|
void connectToHost(const QString& host, int port);
|
||||||
void disconnectFromCore();
|
void disconnectFromHost();
|
||||||
[[nodiscard]] bool isConnected() const;
|
[[nodiscard]] bool isConnected() const;
|
||||||
|
|
||||||
// Authentication
|
// Authentication with auto-auth support
|
||||||
void authenticate(const QString& username, const QString& password);
|
void requestAuthToken(const QString& nickname);
|
||||||
|
void authenticate(const QString& token);
|
||||||
void logout();
|
void logout();
|
||||||
[[nodiscard]] bool isAuthenticated() const;
|
[[nodiscard]] bool isAuthenticated() const;
|
||||||
|
void clearCachedToken();
|
||||||
|
|
||||||
|
// Generic RPC with automatic retry
|
||||||
|
void call(const QString& method, const QJsonObject& params = {});
|
||||||
|
void call(const QString& method, const QJsonObject& params,
|
||||||
|
RpcCallback callback);
|
||||||
|
|
||||||
// Playback control
|
// Playback control
|
||||||
void play(const QString& query);
|
void play(const QString& query);
|
||||||
@@ -40,13 +59,13 @@ public:
|
|||||||
void stop();
|
void stop();
|
||||||
void skip(int count = 1);
|
void skip(int count = 1);
|
||||||
void seek(int positionMs);
|
void seek(int positionMs);
|
||||||
void setVolume(int volume); // 0-100
|
void setVolume(int volume);
|
||||||
|
|
||||||
// Queue management
|
// Queue management (queueId matches GetQueue items + queue events)
|
||||||
void queueTrack(const QString& query);
|
void queueTrack(const QString& query);
|
||||||
void removeFromQueue(int position);
|
void removeFromQueue(quint64 queueId);
|
||||||
void clearQueue();
|
void clearQueue();
|
||||||
void moveInQueue(int from, int to);
|
void moveInQueue(quint64 queueId, int newPosition);
|
||||||
void shuffle();
|
void shuffle();
|
||||||
void toggleRepeat();
|
void toggleRepeat();
|
||||||
void toggleShuffle();
|
void toggleShuffle();
|
||||||
@@ -57,76 +76,106 @@ public:
|
|||||||
// Playlist management
|
// Playlist management
|
||||||
void loadPlaylist(const QString& playlistId);
|
void loadPlaylist(const QString& playlistId);
|
||||||
void savePlaylist(const QString& name, const QString& description);
|
void savePlaylist(const QString& name, const QString& description);
|
||||||
|
void deletePlaylist(const QString& playlistId);
|
||||||
void getUserPlaylists();
|
void getUserPlaylists();
|
||||||
|
|
||||||
// Data requests
|
// Configuration
|
||||||
|
void getConfig();
|
||||||
|
void setConfig(const QString& configJson);
|
||||||
|
void reloadConfig();
|
||||||
|
|
||||||
|
// Data requests (fetch on demand). Data-returning calls may also be
|
||||||
|
// issued via call(method, params, callback) for a one-shot reply.
|
||||||
void requestPlaybackState();
|
void requestPlaybackState();
|
||||||
void requestQueue();
|
void requestQueue();
|
||||||
void requestCurrentTrack();
|
void requestCurrentTrack();
|
||||||
|
|
||||||
// Hot reload
|
|
||||||
void reloadCore();
|
|
||||||
|
|
||||||
signals:
|
signals:
|
||||||
|
|
||||||
// Connection signals
|
// Connection signals
|
||||||
void connected();
|
void connected();
|
||||||
void disconnected();
|
void disconnected();
|
||||||
void errorOccurred(const QString& error);
|
void reconnecting(int attempt);
|
||||||
|
// All automatic reconnect attempts failed; manual retry needed.
|
||||||
|
void reconnectExhausted();
|
||||||
|
void connectionError(const QString& error);
|
||||||
|
void connectionFailed(const QString& reason);
|
||||||
|
|
||||||
// Authentication signals
|
// Authentication signals
|
||||||
void authenticationSuccess(const QString& token);
|
void authTokenRequested(); // Nickname accepted, check PM
|
||||||
void authenticationFailed(const QString& reason);
|
void authenticated();
|
||||||
|
void authFailed(const QString& reason);
|
||||||
void loggedOut();
|
void loggedOut();
|
||||||
|
void tokenSaved(const QString& host, int port);
|
||||||
|
|
||||||
// Playback signals
|
// All events from Core (raw JSON for flexibility)
|
||||||
void playbackStateReceived(const Echoion::Api::PlaybackState& state);
|
void eventReceived(const QString& event, const QJsonObject& data);
|
||||||
void trackStarted(const Echoion::Api::TrackInfo& track);
|
|
||||||
void trackFinished(const Echoion::Api::TrackInfo& track);
|
|
||||||
void playbackPaused();
|
|
||||||
void playbackResumed();
|
|
||||||
void volumeChanged(int volume);
|
|
||||||
|
|
||||||
// Queue signals
|
// Specific event signals
|
||||||
void queueReceived(const std::vector<Echoion::Api::QueueEntry>& queue);
|
void playbackStarted(const QJsonObject& data);
|
||||||
void trackQueued(const Echoion::Api::TrackInfo& track, int position);
|
void playbackPaused(const QJsonObject& data);
|
||||||
void trackRemoved(int position);
|
void playbackResumed(const QJsonObject& data);
|
||||||
|
void playbackStopped(const QJsonObject& data);
|
||||||
// Search signals
|
void playbackFinished(const QJsonObject& data);
|
||||||
void searchResultsReceived(const Echoion::Api::SearchResult& results);
|
void volumeChanged(const QJsonObject& data);
|
||||||
|
void trackChanged(const QJsonObject& data);
|
||||||
// Playlist signals
|
void queueUpdated(const QJsonObject& data);
|
||||||
void playlistsReceived(const std::vector<Echoion::Api::PlaylistInfo>& playlists);
|
void playlistEvent(const QString& event, const QJsonObject& data);
|
||||||
void playlistLoaded(const QString& playlistId, int trackCount);
|
|
||||||
|
|
||||||
private slots:
|
private slots:
|
||||||
void onConnected();
|
|
||||||
void onDisconnected();
|
void onSocketConnected();
|
||||||
void onError(QAbstractSocket::SocketError error);
|
void onSocketDisconnected();
|
||||||
void onMessageReceived(const QString& message);
|
void onSocketError(QAbstractSocket::SocketError error);
|
||||||
void onBinaryMessageReceived(const QByteArray& data);
|
void onTextMessageReceived(const QString& message);
|
||||||
|
void onReconnectTimer();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void sendRpcRequest(const QString& method, const QJsonObject& params = {});
|
|
||||||
void sendRpcRequest(const QString& method, const QJsonObject& params, RpcCallback callback);
|
void setupSocket();
|
||||||
void handleRpcResponse(const QJsonObject& response);
|
void handleRpcResponse(const QJsonObject& response);
|
||||||
void handleEvent(const QJsonObject& event);
|
void handleEvent(const QJsonObject& event);
|
||||||
|
void startReconnectTimer();
|
||||||
|
void stopReconnectTimer();
|
||||||
|
void attemptAutoAuth();
|
||||||
|
void saveCurrentToken();
|
||||||
|
|
||||||
// JSON conversion helpers
|
// Request tracking for retry logic
|
||||||
[[nodiscard]] Echoion::Api::PlaybackState parsePlaybackState(const QJsonObject& obj);
|
struct PendingRequest {
|
||||||
[[nodiscard]] Echoion::Api::TrackInfo parseTrackInfo(const QJsonObject& obj);
|
QString method;
|
||||||
[[nodiscard]] Echoion::Api::QueueEntry parseQueueEntry(const QJsonObject& obj);
|
QJsonObject params;
|
||||||
[[nodiscard]] Echoion::Api::SearchResult parseSearchResult(const QJsonObject& obj);
|
RpcCallback callback;
|
||||||
[[nodiscard]] QJsonObject trackInfoToJson(const Echoion::Api::TrackInfo& track);
|
int retryCount = 0;
|
||||||
|
QTimer* retryTimer = nullptr;
|
||||||
|
};
|
||||||
|
|
||||||
QWebSocket* socket_ = nullptr;
|
void retryRequest(quint64 requestId);
|
||||||
|
void cancelPendingRequests();
|
||||||
|
[[nodiscard]] int methodToInt(const QString& method) const;
|
||||||
|
|
||||||
|
SettingsManager settingsManager_;
|
||||||
|
// QPointer so a stray access after teardown is null-checked rather
|
||||||
|
// than dangling. Qt parent-ownership still frees it.
|
||||||
|
QPointer<QWebSocket> socket_ = nullptr;
|
||||||
|
QString currentHost_;
|
||||||
|
int currentPort_ = 8765;
|
||||||
|
QString currentNickname_;
|
||||||
QString authToken_;
|
QString authToken_;
|
||||||
std::unordered_map<QString, RpcCallback> pendingRequests_;
|
bool isAuthenticated_ = false;
|
||||||
quint64 requestId_ = 0;
|
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
|
// Reconnection
|
||||||
bool shouldReconnect_ = true;
|
QTimer* reconnectTimer_ = nullptr;
|
||||||
int reconnectAttempts_ = 0;
|
int reconnectAttempts_ = 0;
|
||||||
static constexpr int MAX_RECONNECT_ATTEMPTS = 5;
|
static constexpr int MAX_RECONNECT_ATTEMPTS = 5;
|
||||||
|
static constexpr int INITIAL_RECONNECT_DELAY_MS = 1000;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Desktop
|
} // namespace Echoion::Desktop
|
||||||
+21
-18
@@ -1,15 +1,18 @@
|
|||||||
#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();
|
setupUi();
|
||||||
setWindowTitle("Echoion - Admin Login");
|
setWindowTitle("Echoion - Admin Login");
|
||||||
setModal(true);
|
setModal(true);
|
||||||
setFixedSize(350, 200);
|
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);
|
||||||
@@ -52,33 +55,33 @@ void LoginDialog::setupUi() {
|
|||||||
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()) {
|
if (usernameEdit_->text().isEmpty()) {
|
||||||
QMessageBox::warning(this, "Login Error", "Please enter a username.");
|
QMessageBox::warning(this, "Login Error",
|
||||||
|
"Please enter a username.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (passwordEdit_->text().isEmpty()) {
|
if (passwordEdit_->text().isEmpty()) {
|
||||||
QMessageBox::warning(this, "Login Error", "Please enter a password.");
|
QMessageBox::warning(this, "Login Error",
|
||||||
|
"Please enter a password.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
accept();
|
accept();
|
||||||
}
|
}
|
||||||
|
|
||||||
void LoginDialog::onCancelClicked() {
|
void LoginDialog::onCancelClicked() { reject(); }
|
||||||
reject();
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Desktop
|
} // namespace Echoion::Desktop
|
||||||
+10
-6
@@ -1,19 +1,22 @@
|
|||||||
#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);
|
explicit LoginDialog(QWidget* parent = nullptr);
|
||||||
|
|
||||||
[[nodiscard]] QString getUsername() const;
|
[[nodiscard]] QString getUsername() const;
|
||||||
@@ -24,6 +27,7 @@ private slots:
|
|||||||
void onCancelClicked();
|
void onCancelClicked();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|
||||||
void setupUi();
|
void setupUi();
|
||||||
|
|
||||||
QLineEdit* usernameEdit_;
|
QLineEdit* usernameEdit_;
|
||||||
|
|||||||
@@ -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
|
|
||||||
+45
-127
@@ -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);
|
|
||||||
|
explicit MainWindow(CoreClient* client, QWidget* parent = nullptr);
|
||||||
~MainWindow() override;
|
~MainWindow() override;
|
||||||
|
|
||||||
// Authentication
|
|
||||||
void setAuthToken(const QString& token);
|
|
||||||
void clearAuthToken();
|
|
||||||
[[nodiscard]] bool isAuthenticated() const;
|
|
||||||
|
|
||||||
// State updates
|
|
||||||
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:
|
|
||||||
// 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();
|
|
||||||
|
|
||||||
private slots:
|
private slots:
|
||||||
|
|
||||||
|
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 onPlayClicked();
|
||||||
void onPauseClicked();
|
void onPauseClicked();
|
||||||
void onStopClicked();
|
|
||||||
void onSkipClicked();
|
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
|
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
|
||||||
+947
-64
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,294 @@
|
|||||||
|
#include "storage/SecureStorage.hpp"
|
||||||
|
|
||||||
|
#include <Void/Security/Security.hpp>
|
||||||
|
|
||||||
|
#include <QCoreApplication>
|
||||||
|
#include <QCryptographicHash>
|
||||||
|
#include <QDataStream>
|
||||||
|
#include <QDateTime>
|
||||||
|
#include <QDir>
|
||||||
|
#include <QFile>
|
||||||
|
#include <QFileInfo>
|
||||||
|
#include <QRandomGenerator>
|
||||||
|
#include <QSaveFile>
|
||||||
|
#include <QStandardPaths>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <span>
|
||||||
|
|
||||||
|
namespace Echoion::Desktop
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
const QByteArray storageMagic{"ECV2", 4};
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Security::SecretKey
|
||||||
|
toSecretKey(const QByteArray& value)
|
||||||
|
{
|
||||||
|
Void::Security::SecretKey key{};
|
||||||
|
std::copy_n(
|
||||||
|
reinterpret_cast<const unsigned char*>(value.constData()),
|
||||||
|
key.size(), key.begin());
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
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::loadOrCreateKey() const
|
||||||
|
{
|
||||||
|
if (!cachedKey_.isEmpty()) {
|
||||||
|
return cachedKey_;
|
||||||
|
}
|
||||||
|
|
||||||
|
const QString keyPath = getStorageDir() + "/secrets.key";
|
||||||
|
const QFileInfo keyInfo{keyPath};
|
||||||
|
if (keyInfo.isSymLink()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
QFile keyFile{keyPath};
|
||||||
|
if (keyFile.exists()) {
|
||||||
|
if (!keyFile.open(QIODevice::ReadOnly)) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
QByteArray key = keyFile.readAll();
|
||||||
|
if (key.size() !=
|
||||||
|
static_cast<qsizetype>(Void::Security::secret_key_bytes)) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
cachedKey_ = key;
|
||||||
|
return cachedKey_;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto generated = Void::Security::random_secret_key();
|
||||||
|
if (!generated) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
QByteArray key{reinterpret_cast<const char*>(generated->data()),
|
||||||
|
static_cast<qsizetype>(generated->size())};
|
||||||
|
QSaveFile output{keyPath};
|
||||||
|
if (!output.open(QIODevice::WriteOnly)) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (!output.setPermissions(QFileDevice::ReadOwner |
|
||||||
|
QFileDevice::WriteOwner) ||
|
||||||
|
output.write(key) != key.size() || !output.commit()) {
|
||||||
|
output.cancelWriting();
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
cachedKey_ = key;
|
||||||
|
return cachedKey_;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray SecureStorage::legacyKey() const
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
return hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray SecureStorage::legacyXor(const QByteArray& data,
|
||||||
|
const QByteArray& key)
|
||||||
|
{
|
||||||
|
if (key.isEmpty()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
QByteArray result = data;
|
||||||
|
const qsizetype keyLen = key.size();
|
||||||
|
|
||||||
|
for (qsizetype i = 0; i < result.size(); ++i) {
|
||||||
|
result[i] = result[i] ^ key[i % keyLen];
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray SecureStorage::encrypt(const QByteArray& data) const
|
||||||
|
{
|
||||||
|
const QByteArray encodedKey = loadOrCreateKey();
|
||||||
|
if (encodedKey.size() !=
|
||||||
|
static_cast<qsizetype>(Void::Security::secret_key_bytes)) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const auto* bytes =
|
||||||
|
reinterpret_cast<const unsigned char*>(data.constData());
|
||||||
|
auto sealed = Void::Security::seal_secret(
|
||||||
|
std::span<const unsigned char>{
|
||||||
|
bytes, static_cast<std::size_t>(data.size())},
|
||||||
|
toSecretKey(encodedKey));
|
||||||
|
if (!sealed) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
QByteArray result = storageMagic;
|
||||||
|
result.append(reinterpret_cast<const char*>(sealed->data()),
|
||||||
|
static_cast<qsizetype>(sealed->size()));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray SecureStorage::decrypt(const QByteArray& data) const
|
||||||
|
{
|
||||||
|
if (data.startsWith(storageMagic)) {
|
||||||
|
const QByteArray encodedKey = loadOrCreateKey();
|
||||||
|
if (encodedKey.size() !=
|
||||||
|
static_cast<qsizetype>(Void::Security::secret_key_bytes)) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const auto envelope = data.sliced(storageMagic.size());
|
||||||
|
const auto* bytes =
|
||||||
|
reinterpret_cast<const unsigned char*>(envelope.constData());
|
||||||
|
auto opened = Void::Security::open_secret(
|
||||||
|
std::span<const unsigned char>{
|
||||||
|
bytes, static_cast<std::size_t>(envelope.size())},
|
||||||
|
toSecretKey(encodedKey));
|
||||||
|
if (!opened) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return QByteArray{reinterpret_cast<const char*>(opened->data()),
|
||||||
|
static_cast<qsizetype>(opened->size())};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accept the v1 format only to migrate existing installations.
|
||||||
|
if (data.length() < 8) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
QDataStream headerStream(data);
|
||||||
|
quint32 magic = 0;
|
||||||
|
quint32 dataLen = 0;
|
||||||
|
headerStream >> magic >> dataLen;
|
||||||
|
if (magic != 0x4543484F ||
|
||||||
|
dataLen != static_cast<quint32>(data.size() - 8)) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
return legacyXor(data.sliced(8), legacyKey());
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SecureStorage::saveToFile(const QString& filepath,
|
||||||
|
const QByteArray& data) const
|
||||||
|
{
|
||||||
|
// Create backup of existing file
|
||||||
|
if (QFile::exists(filepath)) {
|
||||||
|
createBackup(filepath);
|
||||||
|
}
|
||||||
|
|
||||||
|
QSaveFile output{filepath};
|
||||||
|
if (!output.open(QIODevice::WriteOnly)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!output.setPermissions(QFileDevice::ReadOwner |
|
||||||
|
QFileDevice::WriteOwner) ||
|
||||||
|
output.write(data) != data.size()) {
|
||||||
|
output.cancelWriting();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return output.commit();
|
||||||
|
}
|
||||||
|
|
||||||
|
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,50 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QByteArray>
|
||||||
|
#include <QString>
|
||||||
|
|
||||||
|
namespace Echoion::Desktop
|
||||||
|
{
|
||||||
|
|
||||||
|
class SecureStorage
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
SecureStorage();
|
||||||
|
|
||||||
|
// Encrypt/decrypt data with authenticated VoidLibrary primitives.
|
||||||
|
[[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:
|
||||||
|
|
||||||
|
[[nodiscard]] QByteArray loadOrCreateKey() const;
|
||||||
|
|
||||||
|
// Read-only migration support for the v1 deterministic XOR format.
|
||||||
|
[[nodiscard]] QByteArray legacyKey() const;
|
||||||
|
[[nodiscard]] static QByteArray legacyXor(const QByteArray& data,
|
||||||
|
const QByteArray& key);
|
||||||
|
|
||||||
|
mutable QByteArray cachedKey_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Echoion::Desktop
|
||||||
@@ -0,0 +1,298 @@
|
|||||||
|
#include "storage/SecureStorage.hpp"
|
||||||
|
#include "storage/SettingsManager.hpp"
|
||||||
|
|
||||||
|
#include <QDataStream>
|
||||||
|
#include <QFile>
|
||||||
|
#include <QIODevice>
|
||||||
|
|
||||||
|
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