Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

Qt Allstack II - Adding Firebase

include(FetchContent)

FetchContent_Declare(
  FirebaseAdminQt
  GIT_REPOSITORY https://github.com/cutelyst/FirebaseAdminQt.git
  GIT_TAG        a9db10cdb3c1d6d68d37630fea9abcac8e640219
)
FetchContent_MakeAvailable(FirebaseAdminQt)
FirebaseAdminQt5::Core
class FirebaseAdminMessaging; // Forward declare the pointer type
class Root : public Controller
{
public:
    void sendPushNotifications(const QString &message);
    void sendPushNotification(const QString &deviceToken, const QString &message);

private:
    FirebaseAdminMessaging *m_fbAdminMsg;
};
void Root::sendPushNotifications(const QString &message)
{
    QStringList users;
    QRegularExpression re("@([a-zA-Z0-9_]{3,})");
    auto globalMatch = re.globalMatch(message);
    while (globalMatch.hasNext()) {
        QRegularExpressionMatch match = globalMatch.next();
        users << match.captured(1);
    }
    users.removeDuplicates();

    for (const auto &user : qAsConst(users)) {
        APool::database().exec(u"SELECT data->>'firebase_token' FROM users WHERE nick=$1",
                               {
                                   user,
                               }, [=] (AResult &result) {
            auto firstRow = result.begin();
            if (!result.error()) {
                if (result.size() && !result[0][0].toString().isEmpty()) {
                    sendPushNotification(result[0][0].toString(), message);
                }
            } else {
                qWarning() << "Failed to get firebase_token for user" << user << result.errorString();
            }
        }, this);
    }
}
void Root::sendPushNotification(const QString &deviceToken, const QString &message)
{
    FirebaseMessage msg;
    msg.setToken(deviceToken);
    QString title = "ChatApp - New Message";
    msg.setNotification(title, message);
    FirebaseAndroidNotification android;
    android.setTitle(title);
    android.setBody(message);
    msg.setAndroid(android);
    FirebaseAdminReply *reply = m_fbAdminMsg->send(msg);
    connect(reply, &FirebaseAdminReply::finished, this, [=] {
        reply->deleteLater();
        if (reply->error()) {
            qDebug() << "FIREBASE error" << reply->errorCode() << reply->errorMessage();
        } else {
            qDebug() << "FIREBASE success" << reply->messageId();
        }
    });
}
sendPushNotifications(msg);
auto fbApp = new FirebaseAdmin(this);
    fbApp->setAccountCredentialData(R"V0G0N(
<REPLACE WITH SERVICE ACCOUNT JSON>
)V0G0N");
    fbApp->getAccessToken();
    auto messaging = new FirebaseAdminMessaging(fbApp);
    messaging->setApiKey("<REPLACE SERVER API KEY>");

    return true;
FirebaseAdmin::setAccountCredentialData();
FirebaseAdminMessaging::setApiKey();
void Root::sendPushNotification(const QString &deviceToken, const QString &message)
{
    FirebaseMessage msg;
    msg.setToken(deviceToken);
    QString title = "ChatApp - New Message";
    msg.setNotification(title, message);
    FirebaseAndroidNotification android;
    android.setTitle(title);
    android.setBody(message);
    msg.setAndroid(android);
    FirebaseAdminReply *reply = m_fbAdminMsg->send(msg);
    connect(reply, &FirebaseAdminReply::finished, this, [=] {
        reply->deleteLater();
        if (reply->error()) {
            qDebug() << "FIREBASE error" << reply->errorCode() << reply->errorMessage();
        } else {
            qDebug() << "FIREBASE success" << reply->messageId();
        }
    });
}
DISTFILES += android/google-services.json
android: {
    QT += androidextras
}
#org.gradle.caching=true

android.useAndroidX=true
systemProp.firebase_cpp_sdk.dir=<path_to>/firebase_cpp_sdk
android|ios {
    SOURCES += \
        firebase-qt/src/firebaseqtapp.cpp \
        firebase-qt/src/firebaseqtmessaging.cpp \
        firebase-qt/src/firebaseqtabstractmodule.cpp

    HEADERS += \
        firebase-qt/src/firebaseqtabstractmodule.h \
        firebase-qt/src/firebaseqtapp.h \
        firebase-qt/src/firebaseqtapp_p.h \
        firebase-qt/src/firebaseqtmessaging.h
}
# This is the path for the Firebase C++ SDK
GOOGLE_FIREBASE_SDK = $$PWD/../firebase_cpp_sdk

