mirror of
https://github.com/allankoechke/pocketbase-cpp.git
synced 2026-12-05 01:16:10 +00:00
Added RealtimeService, Event and SSEClient logic
This commit is contained in:
@@ -33,7 +33,6 @@ add_executable(pocketbase-cpp
|
||||
sdk/dtos/logsmodel.h
|
||||
sdk/services/realtimeservice.h sdk/services/realtimeservice.cpp
|
||||
sdk/services/sseclient.h sdk/services/sseclient.cpp
|
||||
sdk/services/eventloop.h sdk/services/eventloop.cpp
|
||||
sdk/services/event.h sdk/services/event.cpp
|
||||
)
|
||||
target_link_libraries(pocketbase-cpp Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Network)
|
||||
|
||||
47
main.cpp
47
main.cpp
@@ -10,6 +10,9 @@
|
||||
#include "sdk/services/settingsservice.h"
|
||||
#include "sdk/services/logservice.h"
|
||||
#include "sdk/dtos/logsmodel.h"
|
||||
#include "sdk/services/event.h"
|
||||
|
||||
#include <QTimer>
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
@@ -17,14 +20,36 @@ int main(int argc, char *argv[])
|
||||
|
||||
PocketBase client{"http://127.0.0.1:5740/"};
|
||||
|
||||
// ADMIN
|
||||
try {
|
||||
auto user = client.admins()->authWithPassword("admin@admin.com", "12345678901");
|
||||
qDebug() << "Admin User: " << user.getToken() << "\t: " << user.getAdmin()->data();
|
||||
|
||||
qDebug() << "Temperature Subscribed ...";
|
||||
|
||||
QTimer::singleShot(10000, [&]() {
|
||||
qDebug() << "Unsubscribe from 'cow'";
|
||||
});
|
||||
QTimer::singleShot(15000, [&]() {
|
||||
client.collection("temperature")->unsubscribe();
|
||||
qDebug() << "Unsubscribe from 'temperature'";
|
||||
});
|
||||
|
||||
client.collection("temperature")->subscribe([&](const Event& data){
|
||||
qDebug() << "New Data: " << data.data();
|
||||
});
|
||||
|
||||
} catch (ClientResponseError e) {
|
||||
qDebug() << "Error thrown! -> " << e.what() << "\t" << e.status();
|
||||
}
|
||||
|
||||
qDebug() << "Hello ...";
|
||||
|
||||
// ADMIN
|
||||
// try {
|
||||
// auto user = client.admins()->authWithPassword("admin@admin.com", "12345678901");
|
||||
// qDebug() << "Admin User: " << user.getToken() << "\t: " << user.getAdmin()->data();
|
||||
// } catch (ClientResponseError e) {
|
||||
// qDebug() << "Error thrown! -> " << e.what() << "\t" << e.status();
|
||||
// }
|
||||
|
||||
// try {
|
||||
// QJsonObject body;
|
||||
// body["email"] = "admin@admin.com";
|
||||
@@ -131,14 +156,14 @@ int main(int argc, char *argv[])
|
||||
// }
|
||||
|
||||
// Logs Service
|
||||
try {
|
||||
QJsonObject params;
|
||||
params["filter"] = "level>0";
|
||||
auto logsmodel = client.logs()->getList(); // getStats(params);
|
||||
// qDebug() << "Logs: " << logsmodel;
|
||||
} catch (ClientResponseError e) {
|
||||
qDebug() << "Error thrown! -> " << e.what() << "\t" << e.status();
|
||||
}
|
||||
// try {
|
||||
// QJsonObject params;
|
||||
// params["filter"] = "level>0";
|
||||
// auto logsmodel = client.logs()->getList(); // getStats(params);
|
||||
// // qDebug() << "Logs: " << logsmodel;
|
||||
// } catch (ClientResponseError e) {
|
||||
// qDebug() << "Error thrown! -> " << e.what() << "\t" << e.status();
|
||||
// }
|
||||
|
||||
// Auth with password
|
||||
// auto user = client.collection("users")->authWithPassword("test@user.com", "123456789");
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include "services/healthservice.h"
|
||||
#include "services/settingsservice.h"
|
||||
#include "services/logservice.h"
|
||||
#include "services/realtimeservice.h"
|
||||
|
||||
PocketBase::PocketBase(const QString& baseUrl, const QString& lang, int timeout, QObject* parent)
|
||||
: QObject(parent),
|
||||
@@ -19,7 +20,8 @@ PocketBase::PocketBase(const QString& baseUrl, const QString& lang, int timeout,
|
||||
m_adminService( new AdminService(this, this) ),
|
||||
m_healthService( new HealthService(this, this) ),
|
||||
m_settingsService( new SettingsService(this, this)),
|
||||
m_logService( new LogService(this, this) ) {}
|
||||
m_logService( new LogService(this, this) ),
|
||||
m_realtimeService( new RealtimeService(this, this) ) {}
|
||||
|
||||
AdminService *PocketBase::admins() const { return m_adminService; }
|
||||
|
||||
@@ -56,6 +58,8 @@ SettingsService *PocketBase::settings() const { return m_settingsService; }
|
||||
|
||||
LogService *PocketBase::logs() const { return m_logService; }
|
||||
|
||||
RealtimeService *PocketBase::realtime() const { return m_realtimeService; }
|
||||
|
||||
QJsonObject PocketBase::send(const QString& path, const QJsonObject params) {
|
||||
QUrl url = buildUrl(path);
|
||||
QNetworkRequest request;
|
||||
|
||||
@@ -22,6 +22,7 @@ class CollectionService;
|
||||
class HealthService;
|
||||
class SettingsService;
|
||||
class LogService;
|
||||
class RealtimeService;
|
||||
|
||||
class PocketBase : public QObject
|
||||
{
|
||||
@@ -39,6 +40,7 @@ public:
|
||||
HealthService* health() const;
|
||||
SettingsService* settings() const;
|
||||
LogService* logs() const;
|
||||
RealtimeService* realtime() const;
|
||||
|
||||
QJsonObject send(const QString& path, const QJsonObject params);
|
||||
|
||||
@@ -67,6 +69,7 @@ private:
|
||||
HealthService* m_healthService;
|
||||
SettingsService* m_settingsService;
|
||||
LogService* m_logService;
|
||||
RealtimeService* m_realtimeService;
|
||||
|
||||
QMap<QString, RecordService*> m_recordServices;
|
||||
};
|
||||
|
||||
@@ -1,36 +1,42 @@
|
||||
#include "event.h"
|
||||
|
||||
Event::Event(const QString& id, const QString& event, const QString& data, int retry)
|
||||
: id(id), event(event), data(data), retry(retry) {}
|
||||
Event::Event(const QString& id,
|
||||
const QString& event,
|
||||
const QJsonObject& data,
|
||||
int retry)
|
||||
: m_id(id),
|
||||
m_event(event),
|
||||
m_data(data),
|
||||
m_retry(retry) {}
|
||||
|
||||
QString Event::getId() const {
|
||||
return id;
|
||||
QString Event::id() const {
|
||||
return m_id;
|
||||
}
|
||||
|
||||
QString Event::getEvent() const {
|
||||
return event;
|
||||
QString Event::event() const {
|
||||
return m_event;
|
||||
}
|
||||
|
||||
QString Event::getData() const {
|
||||
return data;
|
||||
QJsonObject Event::data() const {
|
||||
return m_data;
|
||||
}
|
||||
|
||||
int Event::getRetry() const {
|
||||
return retry;
|
||||
int Event::retry() const {
|
||||
return m_retry;
|
||||
}
|
||||
|
||||
void Event::setId(const QString& id) {
|
||||
this->id = id;
|
||||
m_id = id;
|
||||
}
|
||||
|
||||
void Event::setEvent(const QString& event) {
|
||||
this->event = event;
|
||||
m_event = event;
|
||||
}
|
||||
|
||||
void Event::setData(const QString& data) {
|
||||
this->data = data;
|
||||
void Event::setData(const QJsonObject& data) {
|
||||
m_data = data;
|
||||
}
|
||||
|
||||
void Event::setRetry(int retry) {
|
||||
this->retry = retry;
|
||||
m_retry = retry;
|
||||
}
|
||||
|
||||
@@ -2,29 +2,30 @@
|
||||
#define EVENT_H
|
||||
|
||||
#include <QString>
|
||||
#include <QJsonObject>
|
||||
|
||||
class Event {
|
||||
public:
|
||||
Event(const QString& id = "",
|
||||
const QString& event = "message",
|
||||
const QString& data = "",
|
||||
const QJsonObject& data = {},
|
||||
int retry = -1);
|
||||
|
||||
QString getId() const;
|
||||
QString getEvent() const;
|
||||
QString getData() const;
|
||||
int getRetry() const;
|
||||
QString id() const;
|
||||
QString event() const;
|
||||
QJsonObject data() const;
|
||||
int retry() const;
|
||||
|
||||
void setId(const QString& id);
|
||||
void setEvent(const QString& event);
|
||||
void setData(const QString& data);
|
||||
void setData(const QJsonObject& data);
|
||||
void setRetry(int retry);
|
||||
|
||||
private:
|
||||
QString id;
|
||||
QString event;
|
||||
QString data;
|
||||
int retry;
|
||||
QString m_id;
|
||||
QString m_event;
|
||||
QJsonObject m_data;
|
||||
int m_retry;
|
||||
};
|
||||
|
||||
#endif // EVENT_H
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
#include "eventloop.h"
|
||||
#include <QNetworkRequest>
|
||||
#include <QNetworkReply>
|
||||
#include <QUrl>
|
||||
#include <QUrlQuery>
|
||||
|
||||
EventLoop::EventLoop(const QString& url, const QString& method, const QMap<QString, QString>& headers, const QByteArray& payload, const QString& encoding, QObject* parent)
|
||||
: QThread(parent), url(url), method(method), headers(headers), payload(payload), encoding(encoding), kill(false) {}
|
||||
|
||||
void EventLoop::addEventListener(const QString& event, std::function<void(const Event&)> callback) {
|
||||
listeners[event] = callback;
|
||||
}
|
||||
|
||||
void EventLoop::removeEventListener(const QString& event) {
|
||||
listeners.remove(event);
|
||||
}
|
||||
|
||||
void EventLoop::run() {
|
||||
while (!kill) {
|
||||
readStream();
|
||||
}
|
||||
}
|
||||
|
||||
void EventLoop::readStream() {
|
||||
QNetworkRequest request(QUrl{url});
|
||||
for (auto it = headers.begin(); it != headers.end(); ++it) {
|
||||
request.setRawHeader(it.key().toUtf8(), it.value().toUtf8());
|
||||
}
|
||||
|
||||
QNetworkReply* reply = networkManager.sendCustomRequest(request, method.toUtf8(), payload);
|
||||
connect(reply, &QNetworkReply::readyRead, this, [this, reply]() {
|
||||
QByteArray data = reply->readAll();
|
||||
processEvent(data);
|
||||
});
|
||||
|
||||
connect(reply, &QNetworkReply::finished, this, [reply]() {
|
||||
reply->deleteLater();
|
||||
});
|
||||
}
|
||||
|
||||
void EventLoop::processEvent(const QByteArray& data) {
|
||||
Event event;
|
||||
QList<QByteArray> lines = data.split('\n');
|
||||
for (const QByteArray& line : lines) {
|
||||
if (line.startsWith("id:")) {
|
||||
event.setId(line.mid(3).trimmed());
|
||||
} else if (line.startsWith("event:")) {
|
||||
event.setEvent(line.mid(6).trimmed());
|
||||
} else if (line.startsWith("data:")) {
|
||||
event.setData(line.mid(5).trimmed());
|
||||
} else if (line.startsWith("retry:")) {
|
||||
event.setRetry(line.mid(6).trimmed().toInt());
|
||||
}
|
||||
}
|
||||
if (listeners.contains(event.getEvent())) {
|
||||
listeners[event.getEvent()](event);
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
#ifndef EVENTLOOP_H
|
||||
#define EVENTLOOP_H
|
||||
|
||||
#include <QThread>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkReply>
|
||||
#include <QMap>
|
||||
#include <functional>
|
||||
#include "../event.h"
|
||||
|
||||
class EventLoop : public QThread {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit EventLoop(const QString& url, const QString& method = "GET", const QMap<QString, QString>& headers = {}, const QByteArray& payload = QByteArray(), const QString& encoding = "utf-8", QObject* parent = nullptr);
|
||||
void addEventListener(const QString& event, std::function<void(const Event&)> callback);
|
||||
void removeEventListener(const QString& event);
|
||||
|
||||
protected:
|
||||
void run() override;
|
||||
|
||||
private:
|
||||
void readStream();
|
||||
void processEvent(const QByteArray& data);
|
||||
|
||||
QString url;
|
||||
QString method;
|
||||
QMap<QString, QString> headers;
|
||||
QByteArray payload;
|
||||
QString encoding;
|
||||
QNetworkAccessManager networkManager;
|
||||
bool kill;
|
||||
QMap<QString, std::function<void(const Event&)>> listeners;
|
||||
};
|
||||
|
||||
#endif // EVENTLOOP_H
|
||||
@@ -61,7 +61,7 @@ ListResult LogService::getList(int page, int perPage, const QJsonObject paramObj
|
||||
if ( data.contains("items") ) {
|
||||
QJsonArray itemsArray = data["items"].toArray();
|
||||
for (const QJsonValue& item : itemsArray) {
|
||||
items.append(decode(item.toObject()));
|
||||
items.append(new BaseModel(item.toObject()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,23 +1,174 @@
|
||||
#include "realtimeservice.h"
|
||||
#include "../client.h"
|
||||
|
||||
SSEClient::SSEClient(const QString& url, const QString& method, const QMap<QString, QString>& headers, const QByteArray& payload, const QString& encoding, QObject* parent)
|
||||
: QObject(parent) {
|
||||
loopThread = new EventLoop(url, method, headers, payload, encoding, this);
|
||||
connect(loopThread, &EventLoop::finished, loopThread, &QObject::deleteLater);
|
||||
loopThread->start();
|
||||
RealtimeService::RealtimeService(PocketBase *client, QObject *parent)
|
||||
: QObject{parent},
|
||||
client(client) {
|
||||
m_sseClient = new SSEClient( client->buildUrl("/api/realtime").toString(), client );
|
||||
|
||||
connect(m_sseClient, &SSEClient::dataReceived,
|
||||
this, &RealtimeService::handleMessages);
|
||||
|
||||
///m_sseThread = new QThread(this);
|
||||
//m_sseClient->moveToThread(m_sseThread);
|
||||
//connect(m_sseThread, &QThread::finished, m_sseThread, &QThread::quit);
|
||||
//m_sseThread->start();
|
||||
}
|
||||
|
||||
void SSEClient::addEventListener(const QString& event, std::function<void(const Event&)> callback) {
|
||||
listeners[event] = callback;
|
||||
loopThread->addEventListener(event, callback);
|
||||
QString RealtimeService::clientID() const { return m_clientID; }
|
||||
|
||||
void RealtimeService::subscribe(QString topic,
|
||||
std::function<void (const Event &)> listener,
|
||||
const QJsonObject ¶ms) {
|
||||
QString key = topic;
|
||||
|
||||
QJsonObject payload = params;
|
||||
|
||||
if ( !m_subscriptions.contains(key) ) {
|
||||
m_subscriptions[key] = {};
|
||||
}
|
||||
|
||||
m_subscriptions[key].append(listener);
|
||||
|
||||
// bool isConnected = false;
|
||||
|
||||
// start a new sse connection
|
||||
if( !m_sseClient->isConnected() ) {
|
||||
m_sseClient->connectSSE();
|
||||
}
|
||||
|
||||
if ( m_sseClient->isOpen() &&
|
||||
!m_clientID.isEmpty() &&
|
||||
m_subscriptions[key].size() >= 1 ) {
|
||||
// otherwise - just persist the updated subscriptions
|
||||
// (if it is the first for the topic)
|
||||
qDebug() << "Sumitted Results? " << submitSubscriptions();
|
||||
}
|
||||
}
|
||||
|
||||
void SSEClient::removeEventListener(const QString& event) {
|
||||
listeners.remove(event);
|
||||
loopThread->removeEventListener(event);
|
||||
void RealtimeService::unsubscribe(const QString &topic) {
|
||||
bool needToSubmit = false;
|
||||
|
||||
if ( topic.isEmpty() ) {
|
||||
// remove all subscriptions
|
||||
m_subscriptions.clear();
|
||||
} else {
|
||||
auto subs = getSubscriptionsByTopic(topic);
|
||||
|
||||
for ( const auto& key : subs.keys() ) {
|
||||
m_subscriptions.remove(key);
|
||||
needToSubmit = true;
|
||||
}
|
||||
}
|
||||
|
||||
// no other subscriptions -> close the sse connection
|
||||
if ( !hasNonEmptyTopic() ) {
|
||||
disconnectSSE();
|
||||
}
|
||||
|
||||
// otherwise - notify the server about the subscription changes
|
||||
if ( !m_clientID.isEmpty() && needToSubmit) {
|
||||
submitSubscriptions();
|
||||
}
|
||||
}
|
||||
|
||||
void SSEClient::close() {
|
||||
loopThread->kill = true;
|
||||
loopThread->wait();
|
||||
QMap<QString, QList<std::function<void (const Event &)> > >
|
||||
RealtimeService::getSubscriptionsByTopic(const QString &topic) {
|
||||
QMap<QString, QList<std::function<void(const Event&)>>> result{};
|
||||
|
||||
// "?" so that it can be used as end delimiter for the topic
|
||||
QString _topic = topic.contains("?") ? topic : topic+"?";
|
||||
|
||||
for( const QString& key : m_subscriptions.keys() ) {
|
||||
auto value = m_subscriptions[key];
|
||||
QString _key = key+"?";
|
||||
|
||||
if (_key.startsWith(_topic)) {
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
bool RealtimeService::hasNonEmptyTopic() {
|
||||
for ( const auto& key : m_subscriptions.keys() ) {
|
||||
if ( !m_subscriptions[key].isEmpty() ) {
|
||||
return true; // has at least one listener
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool RealtimeService::connectSSE() {
|
||||
disconnectSSE();
|
||||
|
||||
QString url = client->buildUrl("/api/realtime").toString();
|
||||
m_sseClient->setUrl(url);
|
||||
|
||||
// bind subscriptions listener
|
||||
// _sse?.onMessage.listen((msg) {
|
||||
// if (!_subscriptions.containsKey(msg.event)) {
|
||||
// return;
|
||||
// }
|
||||
|
||||
// _subscriptions[msg.event]?.forEach((fn) {
|
||||
// fn.call(msg);
|
||||
// });
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void RealtimeService::disconnectSSE() {
|
||||
m_sseClient->close();
|
||||
m_clientID.clear();
|
||||
}
|
||||
|
||||
bool RealtimeService::submitSubscriptions() {
|
||||
qDebug() << "[Realtime Service] Submitting subscriptions";
|
||||
|
||||
QJsonObject payload, body;
|
||||
body["clientId"] = m_clientID;
|
||||
body["subscriptions"] = QJsonArray::fromStringList(m_subscriptions.keys());
|
||||
payload["method"] = "POST";
|
||||
payload["body"] = body;
|
||||
|
||||
auto responseJSON = client->send("/api/realtime", payload);
|
||||
qDebug() << "[Submitted Subs] Response: " << responseJSON;
|
||||
return responseJSON.value("statusCode").toInt() == 204;
|
||||
}
|
||||
|
||||
void RealtimeService::onSSEConnected(const QJsonObject& data)
|
||||
{
|
||||
// Get the client ID
|
||||
m_clientID = data.value("clientId").toString("");
|
||||
|
||||
// Lets resend this if it fails
|
||||
if( !submitSubscriptions() ) {
|
||||
QTimer::singleShot(1000, [&]() { onSSEConnected(data); });
|
||||
}
|
||||
}
|
||||
|
||||
void RealtimeService::handleMessages(const QString& id,
|
||||
const QString& event,
|
||||
const QString& data)
|
||||
{
|
||||
QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8());
|
||||
QJsonObject obj = doc.object();
|
||||
|
||||
emit dataChanged(event, obj);
|
||||
|
||||
if( event == "PB_CONNECT" ) {
|
||||
onSSEConnected(obj);
|
||||
}
|
||||
|
||||
// Call the callbacks
|
||||
if( m_subscriptions.contains(event) ) {
|
||||
auto callbacks = m_subscriptions[event];
|
||||
for( const auto& callback : callbacks ) {
|
||||
auto e = Event(id, event, obj);
|
||||
callback(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,62 @@
|
||||
#ifndef SSECLIENT_H
|
||||
#define SSECLIENT_H
|
||||
#ifndef REALTIMESERVICE_H
|
||||
#define REALTIMESERVICE_H
|
||||
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
#include <QMap>
|
||||
#include <functional>
|
||||
#include "EventLoop.h"
|
||||
#include "Event.h"
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
#include <QTimer>
|
||||
#include <QThread>
|
||||
|
||||
class SSEClient : public QObject {
|
||||
#include "event.h"
|
||||
#include "sseclient.h"
|
||||
|
||||
class PocketBase;
|
||||
|
||||
class RealtimeService : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit SSEClient(const QString& url, const QString& method = "GET", const QMap<QString, QString>& headers = {}, const QByteArray& payload = QByteArray(), const QString& encoding = "utf-8", QObject* parent = nullptr);
|
||||
void addEventListener(const QString& event, std::function<void(const Event&)> callback);
|
||||
void removeEventListener(const QString& event);
|
||||
void close();
|
||||
explicit RealtimeService(PocketBase* client,
|
||||
QObject* parent = nullptr);
|
||||
|
||||
// Returns the established SSE connection client id (if any).
|
||||
QString clientID() const;
|
||||
|
||||
void subscribe( QString topic,
|
||||
std::function<void(const Event&)> listener,
|
||||
const QJsonObject& params = QJsonObject());
|
||||
|
||||
void unsubscribe(const QString& topic = "");
|
||||
|
||||
QMap<QString, QList<std::function<void(const Event&)>>>
|
||||
getSubscriptionsByTopic(const QString& topic);
|
||||
|
||||
bool hasNonEmptyTopic();
|
||||
|
||||
bool connectSSE();
|
||||
|
||||
void disconnectSSE();
|
||||
|
||||
bool submitSubscriptions();
|
||||
|
||||
signals:
|
||||
void dataChanged(const QString& event,
|
||||
const QJsonObject& data);
|
||||
|
||||
private slots:
|
||||
void onSSEConnected(const QJsonObject&);
|
||||
void handleMessages(const QString &id,
|
||||
const QString &event,
|
||||
const QString &list);
|
||||
|
||||
private:
|
||||
EventLoop* loopThread;
|
||||
QMap<QString, std::function<void(const Event&)>> listeners;
|
||||
SSEClient* m_sseClient;
|
||||
QString m_clientID = "";
|
||||
QMap<QString, QList<std::function<void(const Event&)>>> m_subscriptions {};
|
||||
PocketBase* client;
|
||||
QThread* m_sseThread;
|
||||
};
|
||||
|
||||
#endif // SSECLIENT_H
|
||||
#endif // REALTIMESERVICE_H
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "recordservice.h"
|
||||
#include "baseauthstore.h"
|
||||
#include "../client.h"
|
||||
#include "realtimeservice.h"
|
||||
|
||||
RecordAuthResponse::RecordAuthResponse(const QString &token, RecordModel* record)
|
||||
: token(token), record(record) {}
|
||||
@@ -65,24 +66,31 @@ QString RecordService::baseCrudPath() const {
|
||||
// return result;
|
||||
// }
|
||||
|
||||
void RecordService::subscribe(std::function<void (const QVariant &)> callback) {
|
||||
// client->realtime()->subscribe(collectionIdOrName, callback);
|
||||
void RecordService::subscribe(std::function<void (const Event &)> callback) {
|
||||
client->realtime()->subscribe(m_collectionIdOrName, callback);
|
||||
}
|
||||
|
||||
void RecordService::subscribeOne(const QString &recordId, std::function<void (const QVariant &)> callback) {
|
||||
// client->realtime()->subscribe(collectionIdOrName + "/" + recordId, callback);
|
||||
void RecordService::subscribeOne(const QString &recordId, std::function<void (const Event &)> callback) {
|
||||
client->realtime()->subscribe(m_collectionIdOrName + "/" + recordId, callback);
|
||||
}
|
||||
|
||||
void RecordService::unsubscribe() {
|
||||
client->realtime()->unsubscribe( m_collectionIdOrName );
|
||||
}
|
||||
|
||||
void RecordService::unsubscribe(const QString &id) {
|
||||
if ( !id.isEmpty() ) {
|
||||
QString topic = m_collectionIdOrName + "/" + id;
|
||||
client->realtime()->unsubscribe(topic);
|
||||
}
|
||||
}
|
||||
|
||||
void RecordService::unsubscribe(const QStringList &recordIds) {
|
||||
/*if (!recordIds.isEmpty()) {
|
||||
QStringList subs;
|
||||
if ( !recordIds.isEmpty() ) {
|
||||
for (const auto& id : recordIds) {
|
||||
subs.append(collectionIdOrName + "/" + id);
|
||||
client->realtime()->unsubscribe(m_collectionIdOrName + "/" + id);
|
||||
}
|
||||
client->realtime()->unsubscribe(subs);
|
||||
} else {
|
||||
client->realtime()->unsubscribeByPrefix(collectionIdOrName);
|
||||
} */
|
||||
}
|
||||
}
|
||||
|
||||
RecordModel RecordService::update(
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <QEventLoop>
|
||||
|
||||
#include "crudservice.h"
|
||||
#include "event.h"
|
||||
#include "../dtos/recordmodel.h"
|
||||
|
||||
// Forward declaration
|
||||
@@ -65,10 +66,12 @@ public:
|
||||
|
||||
QString getFileUrl(const RecordModel& record, const QString& filename, const QUrlQuery& queryParams = QUrlQuery()) const;
|
||||
|
||||
void subscribe(std::function<void(const QVariant&)> callback);
|
||||
void subscribe(std::function<void(const Event&)> callback);
|
||||
|
||||
void subscribeOne(const QString& recordId, std::function<void(const QVariant&)> callback);
|
||||
void subscribeOne(const QString& recordId, std::function<void(const Event&)> callback);
|
||||
|
||||
void unsubscribe();
|
||||
void unsubscribe(const QString& id);
|
||||
void unsubscribe(const QStringList& recordIds);
|
||||
|
||||
RecordModel update(const QString& id, const QJsonObject& bodyParams = QJsonObject(), const QJsonObject& queryParams = QJsonObject());
|
||||
|
||||
@@ -1,122 +1,104 @@
|
||||
#include "SSEClient.h"
|
||||
#include "sseclient.h"
|
||||
#include "../client.h"
|
||||
#include "baseauthstore.h"
|
||||
|
||||
Event::Event(const QString& id,
|
||||
const QString& event,
|
||||
const QString& data,
|
||||
int retry)
|
||||
: id(id),
|
||||
event(event),
|
||||
data(data),
|
||||
retry(retry) {}
|
||||
SSEClient::SSEClient(const QString& url, PocketBase* client, QObject *parent)
|
||||
: QObject(parent),
|
||||
m_url(url),
|
||||
m_connected(false),
|
||||
m_open(false),
|
||||
client(client) {}
|
||||
|
||||
QString Event::getId() const { return id; }
|
||||
|
||||
QString Event::getEvent() const { return event; }
|
||||
|
||||
QString Event::getData() const { return data; }
|
||||
|
||||
int Event::getRetry() const { return retry; }
|
||||
|
||||
EventLoop::EventLoop(const QString& url,
|
||||
const QString& method,
|
||||
const QMap<QString, QString>& headers,
|
||||
const QByteArray& payload,
|
||||
const QString& encoding,
|
||||
QObject* parent)
|
||||
: QThread(parent),
|
||||
url(url),
|
||||
method(method),
|
||||
headers(headers),
|
||||
payload(payload),
|
||||
encoding(encoding),
|
||||
kill(false)
|
||||
void SSEClient::connectSSE()
|
||||
{
|
||||
networkManager = new QNetworkAccessManager(this);
|
||||
m_nman = new QNetworkAccessManager(this);
|
||||
QNetworkRequest request(QUrl{m_url});
|
||||
|
||||
auto token = client->authStore()->token().toUtf8();
|
||||
qDebug() << "Token: " << token;
|
||||
|
||||
request.setRawHeader("Accept","text/event-stream");
|
||||
request.setRawHeader("Authorization", "Bearer " + token);
|
||||
// request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
|
||||
request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
|
||||
QNetworkRequest::AlwaysNetwork);
|
||||
|
||||
qDebug() << "Sending GET request to > " << request.url().toString();
|
||||
|
||||
QNetworkReply *reply = m_nman->get(request);
|
||||
connect(reply, &QNetworkReply::readyRead,
|
||||
this, &SSEClient::onReplyReadyRead);
|
||||
connect(reply, &QNetworkReply::finished,
|
||||
this, &SSEClient::onReplyFinished);
|
||||
|
||||
QEventLoop wait_loop;
|
||||
connect(reply, &QNetworkReply::finished, &wait_loop, &QEventLoop::quit);
|
||||
wait_loop.exec();
|
||||
}
|
||||
|
||||
void EventLoop::addListener(const QString& event,
|
||||
std::function<void(Event)> listener) {
|
||||
listeners[event] = listener;
|
||||
}
|
||||
|
||||
void EventLoop::removeListener(const QString& event) {
|
||||
listeners.remove(event);
|
||||
}
|
||||
|
||||
void EventLoop::run() {
|
||||
QNetworkRequest request(QUrl{url});
|
||||
for (auto it = headers.begin(); it != headers.end(); ++it) {
|
||||
request.setRawHeader(it.key().toUtf8(), it.value().toUtf8());
|
||||
void SSEClient::close()
|
||||
{
|
||||
if( m_nman ) {
|
||||
//
|
||||
}
|
||||
|
||||
if (method.toUpper() == "POST") {
|
||||
reply = networkManager->post(request, payload);
|
||||
} else {
|
||||
reply = networkManager->get(request);
|
||||
}
|
||||
|
||||
connect(reply, &QNetworkReply::readyRead, this, &EventLoop::onReadyRead);
|
||||
|
||||
exec();
|
||||
}
|
||||
|
||||
void EventLoop::stop() {
|
||||
kill = true;
|
||||
if (reply) {
|
||||
reply->abort();
|
||||
}
|
||||
quit();
|
||||
wait();
|
||||
}
|
||||
void SSEClient::setUrl(const QString url) { m_url = url; }
|
||||
|
||||
void EventLoop::onReadyRead() {
|
||||
if (kill) return;
|
||||
readStream();
|
||||
}
|
||||
bool SSEClient::isOpen() { return m_open; }
|
||||
|
||||
void EventLoop::readStream() {
|
||||
QByteArray data = reply->readAll();
|
||||
processEvent(data);
|
||||
}
|
||||
bool SSEClient::isConnected() { return m_connected; }
|
||||
|
||||
void EventLoop::processEvent(const QByteArray& data) {
|
||||
Event event;
|
||||
QList<QByteArray> lines = data.split('\n');
|
||||
for (const QByteArray& line : lines) {
|
||||
if (line.startsWith("id:")) {
|
||||
event.setId(line.mid(3).trimmed());
|
||||
} else if (line.startsWith("event:")) {
|
||||
event.setEvent(line.mid(6).trimmed());
|
||||
} else if (line.startsWith("data:")) {
|
||||
event.setData(line.mid(5).trimmed());
|
||||
} else if (line.startsWith("retry:")) {
|
||||
event.setRetry(line.mid(6).trimmed().toInt());
|
||||
void SSEClient::onReplyReadyRead()
|
||||
{
|
||||
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
|
||||
|
||||
if(reply)
|
||||
{
|
||||
m_connected = true;
|
||||
|
||||
QString response(reply->readAll());
|
||||
QStringList responseList = response.split("\n");
|
||||
|
||||
if( responseList.size() > 2 )
|
||||
{
|
||||
QString id=responseList.at(0);
|
||||
id = id.replace("id:","");
|
||||
|
||||
QString event=responseList.at(1);
|
||||
event=event.replace("event:","");
|
||||
|
||||
QStringList dataArray;
|
||||
|
||||
// for(int i=2; i<responseList.size(); i++) {
|
||||
// QString data=responseList.at(i);
|
||||
// data = data.trimmed();
|
||||
// if(data.startsWith("data:"))
|
||||
// data=data.replace("data:","");
|
||||
// if( data!="" ) dataArray.append(data);
|
||||
// }
|
||||
|
||||
QString data=responseList.at(2);
|
||||
data = data.trimmed();
|
||||
if(data.startsWith("data:"))
|
||||
data=data.replace("data:","");
|
||||
if( data!="" ) dataArray.append(data);
|
||||
|
||||
if( event == "PB_CONNECT") {
|
||||
m_open = true;
|
||||
}
|
||||
|
||||
emit dataReceived(id,event,data);
|
||||
}
|
||||
}
|
||||
if (listeners.contains(event.getEvent())) {
|
||||
listeners[event.getEvent()](event);
|
||||
}
|
||||
|
||||
else
|
||||
m_connected = false;
|
||||
}
|
||||
|
||||
SSEClient::SSEClient(const QString& url, const QString& method, const QMap<QString, QString>& headers, const QByteArray& payload, const QString& encoding, QObject* parent)
|
||||
: QObject(parent) {
|
||||
loopThread = new EventLoop(url, method, headers, payload, encoding, this);
|
||||
connect(loopThread, &EventLoop::finished, loopThread, &QObject::deleteLater);
|
||||
loopThread->start();
|
||||
void SSEClient::onReplyFinished()
|
||||
{
|
||||
m_open = false;
|
||||
m_connected = false;
|
||||
QTimer::singleShot(1000, [&](){ connectSSE(); });
|
||||
}
|
||||
|
||||
void SSEClient::addEventListener(const QString& event, std::function<void(const Event&)> callback) {
|
||||
listeners[event] = callback;
|
||||
loopThread->addListener(event, callback);
|
||||
}
|
||||
|
||||
void SSEClient::removeEventListener(const QString& event) {
|
||||
listeners.remove(event);
|
||||
loopThread->removeListener(event);
|
||||
}
|
||||
|
||||
void SSEClient::close() {
|
||||
loopThread->stop();
|
||||
loopThread->wait();
|
||||
}
|
||||
|
||||
|
||||
@@ -2,95 +2,45 @@
|
||||
#define SSECLIENT_H
|
||||
|
||||
#include <QObject>
|
||||
#include <QThread>
|
||||
#include <QMap>
|
||||
#include <QVariant>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkRequest>
|
||||
#include <QNetworkReply>
|
||||
#include <QTimer>
|
||||
#include <QEventLoop>
|
||||
|
||||
class Event : public QObject {
|
||||
class PocketBase;
|
||||
|
||||
class SSEClient : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit Event(const QString& id = "",
|
||||
const QString& event = "message",
|
||||
const QString& data = "",
|
||||
int retry = -1);
|
||||
|
||||
QString getId() const;
|
||||
void setId(const QString& nId) { id = nId; };
|
||||
|
||||
QString getEvent() const;
|
||||
void setEvent(const QString& nEvent) { event = nEvent; };
|
||||
|
||||
QString getData() const;
|
||||
void setData(const QString& nData) { data = nData; };
|
||||
|
||||
int getRetry() const;
|
||||
void setRetry(const int& nRetry) { retry = nRetry; };
|
||||
|
||||
private:
|
||||
QString id;
|
||||
QString event;
|
||||
QString data;
|
||||
int retry;
|
||||
};
|
||||
|
||||
class EventLoop : public QThread {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit EventLoop(const QString& url,
|
||||
const QString& method = "GET",
|
||||
const QMap<QString, QString>& headers = {},
|
||||
const QByteArray& payload = {},
|
||||
const QString& encoding = "utf-8",
|
||||
QObject* parent = nullptr);
|
||||
void addListener(const QString& event, std::function<void(Event)> listener);
|
||||
void removeListener(const QString& event);
|
||||
void run() override;
|
||||
void stop();
|
||||
|
||||
signals:
|
||||
void eventReceived(const Event& event);
|
||||
|
||||
private slots:
|
||||
void onReadyRead();
|
||||
|
||||
private:
|
||||
void readStream();
|
||||
void processEvent(const QByteArray& chunk);
|
||||
|
||||
QString url;
|
||||
QString method;
|
||||
QMap<QString, QString> headers;
|
||||
QByteArray payload;
|
||||
QString encoding;
|
||||
QNetworkAccessManager* networkManager;
|
||||
QNetworkReply* reply;
|
||||
bool kill;
|
||||
QMap<QString, std::function<void(Event)>> listeners;
|
||||
};
|
||||
|
||||
class SSEClient : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit SSEClient(const QString& url,
|
||||
const QString& method = "GET",
|
||||
const QMap<QString, QString>& headers = {},
|
||||
const QByteArray& payload = QByteArray(),
|
||||
const QString& encoding = "utf-8",
|
||||
PocketBase* client,
|
||||
QObject* parent = nullptr);
|
||||
void addEventListener(const QString& event,
|
||||
std::function<void(const Event&)> callback);
|
||||
void removeEventListener(const QString& event);
|
||||
|
||||
void connectSSE();
|
||||
void close();
|
||||
void setUrl(const QString url);
|
||||
|
||||
bool isOpen(); // SSEClient Open
|
||||
bool isConnected(); // SSEClient connected, PB_CONNECT not yet received
|
||||
|
||||
private slots:
|
||||
// Slots called when the Network Manager has data ready
|
||||
// for reading and when its closed
|
||||
void onReplyReadyRead();
|
||||
void onReplyFinished();
|
||||
|
||||
signals:
|
||||
// Signal emitted for each event from the SSEClient
|
||||
void dataReceived( QString& id,
|
||||
const QString& event,
|
||||
const QString& data );
|
||||
|
||||
private:
|
||||
EventLoop* loopThread;
|
||||
QMap<QString, std::function<void(const Event&)>> listeners;
|
||||
QNetworkAccessManager * m_nman;
|
||||
QString m_url;
|
||||
bool m_connected, m_open;
|
||||
PocketBase* client;
|
||||
};
|
||||
|
||||
#endif // SSECLIENT_H
|
||||
|
||||
Reference in New Issue
Block a user