Chat + real-time notifications

Koresha pk_ na sk_ keys zawe mu mushinga wa chatting. Ubutumwa buza ako kanya (SSE) iyo app ifunguye, kandi iyo ifunze buza nka Web Push notification.

← Docs

Uko ikora

  1. Seriveri yawe (ikoresha sk_) ikora chat token ngufi ku mukoresha wayo: POST /api/v1/chat/token.
  2. Browser / Android bikoresha pk_ + token kugira ngo byohereze kandi bakire ubutumwa.
  3. Real-time: connection ya SSE (/api/v1/chat/stream). Iyo idakora, SDK ihita ikoresha polling.
  4. App ifunze: umukoresha ayandikisha Web Push na userId ye (externalId); iyo ubutumwa bwoherejwe, bujya muri notification.

1. Kora token (kuri seriveri yawe)

Ntuzigere ushyira sk_ muri browser cyangwa muri APK. Token ni yo igera kuri client gusa.

node
// Seriveri yawe (Node 18+) β€” ntuyishyire muri client
app.get('/chat-token', requireLogin, async (req, res) => {
  const r = await fetch('https://push.newtalentsg.co.rw/api/v1/chat/token', {
    method: 'POST',
    headers: {
      Authorization: 'Bearer ' + process.env.PUSHHUB_SECRET_KEY,   // sk_...
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ userId: req.user.id, name: req.user.name, ttl: 3600 }),
  });
  const { token } = await r.json();
  res.json({ token });
});

2. Browser / PWA

Shyira SDK, uhuze, wohereze, wakire. enablePush() isaba uruhushya ikanandika subscription.

html
<script src="https://push.newtalentsg.co.rw/chat-sdk.js"></script>
<script>
  PushHubChat.init({
    publicKey: 'pk_xxxxxxxxxxxxxxxx',
    getToken: function () {
      return fetch('/chat-token').then(function (r) { return r.json(); }).then(function (j) { return j.token; });
    },
  }).then(function (chat) {
    chat.on('message', function (m, info) {
      console.log(info.mine ? 'me' : m.senderName || m.senderId, ':', m.text);
    });
    chat.on('open', function (e) { /* umukoresha yakanze notification: fungura room e.roomId */ });

    chat.connect();                                       // real-time (SSE β†’ polling fallback)
    chat.enablePush();                                    // notifications iyo app ifunze
    chat.send({ to: 'userB', text: 'Muraho!', url: '/chat' });
    chat.rooms().then(console.log);
    chat.history(roomId, { limit: 30 }).then(console.log);
    chat.createRoom({ name: 'Team', members: ['userB', 'userC'] });
  });
</script>

Service worker

Ni yo isanzwe ya PushHub β€” nta kindi uhindura. Iyo urupapuro rureba umukoresha, notification ntiyerekanwa (message iza muri app).

/pushhub-sw.js
// /pushhub-sw.js ku rubuga rwawe
importScripts('https://push.newtalentsg.co.rw/pushhub-sw.js');

3. Android

Uburyo bubiri: (a) WebView / Capacitor / TWA β€” koresha chat-sdk.js nk'uko ibyo muri browser biri hejuru; TWA (Chrome) yerekana Web Push notifications ubwayo. (b) Native Kotlin β€” koresha REST + SSE (OkHttp) nk'uko biri hasi. Icyitonderwa: native app ifunze ntishobora kwakira Web Push; kuri yo hakenerwa FCM (Firebase Admin) cyangwa foreground service.

kotlin
// build.gradle: implementation("com.squareup.okhttp3:okhttp:4.12.0")
//                implementation("com.squareup.okhttp3:okhttp-sse:4.12.0")
val client = OkHttpClient.Builder().readTimeout(0, TimeUnit.SECONDS).build()
val base = "https://push.newtalentsg.co.rw"

// 1) token ivuye kuri seriveri yawe (itari sk_ muri APK!)
val token: String = myBackend.getChatToken()

// 2) Kohereza
fun send(to: String, text: String) {
    val body = JSONObject(mapOf("to" to to, "text" to text)).toString()
        .toRequestBody("application/json".toMediaType())
    client.newCall(Request.Builder().url("$base/api/v1/chat/send")
        .header("Authorization", "Bearer $token").post(body).build()).execute().close()
}

// 3) Real-time (SSE). Seriveri ifunga nyuma y'~50s: ongera uhuze na since = cursor
var since = 0L
fun connect() {
    val url = "$base/api/v1/chat/stream?token=$token&key=pk_xxxxxxxx" + if (since > 0) "&since=$since" else ""
    EventSources.createFactory(client).newEventSource(
        Request.Builder().url(url).build(),
        object : EventSourceListener() {
            override fun onEvent(es: EventSource, id: String?, type: String?, data: String) {
                if (type == "message") {
                    val m = JSONObject(data)
                    since = maxOf(since, m.getLong("createdAt"))
                    // show message in UI / local notification
                } else if (type == "ready" && since == 0L) {
                    since = JSONObject(data).getLong("cursor")
                }
            }
            override fun onClosed(es: EventSource) = connect()
            override fun onFailure(es: EventSource, t: Throwable?, r: Response?) {
                // koresha GET /api/v1/chat/poll?since=… nka fallback, cyangwa wongere ugerageze
            }
        })
}

API reference

POST/api/v1/chat/tokensk_{ userId, name?, ttl? } β†’ { token, expiresAt }
POST/api/v1/chat/sendtoken{ to | roomId, text, url?, notify? } β†’ { message, push }
GET/api/v1/chat/roomstoken→ { rooms }
POST/api/v1/chat/roomstoken{ name, members[] } β†’ { room }
GET/api/v1/chat/messagestoken?roomId&limit&before β†’ { messages }
GET/api/v1/chat/streamtoken?token&key&since β†’ SSE (ready, message, bye)
GET/api/v1/chat/polltoken?since β†’ { messages, cursor }

Ibyitonderwa

  • userId: inyuguti, imibare na _ . : @ - gusa (max 128).
  • Ubutumwa: max inyuguti 4000. Group: abanyamuryango 2–100.
  • Token ikoresha HMAC ya sk_ β€” guhindura sk_ bihagarika tokens zose zikiriho.
  • Rules za Firestore zirafunguye (reba README) β€” mbere yo gukoresha mu by'ukuri zifunge kuko ubutumwa bubikwa muri Firestore.