# This is the path for the iOS Firebase SDK
GOOGLE_IOS_FIREBASE_SDK = $$PWD/../Firebase

INCLUDEPATH += $${GOOGLE_FIREBASE_SDK}/include
DEPENDPATH += $${GOOGLE_FIREBASE_SDK}/include

contains(ANDROID_TARGET_ARCH,armeabi-v7a) {
    ANDROID_PACKAGE_SOURCE_DIR = \
        $$PWD/android

    LIBS += -L$${GOOGLE_FIREBASE_SDK}/libs/android/armeabi-v7a/c++/ -lfirebase_app -lfirebase_messaging

    PRE_TARGETDEPS += $${GOOGLE_FIREBASE_SDK}/libs/android/armeabi-v7a/c++/libfirebase_app.a
    PRE_TARGETDEPS += $${GOOGLE_FIREBASE_SDK}/libs/android/armeabi-v7a/c++/libfirebase_messaging.a
}

contains(ANDROID_TARGET_ARCH,arm64-v8a) {
    ANDROID_PACKAGE_SOURCE_DIR = \
        $$PWD/android

    LIBS += -L$${GOOGLE_FIREBASE_SDK}/libs/android/arm64-v8a/c++/ -lfirebase_app -lfirebase_messaging

    PRE_TARGETDEPS += $${GOOGLE_FIREBASE_SDK}/libs/android/arm64-v8a/c++/libfirebase_app.a
    PRE_TARGETDEPS += $${GOOGLE_FIREBASE_SDK}/libs/android/arm64-v8a/c++/libfirebase_messaging.a
}
buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.0'
        classpath 'com.google.gms:google-services:4.3.8'
    }
}

repositories {
    google()
    jcenter()
    flatDir {
        dirs "../../firebase_cpp_sdk/libs/android"
    }
}
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
    implementation 'com.google.firebase:firebase-analytics:17.4.1'
    implementation 'com.google.firebase:firebase-messaging:20.1.7'
    implementation 'com.google.firebase.messaging.cpp:firebase_messaging_cpp@aar'
    implementation 'com.google.android.gms:play-services-base:16.1.0'
    implementation 'androidx.core:core:1.0.1'
}
class Firebase : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString token MEMBER _token NOTIFY tokenChanged)
public:
    explicit Firebase(QObject *parent = nullptr);

    void tokenReceived(const QByteArray &token);
    void messageReceived(const QMap<QString, QString> &data);

Q_SIGNALS:
    void tokenChanged();

private:
    QString _token;
};
#include <QLoggingCategory>

#include "firebase-qt/src/firebaseqtapp.h"
#include "firebase-qt/src/firebaseqtmessaging.h"

Firebase::Firebase(QObject *parent) : QObject(parent)
{
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
    auto firebase = new FirebaseQtApp(this);

    auto messaging = new FirebaseQtMessaging(firebase);
    connect(messaging, &FirebaseQtMessaging::tokenReceived, this, &Firebase::tokenReceived, Qt::QueuedConnection);
    connect(messaging, &FirebaseQtMessaging::messageReceived, this, &Firebase::messageReceived, Qt::QueuedConnection);

    firebase->initialize();
#endif
}

void Firebase::tokenReceived(const QByteArray &token)
{
    qDebug() << "Got Firebase Messaging token" << token;
    _token = QString::fromLatin1(token);
    Q_EMIT tokenChanged();
}

void Firebase::messageReceived(const QMap<QString, QString> &data)
{
    qDebug() << "Got a Push Notification when the app is running" << data;
}
Firebase fb;
    qmlRegisterSingletonInstance("com.kdab", 1, 0, "Firebase", &fb);
import com.kdab 1.0
xhr.send(JSON.stringify({
                                            user_id: settings.user_id,
                                            nick: nick,
                                            fullname: fullname,
                                            firebase_token: Firebase.token
                                        }));

About KDAB


4 Comments

8 - Nov - 2022

Wonderpush

20 - Jun - 2024

Vidya Patil

20 - Jun - 2024

Daniel Nicoletti

20 - Sept - 2024

Jiri