Dla aplikacji
API i SDK czatu dla Twojej aplikacji
Dodaj czat do Next.js, Laravela, Django i każdego innego stacku: rozmowy we dwoje i czaty grupowe, ze wskaźnikiem pisania, statusem online, potwierdzeniami odczytu, reakcjami i plikami. Gotowy czat działa w przeglądarce od razu, wiadomości trafiają natychmiast do wszystkich uczestników rozmowy, a Twój serwer zapisuje je we własnej bazie danych.
Albo wypróbuj demo na żywo: mały sklep, w którym klient pisze do sklepu, każdy we własnym oknie.
Najlepsze ceny za WebSockets, nielimitowane rozmowy 1 na 1 z serwerami TURN na całym świecie oraz rozmowy grupowe i transmisje na żywo z pakietem w cenie. Od $11.99 miesięcznie za 1000 jednoczesnych połączeń przy rozliczeniu rocznym lub $14.99 przy rozliczeniu miesięcznym.
Next.js na serwerze i React na stronie.
// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
const chat = {
emit: [ 'message', 'typing', 'read', 'reaction' ],
webhook: [ 'message', 'reaction' ],
history: 50,
};
// Two people, such as chat:34:42: the two in its name alone.
realtime.room( 'chat:{pair}', chat );
// A group, such as group:7: its members, who see each other.
realtime.room(
'group:{id}',
( user, { id } ) => isMemberOf( id, user ),
{ ...chat, presence: true },
);// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
const chat = {
emit: [ 'message', 'typing', 'read', 'reaction' ],
webhook: [ 'message', 'reaction' ],
history: 50,
};
// Two people, such as chat:34:42: the two in its name alone.
realtime.room( 'chat:{pair}', chat );
// A group, such as group:7: its members, who see each other.
realtime.room(
'group:{id}',
( user, { id } ) => isMemberOf( id, user ),
{ ...chat, presence: true },
);// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
const chat = {
emit: [ 'message', 'typing', 'read', 'reaction' ],
webhook: [ 'message', 'reaction' ],
history: 50,
};
// Two people, such as chat:34:42: the two in its name alone.
realtime.room( 'chat:{pair}', chat );
// A group, such as group:7: its members, who see each other.
realtime.room(
'group:{id}',
( user, { id } ) => isMemberOf( id, user ),
{ ...chat, presence: true },
);$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
$chat = [
'emit' => [ 'message', 'typing', 'read', 'reaction' ],
'webhook' => [ 'message', 'reaction' ],
'history' => 50,
];
// Two people, such as chat:34:42: the two in its name alone.
$realtime->room( 'chat:{pair}', null, $chat );
// A group, such as group:7: its members, who see each other.
$realtime->room(
'group:{id}',
fn ( $user, array $p ) => is_member_of( $p['id'], $user ),
[ ...$chat, 'presence' => true ],
);
} );// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
$chat = [
'emit' => [ 'message', 'typing', 'read', 'reaction' ],
'webhook' => [ 'message', 'reaction' ],
'history' => 50,
];
// Two people, such as chat:34:42: the two in its name alone.
$realtime->room( 'chat:{pair}', null, $chat );
// A group, such as group:7: its members, who see each other.
$realtime->room(
'group:{id}',
fn ( $user, array $p ) => is_member_of( $p['id'], $user ),
[ ...$chat, 'presence' => true ],
);# What every chat carries: what pages send, what your webhook
# gets to keep, and the last 50 for a page that reconnects.
chat = {
"emit": ["message", "typing", "read", "reaction"],
"webhook": ["message", "reaction"],
"history": 50,
}
# Two people, such as chat:34:42: the two in its name alone.
realtime.room("chat:{pair}", **chat)
# A group, such as group:7: its members, who see each other.
realtime.room(
"group:{id}",
lambda user, p: is_member_of(p["id"], user),
presence=True,
**chat,
)# What every chat carries: what pages send, what your webhook
# gets to keep, and the last 50 for a page that reconnects.
chat = {
"emit": ["message", "typing", "read", "reaction"],
"webhook": ["message", "reaction"],
"history": 50,
}
# Two people, such as chat:34:42: the two in its name alone.
realtime.room("chat:{pair}", **chat)
# A group, such as group:7: its members, who see each other.
realtime.room(
"group:{id}",
lambda user, p: is_member_of(p["id"], user),
presence=True,
**chat,
)# What every chat carries: what pages send, what your webhook
# gets to keep, and the last 50 for a page that reconnects.
chat = {
"emit": ["message", "typing", "read", "reaction"],
"webhook": ["message", "reaction"],
"history": 50,
}
# Two people, such as chat:34:42: the two in its name alone.
realtime.room("chat:{pair}", **chat)
# A group, such as group:7: its members, who see each other.
realtime.room(
"group:{id}",
lambda user, p: is_member_of(p["id"], user),
presence=True,
**chat,
)// Your /auth route asks this for each room a page wants.
func roomRule(room, user string) (*wordplus.Room, string) {
chat := wordplus.Room{
Emit: []string{"message", "typing", "read", "reaction"},
Webhook: []string{"message", "reaction"},
History: 50,
Info: profile(user),
}
part := strings.Split(room, ":")
// Two people, such as chat:34:42: the two in its name alone.
if len(part) == 3 && part[0] == "chat" {
if user != part[1] && user != part[2] {
return nil, "forbidden"
}
return &chat, ""
}
// A group, such as group:7: its members, who see each other.
if len(part) == 2 && part[0] == "group" {
if !isMemberOf(part[1], user) {
return nil, "forbidden"
}
chat.Presence = true
return &chat, ""
}
return nil, "no_rule"
}Hooki i komponenty dla każdej aplikacji React, z dowolnym serwerem powyżej.
import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list><chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>
<script type="module">
// The chat, who is online and typing, with no calls.
await window.Echo.connector.rt.ui();
</script>'use client'; // in Next.js
import { Chat, RealtimeUi } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
return (
<>
<RealtimeUi />
<div style={ { height: 520 } }>
<Chat room="chat:34:42" to={ 34 } name="Ann" />
</div>
</>
);
}<script setup>
import { watchEffect } from 'vue';
import { useRealtime } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const rt = useRealtime();
watchEffect( () => rt.value?.ui() );
</script>
<!-- isCustomElement for this tag, in vite.config.js -->
<template>
<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>
</template><script>
import { useRealtime } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const rt = useRealtime();
$effect( () => { rt.current?.ui(); } );
</script>
<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>import {
Component, CUSTOM_ELEMENTS_SCHEMA, effect,
} from '@angular/core';
import { injectRealtime } from '@wordplus/realtime/angular';
@Component( {
selector: 'app-conversation',
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
template: `<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>`,
} )
export class Conversation {
readonly rt = injectRealtime();
constructor() {
effect( () => void this.rt()?.ui() );
}
}// No ready-made chat on iOS: your own, on the same room.
let chat = rt.join("chat:34:42")
chat.on("message") { data, meta in
draw(meta.from, data["text"]?.string ?? "")
}
try await chat.emitWithAck("message", ["text": "Hi Ann"])// No ready-made chat on Android: your own, on the same room.
val chat = rt.join("chat:34:42")
chat.on("message") { data, meta ->
draw(meta.from, data.jsonObject["text"])
}
chat.emitWithAck("message", buildJsonObject { put("text", "Hi") })import { useRoom } from '@wordplus/realtime/react';
// No ready-made chat in React Native: your own, on the room.
export function Conversation() {
const chat = useRoom( 'chat:34:42', {
message: ( data, meta ) => draw( meta.from, data.text ),
} );
const send = ( text ) => chat.emitWithAck( 'message', { text } );
return <SendBox onSend={ send } />;
}// No ready-made chat in Flutter: your own, on the same room.
final chat = rt.join('chat:34:42');
chat.on('message', (data, meta) => draw(meta.from, data['text']));
await chat.emitWithAck('message', {'text': 'Hi Ann'});
Twoje wiadomości
Twoje wiadomości zostają w Twojej bazie danych
My przenosimy rozmowę, a Twój serwer ją przechowuje. Pokój trzyma swoje ostatnie zdarzenia przez około pięć minut, tylko po to, by strona, która łączy się ponownie, niczego nie przegapiła, a Twoja baza danych trzyma samą rozmowę.
Od razu, na każdym urządzeniu
Wiadomość w chwili wysłania przechodzi przez nasze serwery ze strony na stronę, bez żądania do Twojego serwera, do każdej karty i aplikacji wszystkich uczestników rozmowy.
Przechowywane przez Twój serwer
Twój webhook dostaje każdą wiadomość i reakcję w chwili wysłania i zapisuje je we własnej bazie danych. Twoja własna trasa daje czatowi historię przy otwarciu, więc rozmowę możesz przeszukiwać, moderować i wyświetlać ponownie.
Zapieczętowane w drodze
Prywatna rozmowa podróżuje zapieczętowana kluczami, które tworzy Twój serwer: jej wiadomości, historia i lista uczestników. Chmura przenosi ją bez możliwości odczytu.
Decyduje Twój serwer
Zbuduj czat, zadanie po zadaniu
Czat to pokój: chat:34:42, gdy Ben pisze do Ann, która sprzedaje, albo group:7 dla grupy. Jedna reguła na Twoim serwerze mówi, kto w nim jest, a strony wysyłają sobie przez niego wiadomości, pisanie i potwierdzenia odczytu. Oto oba, od gotowego czatu po rozmowę.
Next.js na serwerze i React na stronie.
Dodaj gotowy czat
Jedna reguła na Twoim serwerze dla każdego rodzaju czatu: czat we dwoje wpuszcza dwie osoby z jego nazwy, a grupa swoich członków, według Twoich własnych danych. Potem czat trafia na stronę, ze wskaźnikiem pisania, potwierdzeniami odczytu i reakcjami. isMemberOf to Twoje własne wyszukiwanie.
// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
const chat = {
emit: [ 'message', 'typing', 'read', 'reaction' ],
webhook: [ 'message', 'reaction' ],
history: 50,
};
// Two people, such as chat:34:42: the two in its name alone.
realtime.room( 'chat:{pair}', chat );
// A group, such as group:7: its members, who see each other.
realtime.room(
'group:{id}',
( user, { id } ) => isMemberOf( id, user ),
{ ...chat, presence: true },
);// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
const chat = {
emit: [ 'message', 'typing', 'read', 'reaction' ],
webhook: [ 'message', 'reaction' ],
history: 50,
};
// Two people, such as chat:34:42: the two in its name alone.
realtime.room( 'chat:{pair}', chat );
// A group, such as group:7: its members, who see each other.
realtime.room(
'group:{id}',
( user, { id } ) => isMemberOf( id, user ),
{ ...chat, presence: true },
);// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
const chat = {
emit: [ 'message', 'typing', 'read', 'reaction' ],
webhook: [ 'message', 'reaction' ],
history: 50,
};
// Two people, such as chat:34:42: the two in its name alone.
realtime.room( 'chat:{pair}', chat );
// A group, such as group:7: its members, who see each other.
realtime.room(
'group:{id}',
( user, { id } ) => isMemberOf( id, user ),
{ ...chat, presence: true },
);$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
$chat = [
'emit' => [ 'message', 'typing', 'read', 'reaction' ],
'webhook' => [ 'message', 'reaction' ],
'history' => 50,
];
// Two people, such as chat:34:42: the two in its name alone.
$realtime->room( 'chat:{pair}', null, $chat );
// A group, such as group:7: its members, who see each other.
$realtime->room(
'group:{id}',
fn ( $user, array $p ) => is_member_of( $p['id'], $user ),
[ ...$chat, 'presence' => true ],
);
} );// What every chat carries: what pages send, what your webhook
// gets to keep, and the last 50 for a page that reconnects.
$chat = [
'emit' => [ 'message', 'typing', 'read', 'reaction' ],
'webhook' => [ 'message', 'reaction' ],
'history' => 50,
];
// Two people, such as chat:34:42: the two in its name alone.
$realtime->room( 'chat:{pair}', null, $chat );
// A group, such as group:7: its members, who see each other.
$realtime->room(
'group:{id}',
fn ( $user, array $p ) => is_member_of( $p['id'], $user ),
[ ...$chat, 'presence' => true ],
);# What every chat carries: what pages send, what your webhook
# gets to keep, and the last 50 for a page that reconnects.
chat = {
"emit": ["message", "typing", "read", "reaction"],
"webhook": ["message", "reaction"],
"history": 50,
}
# Two people, such as chat:34:42: the two in its name alone.
realtime.room("chat:{pair}", **chat)
# A group, such as group:7: its members, who see each other.
realtime.room(
"group:{id}",
lambda user, p: is_member_of(p["id"], user),
presence=True,
**chat,
)# What every chat carries: what pages send, what your webhook
# gets to keep, and the last 50 for a page that reconnects.
chat = {
"emit": ["message", "typing", "read", "reaction"],
"webhook": ["message", "reaction"],
"history": 50,
}
# Two people, such as chat:34:42: the two in its name alone.
realtime.room("chat:{pair}", **chat)
# A group, such as group:7: its members, who see each other.
realtime.room(
"group:{id}",
lambda user, p: is_member_of(p["id"], user),
presence=True,
**chat,
)# What every chat carries: what pages send, what your webhook
# gets to keep, and the last 50 for a page that reconnects.
chat = {
"emit": ["message", "typing", "read", "reaction"],
"webhook": ["message", "reaction"],
"history": 50,
}
# Two people, such as chat:34:42: the two in its name alone.
realtime.room("chat:{pair}", **chat)
# A group, such as group:7: its members, who see each other.
realtime.room(
"group:{id}",
lambda user, p: is_member_of(p["id"], user),
presence=True,
**chat,
)// Your /auth route asks this for each room a page wants.
func roomRule(room, user string) (*wordplus.Room, string) {
chat := wordplus.Room{
Emit: []string{"message", "typing", "read", "reaction"},
Webhook: []string{"message", "reaction"},
History: 50,
Info: profile(user),
}
part := strings.Split(room, ":")
// Two people, such as chat:34:42: the two in its name alone.
if len(part) == 3 && part[0] == "chat" {
if user != part[1] && user != part[2] {
return nil, "forbidden"
}
return &chat, ""
}
// A group, such as group:7: its members, who see each other.
if len(part) == 2 && part[0] == "group" {
if !isMemberOf(part[1], user) {
return nil, "forbidden"
}
chat.Presence = true
return &chat, ""
}
return nil, "no_rule"
}Hooki i komponenty dla każdej aplikacji React, z dowolnym serwerem powyżej.
import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat, who is online and typing, with no calls.
await rt.ui();
// And in the page of Ben, writing to Ann:
// <chat-room room="chat:34:42" to="34" name="Ann"
// style="height: 520px"></chat-room>
//
// And in a group, beside who is in it now:
// <chat-room room="group:7"></chat-room>
// <online-list room="group:7" title="In the group"></online-list>{{-- In the page of Ben, writing to Ann. --}}
<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>
<script type="module">
// The chat, who is online and typing, with no calls.
await window.Echo.connector.rt.ui();
</script>'use client'; // in Next.js
import { Chat, RealtimeUi } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
// In the page of Ben, writing to Ann.
export function Conversation() {
return (
<>
<RealtimeUi />
<div style={ { height: 520 } }>
<Chat room="chat:34:42"
to={ 34 }
name="Ann" />
</div>
</>
);
}<script setup>
import { watchEffect } from 'vue';
import { useRealtime } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat, who is online and typing, with no calls.
watchEffect( () => rt.value?.ui() );
</script>
<!-- isCustomElement for this tag, in vite.config.js. In the page of Ben, writing to Ann. -->
<template>
<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>
</template><script>
import { useRealtime } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat, who is online and typing, with no calls.
$effect( () => { rt.current?.ui(); } );
</script>
<!-- In the page of Ben, writing to Ann. -->
<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
// realtime.ts, one connection for the whole app:
// export const realtime = connect();
import { realtime } from './realtime';
@Component( {
selector: 'app-conversation',
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
template: `
<!-- In the page of Ben, writing to Ann. -->
<chat-room room="chat:34:42" to="34" name="Ann"
style="height: 520px"></chat-room>
`,
} )
export class Conversation {
async ngOnInit() {
const rt = await realtime;
// The chat, who is online and typing, with no calls.
await rt.ui();
}
}Wyślij i zapisz wiadomość
Gotowy czat robi to sam. Na własnym ekranie strona wysyła wiadomość do pokoju i wszyscy w nim dostają ją od razu. Twój webhook zapisuje ją pod jej id i powiadamia drugą osobę, na jakiejkolwiek stronie jest. saveMessage to Twoja własna funkcja.
// Each message pages send, kept once by its id, however often the webhook brings it.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
await saveMessage( { id: event_id, room, from, text: data.text, at } );
// A notice to the other of the two, on whatever page or app they have open.
const [ kind, a, b ] = room.split( ':' );
if ( kind === 'chat' ) {
const to = String( from ) === a ? b : a;
await realtime.toUser( to ).emit( 'new_message', { room, from, text: data.text } );
}
} );// Each message pages send, kept once by its id, however often the webhook brings it.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
await saveMessage( { id: event_id, room, from, text: data.text, at } );
// A notice to the other of the two, on whatever page or app they have open.
const [ kind, a, b ] = room.split( ':' );
if ( kind === 'chat' ) {
const to = String( from ) === a ? b : a;
await realtime.toUser( to ).emit( 'new_message', { room, from, text: data.text } );
}
} );// Each message pages send, kept once by its id, however often the webhook brings it.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
await saveMessage( { id: event_id, room, from, text: data.text, at } );
// A notice to the other of the two, on whatever page or app they have open.
const [ kind, a, b ] = room.split( ':' );
if ( kind === 'chat' ) {
const to = String( from ) === a ? b : a;
await realtime.toUser( to ).emit( 'new_message', { room, from, text: data.text } );
}
} );$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// Each message pages send, kept once by its id, however often the webhook brings it.
$realtime->on( 'message', function ( array $e ) use ( $realtime ) {
Message::updateOrCreate( [ 'id' => $e['event_id'] ], [ 'room' => $e['room'], 'from' => $e['from'], 'text' => $e['data']['text'] ] );
// A notice to the other of the two, on whatever page or app they have open.
[ $kind, $a, $b ] = explode( ':', $e['room'] ) + [ '', '', '' ];
if ( 'chat' === $kind ) {
$to = (string) $e['from'] === $a ? $b : $a;
$realtime->toUser( $to )->emit( 'new_message', [ 'room' => $e['room'], 'from' => $e['from'], 'text' => $e['data']['text'] ] );
}
} );
} );// Each message pages send, kept once by its id, however often the webhook brings it.
$realtime->on( 'message', function ( array $e ) use ( $realtime ) {
save_message( $e['event_id'], $e['room'], $e['from'], $e['data']['text'], $e['at'] );
// A notice to the other of the two, on whatever page or app they have open.
[ $kind, $a, $b ] = explode( ':', $e['room'] ) + [ '', '', '' ];
if ( 'chat' === $kind ) {
$to = (string) $e['from'] === $a ? $b : $a;
$realtime->toUser( $to )->emit( 'new_message', [ 'room' => $e['room'], 'from' => $e['from'], 'text' => $e['data']['text'] ] );
}
} );# Each message pages send, kept once by its id, however often the webhook brings it.
def keep_message(e):
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"])
# A notice to the other of the two, on whatever page or app they have open.
kind, a, b = (e["room"].split(":") + ["", "", ""])[:3]
if kind == "chat":
to = b if str(e["from"]) == a else a
realtime.to_user(to).emit("new_message", {"room": e["room"], "from": e["from"], "text": e["data"]["text"]})
realtime.on("message", keep_message)# Each message pages send, kept once by its id, however often the webhook brings it.
def keep_message(e):
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"])
# A notice to the other of the two, on whatever page or app they have open.
kind, a, b = (e["room"].split(":") + ["", "", ""])[:3]
if kind == "chat":
to = b if str(e["from"]) == a else a
realtime.to_user(to).emit("new_message", {"room": e["room"], "from": e["from"], "text": e["data"]["text"]})
realtime.on("message", keep_message)# Each message pages send, kept once by its id, however often the webhook brings it.
def keep_message(e):
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"])
# A notice to the other of the two, on whatever page or app they have open.
kind, a, b = (e["room"].split(":") + ["", "", ""])[:3]
if kind == "chat":
to = b if str(e["from"]) == a else a
realtime.to_user(to).emit("new_message", {"room": e["room"], "from": e["from"], "text": e["data"]["text"]})
realtime.on("message", keep_message)// In your webhook route: app.Webhook() checks it and opens what each page sent.
for _, event := range events {
if event["type"] != "emit" || event["event"] != "message" {
continue
}
room, _ := event["room"].(string)
from := fmt.Sprint(event["from"])
data, _ := event["data"].(map[string]any)
// Kept once, by the id the pages saw, however often the webhook brings it.
saveMessage(event["event_id"], room, from, data["text"], event["at"])
// A notice to the other of the two, on whatever page or app they have open.
if part := strings.Split(room, ":"); len(part) == 3 && part[0] == "chat" {
to := part[1]
if from == part[1] {
to = part[2]
}
app.EmitToUser(to, "new_message", map[string]any{"room": room, "from": from, "text": data["text"]})
}
}Hooki i komponenty dla każdej aplikacji React, z dowolnym serwerem powyżej.
import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );const rt = window.Echo.connector.rt; // the connection Echo made
const chat = rt.join( 'chat:34:42' );
// Every page in the conversation gets it at once, the sender's other tabs too.
chat.on( 'message', ( data, meta ) => draw( meta.id, meta.from, data.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const text = 'Has my order left yet?';
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, rt.user, text ); // this tab does not get its own back
// On any page: a message in a chat that is not open there.
rt.on( 'new_message', ( m ) => showNotice( m.room, m.text ) );'use client'; // in Next.js
import { useRoom, useUserEvent } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
const chat = useRoom( 'chat:34:42', {
message: ( data, meta ) => draw( meta.id, meta.from, data.text ),
} );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const send = async ( text ) => {
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, 'me', text ); // this tab does not get its own back
};
return <SendBox onSend={ send } />;
}
// In your layout: a message in a chat that is not open there.
export function NewMessages() {
useUserEvent( 'new_message', ( m ) => showNotice( m.room, m.text ) );
return null;
}<script setup>
import { useRoom, useUserEvent } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const { emitWithAck } = useRoom( 'chat:34:42', {
message: ( data, meta ) => draw( meta.id, meta.from, data.text ),
} );
// A message in a chat that is not open here.
useUserEvent( 'new_message', ( m ) => showNotice( m.room, m.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const send = async ( text ) => {
const { id } = await emitWithAck( 'message', { text } );
draw( id, 'me', text );
};
</script>
<template>
<SendBox @send="send" />
</template><script>
import { useRoom, useUserEvent } from '@wordplus/realtime/svelte';
import SendBox from './SendBox.svelte';
// provideRealtime() once, in your root component.
const chat = useRoom( 'chat:34:42', {
message: ( data, meta ) => draw( meta.id, meta.from, data.text ),
} );
// A message in a chat that is not open here.
useUserEvent( 'new_message', ( m ) => showNotice( m.room, m.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const send = async ( text ) => {
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, 'me', text );
};
</script>
<SendBox onsend={ send } />import { Component } from '@angular/core';
import { injectRoom, injectUserEvent } from '@wordplus/realtime/angular';
import { SendBox } from './send-box';
// provideRealtime() once, in your application's providers.
@Component( {
selector: 'app-conversation',
imports: [ SendBox ],
template: '<app-send-box (send)="send( $event )" />',
} )
export class Conversation {
readonly chat = injectRoom( 'chat:34:42', {
message: ( data, meta ) => draw( meta.id, meta.from, data.text ),
} );
constructor() {
// A message in a chat that is not open here.
injectUserEvent( 'new_message', ( m ) => showNotice( m.room, m.text ) );
}
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
async send( text: string ) {
const { id } = await this.chat.emitWithAck( 'message', { text } );
draw( id, 'me', text );
}
}let chat = rt.join("chat:34:42")
// Every page and app in the conversation gets it at once.
chat.on("message") { data, meta in draw(meta.id, meta.from, data["text"]?.string ?? "") }
// Checked, kept for a reconnect and sent on. ack.id is the one your webhook gets.
let ack = try await chat.emitWithAck("message", ["text": "Has my order left yet?"])
// A message in a chat that is not open here.
rt.on("new_message") { m, _ in showNotice(m["room"]?.string ?? "", m["text"]?.string ?? "") }val chat = rt.join("chat:34:42")
// Every page and app in the conversation gets it at once.
chat.on("message") { data, meta -> draw(meta.id, meta.from, data.jsonObject["text"]?.jsonPrimitive?.content ?: "") }
// Checked, kept for a reconnect and sent on. ack.id is the one your webhook gets.
val ack = chat.emitWithAck("message", buildJsonObject { put("text", "Has my order left yet?") })
// A message in a chat that is not open here.
rt.on("new_message") { m, _ -> showNotice(m.jsonObject["room"]?.jsonPrimitive?.content ?: "", m.jsonObject["text"]?.jsonPrimitive?.content ?: "") }import { useRoom, useUserEvent } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
const chat = useRoom( 'chat:34:42', {
message: ( data, meta ) => draw( meta.id, meta.from, data.text ),
} );
// A message in a chat that is not open here.
useUserEvent( 'new_message', ( m ) => showNotice( m.room, m.text ) );
// Checked, kept for a reconnect and sent on. id is the one your webhook gets.
const send = async ( text ) => {
const { id } = await chat.emitWithAck( 'message', { text } );
draw( id, 'me', text );
};
return <SendBox onSend={ send } />;
}final chat = rt.join('chat:34:42');
// Every page and app in the conversation gets it at once.
chat.on('message', (data, meta) => draw(meta.id, meta.from, data['text']));
// Checked, kept for a reconnect and sent on. ack.id is the one your webhook gets.
final ack = await chat.emitWithAck('message', {'text': 'Has my order left yet?'});
// A message in a chat that is not open here.
rt.on('new_message', (m, _) => showNotice(m['room'], m['text']));Kto jest online i kto pisze
Pisanie to zdarzenie ulotne, nigdy nie kolejkowane ani nie przechowywane. Kto jest online działa w każdym miejscu Twojej aplikacji, a grupa pokazuje, kto jest w niej teraz. Gotowy czat pokazuje jedno i drugie, a gotowa lista pokazuje osoby z grupy.
Hooki i komponenty dla każdej aplikacji React, z dowolnym serwerem powyżej.
import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );const rt = window.Echo.connector.rt; // the connection Echo made
const chat = rt.join( 'chat:34:42' );
// Typing is volatile: dropped rather than queued while offline, and never kept.
input.oninput = () => chat.volatile.emit( 'typing', { on: input.value !== '' } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );
// Ann online now, or when she was last, on any page or app of hers.
rt.online.watch( [ 34 ] ).on( 'change', ( { id, online, at } ) => showOnline( id, online, at ) );
// Who is in the group now, as its rule says presence: true.
const group = rt.join( 'group:7' );
group.on( 'joined', () => showMembers( [ ...group.members ] ) ); // [ id, info ]
group.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
group.on( 'leave', ( { id } ) => removeMember( id ) );'use client'; // in Next.js
import { OnlineList, useOnline, usePresence, useRoom, useTyping } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
const chat = useRoom( 'chat:34:42' );
const typing = useTyping( chat ); // the ids typing now, gone as they stop
const { online, lastSeen } = useOnline( [ 34 ] ); // Ann online, or when she was last
// Volatile: dropped rather than queued while offline, and never kept.
const onKey = () => chat.room?.volatile.emit( 'typing', { on: true } );
// draw them your way
}
// Who is in the group now: [ { id, info } ], or the ready-made list.
export function GroupMembers() {
const members = usePresence( 'group:7' );
return <OnlineList room="group:7" title="In the group" />;
}<script setup>
import { useOnline, usePresence, useRoom, useTyping } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const chat = useRoom( 'chat:34:42' );
const typing = useTyping( chat ); // the ids typing now, gone as they stop
const { online, lastSeen } = useOnline( [ 34 ] ); // Ann online, or when she was last
const members = usePresence( 'group:7' ); // who is in the group now: [ { id, info } ]
// Volatile: dropped rather than queued while offline, and never kept.
const onKey = () => chat.room.value?.volatile.emit( 'typing', { on: true } );
</script><script>
import { useOnline, usePresence, useRoom, useTyping } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const chat = useRoom( 'chat:34:42' );
const typing = useTyping( chat ); // typing.current: the ids typing now
const status = useOnline( [ 34 ] ); // status.online[ 34 ], status.lastSeen[ 34 ]
const members = usePresence( 'group:7' ); // members.current: who is in the group now
// Volatile: dropped rather than queued while offline, and never kept.
const onKey = () => chat.room?.volatile.emit( 'typing', { on: true } );
</script>import { Component } from '@angular/core';
import { injectOnline, injectPresence, injectRoom, injectTyping } from '@wordplus/realtime/angular';
// provideRealtime() once, in your application's providers.
@Component( {
selector: 'app-conversation',
template: `
<p>Ann is {{ status.online()[ 34 ] ? 'online' : 'away' }}</p>
@if ( typing().length > 0 ) { <p>Typing…</p> }
<input (input)="chat.room()?.volatile?.emit( 'typing', { on: true } )">
`,
} )
export class Conversation {
readonly chat = injectRoom( 'chat:34:42' );
readonly typing = injectTyping( this.chat ); // the ids typing now, gone as they stop
readonly status = injectOnline( [ 34 ] ); // Ann online, or when she was last
readonly members = injectPresence( 'group:7' ); // who is in the group now
}let chat = rt.join("chat:34:42")
// Typing is volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit("typing", ["on": true])
chat.on("typing") { data, meta in showTyping(meta.from, data["on"]?.bool ?? false) }
// Ann online now, or when she was last.
rt.online.watch(["34"]).on("change") { change in showOnline(change["id"]?.string, change["online"]?.bool ?? false) }
// Who is in the group now, as its rule says presence: true.
let group = rt.join("group:7")
group.on("join") { member, _ in addMember(member["id"]?.string ?? "") }
group.on("leave") { member, _ in removeMember(member["id"]?.string ?? "") }val chat = rt.join("chat:34:42")
// Typing is volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit("typing", buildJsonObject { put("on", true) })
chat.on("typing") { data, meta -> showTyping(meta.from, data.jsonObject["on"]) }
// Ann online now, or when she was last.
rt.online.watch(listOf("34")).on("change") { change -> showOnline(change.jsonObject["id"], change.jsonObject["online"]) }
// Who is in the group now, as its rule says presence: true.
val group = rt.join("group:7")
group.on("join") { member, _ -> addMember(member.jsonObject["id"]) }
group.on("leave") { member, _ -> removeMember(member.jsonObject["id"]) }import { useOnline, usePresence, useRoom, useTyping } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
const chat = useRoom( 'chat:34:42' );
const typing = useTyping( chat ); // the ids typing now, gone as they stop
const { online, lastSeen } = useOnline( [ 34 ] ); // Ann online, or when she was last
const members = usePresence( 'group:7' ); // who is in the group now
// Volatile: dropped rather than queued while offline, and never kept.
const onChangeText = () => chat.room?.volatile.emit( 'typing', { on: true } );
// draw them your way
}final chat = rt.join('chat:34:42');
// Typing is volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit('typing', {'on': true});
chat.on('typing', (data, meta) => showTyping(meta.from, data['on']));
// Ann online now, or when she was last.
rt.online.watch(['34']).on('change', (change) => showOnline(change['id'], change['online']));
// Who is in the group now, as its rule says presence: true.
final group = rt.join('group:7');
group.on('join', (member, _) => addMember(member['id']));
group.on('leave', (member, _) => removeMember(member['id']));Historia przy otwarciu czatu
Rozmowa jest w Twojej bazie danych, nie u nas. Własna trasa zwraca jej 50 najnowszych wiadomości, a przy przewijaniu w górę 50 wcześniejszych, tym, których wpuszcza Twoja reguła. Pokój uzupełnia to, co przyszło później. messagesOf to Twoje własne zapytanie.
// GET /api/messages?room=chat:34:42, and &before=<id> as the reader scrolls up.
export async function GET( request: Request ) {
const me = await currentUserId();
const query = new URL( request.url ).searchParams;
const room = query.get( 'room' ) ?? '';
// The room's own rule: whoever may be in the conversation may read it.
if ( ! me || ! await realtime.mayJoin( room, me ) ) {
return new Response( null, { status: 403 } );
}
// Your own query: the newest 50, or the 50 before that id, oldest first,
// as { messages: [ { id, from, text, at, files, reactions } ], more }.
return Response.json( await messagesOf( room, query.get( 'before' ) ) );
}// GET /api/messages?room=chat:34:42, and &before=<id> as the reader scrolls up.
app.get( '/api/messages', async ( req, res ) => {
const me = userOf( req );
const { room = '', before } = req.query;
// The room's own rule: whoever may be in the conversation may read it.
if ( ! me || ! await realtime.mayJoin( room, me ) ) {
return res.sendStatus( 403 );
}
// Your own query: the newest 50, or the 50 before that id, oldest first,
// as { messages: [ { id, from, text, at, files, reactions } ], more }.
res.json( await messagesOf( room, before ) );
} );// In your createServer(): GET /api/messages?room=chat:34:42, and &before=<id>.
if ( url.pathname === '/api/messages' ) {
const me = userOf( req );
const room = url.searchParams.get( 'room' ) ?? '';
// The room's own rule: whoever may be in the conversation may read it.
if ( ! me || ! await realtime.mayJoin( room, me ) ) {
res.writeHead( 403 );
return res.end();
}
// Your own query: the newest 50, or the 50 before that id, oldest first,
// as { messages: [ { id, from, text, at, files, reactions } ], more }.
const page = await messagesOf( room, url.searchParams.get( 'before' ) );
res.writeHead( 200, { 'Content-Type': 'application/json' } );
return res.end( JSON.stringify( page ) );
}use Illuminate\Http\Request;
use WordPlus\Realtime\Laravel\Facades\Realtime;
// GET /api/messages?room=chat:34:42, and &before=<id> as the reader scrolls up.
Route::get( '/api/messages', function ( Request $request ) {
$room = (string) $request->query( 'room' );
// The room's own rule: whoever may be in the conversation may read it.
abort_unless( Realtime::mayJoin( $room, $request->user()->id ), 403 );
// Your own query: the newest 50, or the 50 before that id, oldest first,
// as [ 'messages' => [ [ 'id', 'from', 'text', 'at', 'files', 'reactions' ] ], 'more' ].
return messages_of( $room, $request->query( 'before' ) );
} )->middleware( 'auth' );require __DIR__ . '/../../src/realtime.php';
// GET /api/messages?room=chat:34:42, and &before=<id> as the reader scrolls up.
$me = current_user_id();
$room = (string) ( $_GET['room'] ?? '' );
// The room's own rule: whoever may be in the conversation may read it.
if ( ! $me || ! $realtime->mayJoin( $room, $me ) ) {
http_response_code( 403 );
exit;
}
// Your own query: the newest 50, or the 50 before that id, oldest first,
// as [ 'messages' => [ [ 'id', 'from', 'text', 'at', 'files', 'reactions' ] ], 'more' ].
header( 'Content-Type: application/json' );
echo json_encode( messages_of( $room, $_GET['before'] ?? null ) );from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden, JsonResponse
from .realtime import realtime
# In urls.py: path("api/messages", views.messages)
@login_required
def messages(request):
room = request.GET.get("room", "")
# The room's own rule: whoever may be in the conversation may read it.
if not realtime.may_join(room, request.user.id):
return HttpResponseForbidden()
# Your own query: the newest 50, or the 50 before that id, oldest first,
# as {"messages": [{"id", "from", "text", "at", "files", "reactions"}], "more"}.
return JsonResponse(messages_of(room, request.GET.get("before")))from fastapi import Depends, HTTPException
from realtime import realtime
# GET /api/messages?room=chat:34:42, and &before=<id> as the reader scrolls up.
@app.get("/api/messages")
def messages(room: str, before: str | None = None, me: int = Depends(current_user_id)):
# The room's own rule: whoever may be in the conversation may read it.
if not me or not realtime.may_join(room, me):
raise HTTPException(403)
# Your own query: the newest 50, or the 50 before that id, oldest first,
# as {"messages": [{"id", "from", "text", "at", "files", "reactions"}], "more"}.
return messages_of(room, before)from flask import abort, request, session
from realtime import realtime
# GET /api/messages?room=chat:34:42, and &before=<id> as the reader scrolls up.
@app.get("/api/messages")
def messages():
me = session.get("user_id")
room = request.args.get("room", "")
# The room's own rule: whoever may be in the conversation may read it.
if not me or not realtime.may_join(room, me):
abort(403)
# Your own query: the newest 50, or the 50 before that id, oldest first,
# as {"messages": [{"id", "from", "text", "at", "files", "reactions"}], "more"}.
return messages_of(room, request.args.get("before"))// http.HandleFunc("GET /api/messages", messages)
func messages(w http.ResponseWriter, r *http.Request) {
me := userOf(r)
room := r.URL.Query().Get("room")
// The room's own rule: whoever may be in the conversation may read it.
if allowed, _ := roomRule(room, me); me == "" || allowed == nil {
w.WriteHeader(403)
return
}
// Your own query: the newest 50, or the 50 before that id, oldest first.
list, more := messagesOf(room, r.URL.Query().Get("before"))
reply(w, map[string]any{"messages": list, "more": more})
}Hooki i komponenty dla każdej aplikacji React, z dowolnym serwerem powyżej.
import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );import { connect } from '@wordplus/realtime';
const rt = await connect();
// The ready-made chat asks your route as it opens, and for the page before
// as the reader scrolls up. What came since, the room fills in.
await rt.ui();
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"></chat-room>
// Or on a screen of your own.
const answer = await fetch( '/api/messages?room=chat:34:42' );
const { messages, more } = await answer.json();
drawAll( messages );
// Back after more than the room keeps: some were missed, so ask your route again.
rt.join( 'chat:34:42' ).on( 'error', ( e ) => e.code === 'gap' && reload() );{{-- The conversation from your route as it opens, and the page before as the reader scrolls up. --}}
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
style="height: 520px"></chat-room>
<script type="module">
// The chat, who is online and typing, with no calls.
await window.Echo.connector.rt.ui();
</script>'use client'; // in Next.js
import { Chat, RealtimeUi } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
// The conversation from your route as it opens, and the page before as the reader scrolls up.
export function Conversation() {
return (
<>
<RealtimeUi />
<div style={ { height: 520 } }>
<Chat room="chat:34:42"
to={ 34 }
name="Ann"
messages="/api/messages?room=chat:34:42" />
</div>
</>
);
}<script setup>
import { watchEffect } from 'vue';
import { useRealtime } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat, who is online and typing, with no calls.
watchEffect( () => rt.value?.ui() );
</script>
<!-- isCustomElement for this tag, in vite.config.js. The conversation from your route as it opens, and the page before as the reader scrolls up. -->
<template>
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
style="height: 520px"></chat-room>
</template><script>
import { useRealtime } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat, who is online and typing, with no calls.
$effect( () => { rt.current?.ui(); } );
</script>
<!-- The conversation from your route as it opens, and the page before as the reader scrolls up. -->
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
style="height: 520px"></chat-room>import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
// realtime.ts, one connection for the whole app:
// export const realtime = connect();
import { realtime } from './realtime';
@Component( {
selector: 'app-conversation',
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
template: `
<!-- The conversation from your route as it opens, and the page before as the reader scrolls up. -->
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
style="height: 520px"></chat-room>
`,
} )
export class Conversation {
async ngOnInit() {
const rt = await realtime;
// The chat, who is online and typing, with no calls.
await rt.ui();
}
}// No ready-made chat on iOS: ask your route as the screen opens,
// and with before: as the reader scrolls up.
let page = try await api.messages(room: "chat:34:42", before: oldest?.id) // your own request
drawAll(page.messages)
// Back after more than the room keeps: some were missed, so ask your route again.
chat.on("error") { error, _ in if error["code"]?.string == "gap" { reload() } }// No ready-made chat on Android: ask your route as the screen opens,
// and with before = as the reader scrolls up.
val page = api.messages(room = "chat:34:42", before = oldest?.id) // your own request
drawAll(page.messages)
// Back after more than the room keeps: some were missed, so ask your route again.
chat.on("error") { error, _ -> if (error.jsonObject["code"]?.jsonPrimitive?.content == "gap") reload() }import { useEffect } from 'react';
import { useRoom } from '@wordplus/realtime/react';
// Your server, in full, as an app has no address of its own.
const API = 'https://app.example.com/api';
export function Conversation() {
// Back after more than the room keeps: some were missed, so ask your route again.
useRoom( 'chat:34:42', { error: ( e ) => e.code === 'gap' && reload() } );
// No ready-made chat in React Native: ask your route as the screen opens,
// and with &before= as the reader scrolls up.
useEffect( () => {
fetch( API + '/messages?room=chat:34:42', { headers: { Authorization: 'Bearer ' + session.token } } )
.then( ( answer ) => answer.json() )
.then( ( { messages } ) => drawAll( messages ) );
}, [] );
// draw them your way
}// No ready-made chat in Flutter: ask your route as the screen opens,
// and with before as the reader scrolls up.
final page = await api.messages(room: 'chat:34:42', before: oldest?.id); // your own request
drawAll(page.messages);Potwierdzenia odczytu i reakcje
Gotowy czat wysyła jedno i drugie i je rysuje. Potwierdzenie odczytu jest ulotne: trafia do stron otwartych teraz i zmienia znaczniki nadawcy. Reakcja przychodzi z potwierdzeniem, a Twój webhook ją zapisuje.
// Each reaction, by the message and the person: an empty key takes it back.
realtime.on( 'reaction', ( { from, data } ) => saveReaction( data.id, from, data.key ) );// Each reaction, by the message and the person: an empty key takes it back.
realtime.on( 'reaction', ( { from, data } ) => saveReaction( data.id, from, data.key ) );// Each reaction, by the message and the person: an empty key takes it back.
realtime.on( 'reaction', ( { from, data } ) => saveReaction( data.id, from, data.key ) );$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// Each reaction, by the message and the person: an empty key takes it back.
$realtime->on( 'reaction', fn ( array $e ) => save_reaction( $e['data']['id'], $e['from'], $e['data']['key'] ) );
} );// Each reaction, by the message and the person: an empty key takes it back.
$realtime->on( 'reaction', fn ( array $e ) => save_reaction( $e['data']['id'], $e['from'], $e['data']['key'] ) );# Each reaction, by the message and the person: an empty key takes it back.
realtime.on("reaction", lambda e: save_reaction(e["data"]["id"], e["from"], e["data"]["key"]))# Each reaction, by the message and the person: an empty key takes it back.
realtime.on("reaction", lambda e: save_reaction(e["data"]["id"], e["from"], e["data"]["key"]))# Each reaction, by the message and the person: an empty key takes it back.
realtime.on("reaction", lambda e: save_reaction(e["data"]["id"], e["from"], e["data"]["key"]))// In your webhook route, beside the messages.
// Each reaction, by the message and the person: an empty key takes it back.
if event["type"] == "emit" && event["event"] == "reaction" {
data, _ := event["data"].(map[string]any)
saveReaction(data["id"], event["from"], data["key"])
}Hooki i komponenty dla każdej aplikacji React, z dowolnym serwerem powyżej.
import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );const rt = window.Echo.connector.rt; // the connection Echo made
const chat = rt.join( 'chat:34:42' );
// Seen: volatile, so it reaches the pages open now and is never kept.
chat.on( 'message', ( data, meta ) => {
draw( meta.id, meta.from, data.text );
if ( document.visibilityState === 'visible' ) chat.volatile.emit( 'read', { id: meta.id } );
} );
// Ann has seen up to this one: tick it, and every message of Ben's before it.
chat.on( 'read', ( data, meta ) => markSeen( meta.from, data.id ) );
// One reaction each, by its code point, as the ready-made chat names them.
await chat.emitWithAck( 'reaction', { id: messageId, key: '1f44d' } ); // 👍, or '' to take it back
chat.on( 'reaction', ( data, meta ) => showReaction( data.id, meta.from, data.key ) );'use client'; // in Next.js
import { useRoom } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
const chat = useRoom( 'chat:34:42', {
// Seen: volatile, so it reaches the pages open now and is never kept.
message: ( data, meta ) => {
draw( meta.id, meta.from, data.text );
chat.room?.volatile.emit( 'read', { id: meta.id } );
},
// Ann has seen up to this one: tick it, and every message before it.
read: ( data, meta ) => markSeen( meta.from, data.id ),
reaction: ( data, meta ) => showReaction( data.id, meta.from, data.key ),
} );
// One reaction each, by its code point: 👍, or '' to take it back.
const react = ( id ) => chat.emitWithAck( 'reaction', { id, key: '1f44d' } );
// draw them your way
}<script setup>
import { useRoom } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const chat = useRoom( 'chat:34:42', {
// Seen: volatile, so it reaches the pages open now and is never kept.
message: ( data, meta ) => {
draw( meta.id, meta.from, data.text );
chat.room.value?.volatile.emit( 'read', { id: meta.id } );
},
// Ann has seen up to this one: tick it, and every message before it.
read: ( data, meta ) => markSeen( meta.from, data.id ),
reaction: ( data, meta ) => showReaction( data.id, meta.from, data.key ),
} );
// One reaction each, by its code point: 👍, or '' to take it back.
const react = ( id ) => chat.emitWithAck( 'reaction', { id, key: '1f44d' } );
</script><script>
import { useRoom } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const chat = useRoom( 'chat:34:42', {
// Seen: volatile, so it reaches the pages open now and is never kept.
message: ( data, meta ) => {
draw( meta.id, meta.from, data.text );
chat.room?.volatile.emit( 'read', { id: meta.id } );
},
// Ann has seen up to this one: tick it, and every message before it.
read: ( data, meta ) => markSeen( meta.from, data.id ),
reaction: ( data, meta ) => showReaction( data.id, meta.from, data.key ),
} );
// One reaction each, by its code point: 👍, or '' to take it back.
const react = ( id ) => chat.emitWithAck( 'reaction', { id, key: '1f44d' } );
</script>import { Component } from '@angular/core';
import { injectRoom } from '@wordplus/realtime/angular';
// provideRealtime() once, in your application's providers.
@Component( { selector: 'app-conversation', template: '<!-- your messages -->' } )
export class Conversation {
readonly chat = injectRoom( 'chat:34:42', {
// Seen: volatile, so it reaches the pages open now and is never kept.
message: ( data, meta ) => {
draw( meta.id, meta.from, data.text );
this.chat.room()?.volatile.emit( 'read', { id: meta.id } );
},
// Ann has seen up to this one: tick it, and every message before it.
read: ( data, meta ) => markSeen( meta.from, data.id ),
reaction: ( data, meta ) => showReaction( data.id, meta.from, data.key ),
} );
// One reaction each, by its code point: 👍, or '' to take it back.
react( id: string ) {
return this.chat.emitWithAck( 'reaction', { id, key: '1f44d' } );
}
}// Seen: volatile, so it reaches the pages and apps open now and is never kept.
chat.on("message") { data, meta in
draw(meta.id, meta.from, data["text"]?.string ?? "")
chat.volatile.emit("read", ["id": .string(meta.id ?? "")])
}
// Ann has seen up to this one: tick it, and every message before it.
chat.on("read") { data, meta in markSeen(meta.from, data["id"]?.string ?? "") }
// One reaction each, by its code point: 👍, or "" to take it back.
_ = try await chat.emitWithAck("reaction", ["id": .string(messageId), "key": "1f44d"])// Seen: volatile, so it reaches the pages and apps open now and is never kept.
chat.on("message") { data, meta ->
draw(meta.id, meta.from, data.jsonObject["text"]?.jsonPrimitive?.content ?: "")
chat.volatile.emit("read", buildJsonObject { put("id", meta.id) })
}
// Ann has seen up to this one: tick it, and every message before it.
chat.on("read") { data, meta -> markSeen(meta.from, data.jsonObject["id"]?.jsonPrimitive?.content) }
// One reaction each, by its code point: 👍, or "" to take it back.
chat.emitWithAck("reaction", buildJsonObject { put("id", messageId); put("key", "1f44d") })import { useRoom } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Conversation() {
const chat = useRoom( 'chat:34:42', {
// Seen: volatile, so it reaches the pages and apps open now and is never kept.
message: ( data, meta ) => {
draw( meta.id, meta.from, data.text );
chat.room?.volatile.emit( 'read', { id: meta.id } );
},
// Ann has seen up to this one: tick it, and every message before it.
read: ( data, meta ) => markSeen( meta.from, data.id ),
} );
// One reaction each, by its code point: 👍, or '' to take it back.
const react = ( id ) => chat.emitWithAck( 'reaction', { id, key: '1f44d' } );
// draw them your way
}// Seen: volatile, so it reaches the pages and apps open now and is never kept.
chat.on('message', (data, meta) {
draw(meta.id, meta.from, data['text']);
chat.volatile.emit('read', {'id': meta.id});
});
// Ann has seen up to this one: tick it, and every message before it.
chat.on('read', (data, meta) => markSeen(meta.from, data['id']));
// One reaction each, by its code point: 👍, or '' to take it back.
await chat.emitWithAck('reaction', {'id': messageId, 'key': '1f44d'});Wysyłaj pliki
Czat wysyła każdy plik do Twojej trasy, która zapisuje go we własnym magazynie, a wiadomość niesie tylko jego adres. My nigdy nie mamy pliku. Przy wiadomości zapisuj tylko pliki, które Twoja trasa przyjęła dla jej pokoju, i otwieraj plik tylko uczestnikom jego rozmowy.
// POST /api/files: a form of the file and the room, sent as the file is picked.
export async function POST( request: Request ) {
const me = await currentUserId();
const form = await request.formData();
const room = String( form.get( 'room' ) ?? '' );
const file = form.get( 'file' );
// The room's own rule: whoever may be in the conversation may send it a file.
if ( ! me || ! ( file instanceof File ) || ! await realtime.mayJoin( room, me ) ) {
return Response.json( { error: 'Not for this conversation.' }, { status: 403 } );
}
if ( file.size > 10_000_000 ) {
return Response.json( { error: 'Larger than 10 MB.' }, { status: 413 } );
}
// Your own storage: keep it, and answer { id, url, name, type, size }.
return Response.json( await saveFile( room, me, file ), { status: 201 } );
}// The webhook keeps the files with their message: those your route took
// for this room alone, as a page may write anything into a message of its own.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
const files = await filesOf( room, ( data.files ?? [] ).map( ( file ) => file.id ) );
await saveMessage( { id: event_id, room, from, text: data.text, files, at } );
} );// POST /api/files: a form of the file and the room, sent as the file is picked.
// upload is multer: multer( { limits: { fileSize: 10_000_000 } } )
app.post( '/api/files', upload.single( 'file' ), async ( req, res ) => {
const me = userOf( req );
const room = req.body.room ?? '';
// The room's own rule: whoever may be in the conversation may send it a file.
if ( ! me || ! req.file || ! await realtime.mayJoin( room, me ) ) {
return res.status( 403 ).json( { error: 'Not for this conversation.' } );
}
// Your own storage: keep it, and answer { id, url, name, type, size }.
res.status( 201 ).json( await saveFile( room, me, req.file ) );
} );// The webhook keeps the files with their message: those your route took
// for this room alone, as a page may write anything into a message of its own.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
const files = await filesOf( room, ( data.files ?? [] ).map( ( file ) => file.id ) );
await saveMessage( { id: event_id, room, from, text: data.text, files, at } );
} );// In your createServer(): POST /api/files, a form of the file and the room.
// import { Readable } from 'node:stream';
if ( url.pathname === '/api/files' && req.method === 'POST' ) {
const me = userOf( req );
const headers = { 'Content-Type': req.headers[ 'content-type' ] ?? '' };
const form = await new Response( Readable.toWeb( req ), { headers } ).formData();
const room = String( form.get( 'room' ) ?? '' );
const file = form.get( 'file' );
// The room's own rule: whoever may be in the conversation may send it a file.
if ( ! me || ! ( file instanceof File ) || ! await realtime.mayJoin( room, me ) ) {
res.writeHead( 403, { 'Content-Type': 'application/json' } );
return res.end( JSON.stringify( { error: 'Not for this conversation.' } ) );
}
// Your own storage: keep it, and answer { id, url, name, type, size }.
res.writeHead( 201, { 'Content-Type': 'application/json' } );
return res.end( JSON.stringify( await saveFile( room, me, file ) ) );
}// The webhook keeps the files with their message: those your route took
// for this room alone, as a page may write anything into a message of its own.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
const files = await filesOf( room, ( data.files ?? [] ).map( ( file ) => file.id ) );
await saveMessage( { id: event_id, room, from, text: data.text, files, at } );
} );// POST /api/files: a form of the file and the room, sent as the file is picked.
Route::post( '/api/files', function ( Request $request ) {
$room = (string) $request->input( 'room' );
$file = $request->file( 'file' );
// The room's own rule: whoever may be in the conversation may send it a file.
if ( ! $file || ! Realtime::mayJoin( $room, $request->user()->id ) ) {
return response()->json( [ 'error' => 'Not for this conversation.' ], 403 );
}
if ( $file->getSize() > 10_000_000 ) {
return response()->json( [ 'error' => 'Larger than 10 MB.' ], 413 );
}
// Your own storage: keep it, and answer [ 'id', 'url', 'name', 'type', 'size' ].
return response()->json( save_file( $room, $request->user()->id, $file ), 201 );
} )->middleware( 'auth' );$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// The webhook keeps the files with their message: those your route took
// for this room alone, as a page may write anything into a message of its own.
$realtime->on( 'message', function ( array $e ) {
$files = files_of( $e['room'], array_column( $e['data']['files'] ?? [], 'id' ) );
save_message( $e['event_id'], $e['room'], $e['from'], $e['data']['text'], $e['at'], $files );
} );
} );require __DIR__ . '/../../src/realtime.php';
// POST /api/files: a form of the file and the room, sent as the file is picked.
header( 'Content-Type: application/json' );
$me = current_user_id();
$room = (string) ( $_POST['room'] ?? '' );
$file = $_FILES['file'] ?? null;
// The room's own rule: whoever may be in the conversation may send it a file.
if ( ! $me || ! $file || ! $realtime->mayJoin( $room, $me ) ) {
http_response_code( 403 );
exit( json_encode( [ 'error' => 'Not for this conversation.' ] ) );
}
if ( $file['size'] > 10_000_000 ) {
http_response_code( 413 );
exit( json_encode( [ 'error' => 'Larger than 10 MB.' ] ) );
}
// Your own storage: keep it, and answer [ 'id', 'url', 'name', 'type', 'size' ].
http_response_code( 201 );
echo json_encode( save_file( $room, $me, $file ) );// The webhook keeps the files with their message: those your route took
// for this room alone, as a page may write anything into a message of its own.
$realtime->on( 'message', function ( array $e ) {
$files = files_of( $e['room'], array_column( $e['data']['files'] ?? [], 'id' ) );
save_message( $e['event_id'], $e['room'], $e['from'], $e['data']['text'], $e['at'], $files );
} );# In urls.py: path("api/files", views.files)
@login_required
def files(request):
room = request.POST.get("room", "")
file = request.FILES.get("file")
# The room's own rule: whoever may be in the conversation may send it a file.
if file is None or not realtime.may_join(room, request.user.id):
return JsonResponse({"error": "Not for this conversation."}, status=403)
if file.size > 10_000_000:
return JsonResponse({"error": "Larger than 10 MB."}, status=413)
# Your own storage: keep it, and answer {"id", "url", "name", "type", "size"}.
return JsonResponse(save_file(room, request.user.id, file), status=201)# The webhook keeps the files with their message: those your route took
# for this room alone, as a page may write anything into a message of its own.
def keep_message(e):
files = files_of(e["room"], [file["id"] for file in e["data"].get("files", [])])
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"], files)
realtime.on("message", keep_message)from fastapi import File, Form, UploadFile
from fastapi.responses import JSONResponse
# POST /api/files: a form of the file and the room, sent as the file is picked.
@app.post("/api/files")
def files(room: str = Form(...), file: UploadFile = File(...), me: int = Depends(current_user_id)):
# The room's own rule: whoever may be in the conversation may send it a file.
if not me or not realtime.may_join(room, me):
return JSONResponse({"error": "Not for this conversation."}, status_code=403)
if file.size and file.size > 10_000_000:
return JSONResponse({"error": "Larger than 10 MB."}, status_code=413)
# Your own storage: keep it, and answer {"id", "url", "name", "type", "size"}.
return JSONResponse(save_file(room, me, file), status_code=201)# The webhook keeps the files with their message: those your route took
# for this room alone, as a page may write anything into a message of its own.
def keep_message(e):
files = files_of(e["room"], [file["id"] for file in e["data"].get("files", [])])
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"], files)
realtime.on("message", keep_message)# POST /api/files: a form of the file and the room, sent as the file is picked.
@app.post("/api/files")
def files():
me = session.get("user_id")
room = request.form.get("room", "")
file = request.files.get("file")
# The room's own rule: whoever may be in the conversation may send it a file.
if not me or file is None or not realtime.may_join(room, me):
return {"error": "Not for this conversation."}, 403
# Your own storage: keep it, and answer {"id", "url", "name", "type", "size"}.
return save_file(room, me, file), 201# The webhook keeps the files with their message: those your route took
# for this room alone, as a page may write anything into a message of its own.
def keep_message(e):
files = files_of(e["room"], [file["id"] for file in e["data"].get("files", [])])
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"], files)
realtime.on("message", keep_message)// http.HandleFunc("POST /api/files", files)
func files(w http.ResponseWriter, r *http.Request) {
me := userOf(r)
room := r.FormValue("room")
file, header, err := r.FormFile("file")
// The room's own rule: whoever may be in the conversation may send it a file.
if allowed, _ := roomRule(room, me); me == "" || err != nil || allowed == nil {
w.WriteHeader(403)
reply(w, map[string]string{"error": "Not for this conversation."})
return
}
defer file.Close()
// Your own storage: keep it, and answer {id, url, name, type, size}.
w.WriteHeader(201)
reply(w, saveFile(room, me, file, header))
}
// In your webhook route: the files with their message, those your route took
// for this room alone, as a page may write anything into a message of its own.
if event["type"] == "emit" && event["event"] == "message" {
data, _ := event["data"].(map[string]any)
files := filesOf(event["room"], data["files"])
saveMessage(event["event_id"], event["room"], event["from"], data["text"], event["at"], files)
}Hooki i komponenty dla każdej aplikacji React, z dowolnym serwerem powyżej.
import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
await rt.ui();
// The paperclip, a paste or a drop sends each file to your route as it is picked,
// and the message carries only where it is, its name, type and size.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"></chat-room>{{-- Each file goes to your route as it is picked, and the message carries where it is. --}}
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"
style="height: 520px"></chat-room>
<script type="module">
// The chat, who is online and typing, with no calls.
await window.Echo.connector.rt.ui();
</script>'use client'; // in Next.js
import { Chat, RealtimeUi } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
// Each file goes to your route as it is picked, and the message carries where it is.
export function Conversation() {
return (
<>
<RealtimeUi />
<div style={ { height: 520 } }>
<Chat room="chat:34:42"
to={ 34 }
name="Ann"
messages="/api/messages?room=chat:34:42"
upload="/api/files"
accept="image/*,.pdf"
maxFileSize={ 10_000_000 } />
</div>
</>
);
}<script setup>
import { watchEffect } from 'vue';
import { useRealtime } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat, who is online and typing, with no calls.
watchEffect( () => rt.value?.ui() );
</script>
<!-- isCustomElement for this tag, in vite.config.js. Each file goes to your route as it is picked, and the message carries where it is. -->
<template>
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"
style="height: 520px"></chat-room>
</template><script>
import { useRealtime } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat, who is online and typing, with no calls.
$effect( () => { rt.current?.ui(); } );
</script>
<!-- Each file goes to your route as it is picked, and the message carries where it is. -->
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"
style="height: 520px"></chat-room>import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
// realtime.ts, one connection for the whole app:
// export const realtime = connect();
import { realtime } from './realtime';
@Component( {
selector: 'app-conversation',
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
template: `
<!-- Each file goes to your route as it is picked, and the message carries where it is. -->
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
upload="/api/files" accept="image/*,.pdf" max-file-size="10000000"
style="height: 520px"></chat-room>
`,
} )
export class Conversation {
async ngOnInit() {
const rt = await realtime;
// The chat, who is online and typing, with no calls.
await rt.ui();
}
}Wyciszaj, usuwaj i banuj
Twoja reguła czyta Twoje własne wiersze, więc wyciszenie, ban i blokada to zmiana w Twoich danych. SDK od razu pyta wtedy Twoją regułę ponownie albo natychmiast usuwa kogoś z pokoju. Zgłoszona wiadomość znika z Twojej bazy i z tego, co przechowuje pokój.
// The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
realtime.room( 'chat:{pair}', async ( user, { other } ) => ! await hasBlocked( other, user ), chat );
// In a group, a ban keeps them out, and a mute lets them read alone.
realtime.room( 'group:{id}', async ( user, { id } ) => {
const member = await memberOf( id, user );
if ( ! member || member.banned ) return false;
return member.muted ? { readOnly: true } : true;
}, { ...chat, presence: true } );// Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
await setMuted( 7, 56, true );
await realtime.room( 'group:7' ).recheck( 56 );
// Out now. She is still a member, so she may come back.
await realtime.room( 'group:7' ).remove( 56 );
// Ban her: your rule says no from now on, then out now.
await setBanned( 7, 56, true );
await realtime.room( 'group:7' ).remove( 56 );
// Ann blocks Ben in their chat.
await block( 34, 42 );
await realtime.room( 'chat:34:42' ).remove( 42 );
// A message reported: out of your database, and out of what the room keeps.
await deleteMessage( eventId );
await realtime.room( 'group:7' ).forget( eventId );// The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
realtime.room( 'chat:{pair}', async ( user, { other } ) => ! await hasBlocked( other, user ), chat );
// In a group, a ban keeps them out, and a mute lets them read alone.
realtime.room( 'group:{id}', async ( user, { id } ) => {
const member = await memberOf( id, user );
if ( ! member || member.banned ) return false;
return member.muted ? { readOnly: true } : true;
}, { ...chat, presence: true } );// Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
await setMuted( 7, 56, true );
await realtime.room( 'group:7' ).recheck( 56 );
// Out now. She is still a member, so she may come back.
await realtime.room( 'group:7' ).remove( 56 );
// Ban her: your rule says no from now on, then out now.
await setBanned( 7, 56, true );
await realtime.room( 'group:7' ).remove( 56 );
// Ann blocks Ben in their chat.
await block( 34, 42 );
await realtime.room( 'chat:34:42' ).remove( 42 );
// A message reported: out of your database, and out of what the room keeps.
await deleteMessage( eventId );
await realtime.room( 'group:7' ).forget( eventId );// The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
realtime.room( 'chat:{pair}', async ( user, { other } ) => ! await hasBlocked( other, user ), chat );
// In a group, a ban keeps them out, and a mute lets them read alone.
realtime.room( 'group:{id}', async ( user, { id } ) => {
const member = await memberOf( id, user );
if ( ! member || member.banned ) return false;
return member.muted ? { readOnly: true } : true;
}, { ...chat, presence: true } );// Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
await setMuted( 7, 56, true );
await realtime.room( 'group:7' ).recheck( 56 );
// Out now. She is still a member, so she may come back.
await realtime.room( 'group:7' ).remove( 56 );
// Ban her: your rule says no from now on, then out now.
await setBanned( 7, 56, true );
await realtime.room( 'group:7' ).remove( 56 );
// Ann blocks Ben in their chat.
await block( 34, 42 );
await realtime.room( 'chat:34:42' ).remove( 42 );
// A message reported: out of your database, and out of what the room keeps.
await deleteMessage( eventId );
await realtime.room( 'group:7' ).forget( eventId );$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
$realtime->room( 'chat:{pair}', fn ( $user, array $p ) => ! Block::where( [ 'by' => $p['other'], 'user' => $user ] )->exists(), $chat );
// In a group, a ban keeps them out, and a mute lets them read alone.
$realtime->room( 'group:{id}', function ( $user, array $p ) {
$member = GroupMember::where( [ 'group_id' => $p['id'], 'user_id' => $user ] )->first();
if ( ! $member || $member->banned ) {
return false;
}
return $member->muted ? [ 'readOnly' => true ] : true;
}, [ ...$chat, 'presence' => true ] );
} );// Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
GroupMember::where( [ 'group_id' => 7, 'user_id' => 56 ] )->update( [ 'muted' => true ] );
Realtime::room( 'group:7' )->recheck( 56 );
// Out now. She is still a member, so she may come back.
Realtime::room( 'group:7' )->remove( 56 );
// Ban her: your rule says no from now on, then out now.
GroupMember::where( [ 'group_id' => 7, 'user_id' => 56 ] )->update( [ 'banned' => true ] );
Realtime::room( 'group:7' )->remove( 56 );
// Ann blocks Ben in their chat.
Block::create( [ 'by' => 34, 'user' => 42 ] );
Realtime::room( 'chat:34:42' )->remove( 42 );
// A message reported: out of your database, and out of what the room keeps.
Message::whereKey( $eventId )->delete();
Realtime::room( 'group:7' )->forget( $eventId );// The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
$realtime->room( 'chat:{pair}', fn ( $user, array $p ) => ! has_blocked( $p['other'], $user ), $chat );
// In a group, a ban keeps them out, and a mute lets them read alone.
$realtime->room( 'group:{id}', function ( $user, array $p ) {
$member = member_of( $p['id'], $user );
if ( ! $member || $member['banned'] ) {
return false;
}
return $member['muted'] ? [ 'readOnly' => true ] : true;
}, [ ...$chat, 'presence' => true ] );// Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
set_muted( 7, 56, true );
$realtime->room( 'group:7' )->recheck( 56 );
// Out now. She is still a member, so she may come back.
$realtime->room( 'group:7' )->remove( 56 );
// Ban her: your rule says no from now on, then out now.
set_banned( 7, 56, true );
$realtime->room( 'group:7' )->remove( 56 );
// Ann blocks Ben in their chat.
block( 34, 42 );
$realtime->room( 'chat:34:42' )->remove( 42 );
// A message reported: out of your database, and out of what the room keeps.
delete_message( $event_id );
$realtime->room( 'group:7' )->forget( $event_id );# The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
realtime.room("chat:{pair}", lambda user, p: not has_blocked(p["other"], user), **chat)
# In a group, a ban keeps them out, and a mute lets them read alone.
def may_join_group(user, p):
member = member_of(p["id"], user)
if member is None or member.banned:
return False
return {"readOnly": True} if member.muted else True
realtime.room("group:{id}", may_join_group, presence=True, **chat)# Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
set_muted(7, 56, True)
realtime.room("group:7").recheck(56)
# Out now. She is still a member, so she may come back.
realtime.room("group:7").remove(56)
# Ban her: your rule says no from now on, then out now.
set_banned(7, 56, True)
realtime.room("group:7").remove(56)
# Ann blocks Ben in their chat.
block(34, 42)
realtime.room("chat:34:42").remove(42)
# A message reported: out of your database, and out of what the room keeps.
delete_message(event_id)
realtime.room("group:7").forget(event_id)# The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
realtime.room("chat:{pair}", lambda user, p: not has_blocked(p["other"], user), **chat)
# In a group, a ban keeps them out, and a mute lets them read alone.
def may_join_group(user, p):
member = member_of(p["id"], user)
if member is None or member.banned:
return False
return {"readOnly": True} if member.muted else True
realtime.room("group:{id}", may_join_group, presence=True, **chat)# In a def route, as these calls block.
# Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
set_muted(7, 56, True)
realtime.room("group:7").recheck(56)
# Out now. She is still a member, so she may come back.
realtime.room("group:7").remove(56)
# Ban her: your rule says no from now on, then out now.
set_banned(7, 56, True)
realtime.room("group:7").remove(56)
# Ann blocks Ben in their chat.
block(34, 42)
realtime.room("chat:34:42").remove(42)
# A message reported: out of your database, and out of what the room keeps.
delete_message(event_id)
realtime.room("group:7").forget(event_id)# The rules read your own rows. In a chat of two, the one blocked by the other is kept out.
realtime.room("chat:{pair}", lambda user, p: not has_blocked(p["other"], user), **chat)
# In a group, a ban keeps them out, and a mute lets them read alone.
def may_join_group(user, p):
member = member_of(p["id"], user)
if member is None or member.banned:
return False
return {"readOnly": True} if member.muted else True
realtime.room("group:{id}", may_join_group, presence=True, **chat)# Mute Cara: she reads on and sends nothing. recheck() asks your rule again at once.
set_muted(7, 56, True)
realtime.room("group:7").recheck(56)
# Out now. She is still a member, so she may come back.
realtime.room("group:7").remove(56)
# Ban her: your rule says no from now on, then out now.
set_banned(7, 56, True)
realtime.room("group:7").remove(56)
# Ann blocks Ben in their chat.
block(34, 42)
realtime.room("chat:34:42").remove(42)
# A message reported: out of your database, and out of what the room keeps.
delete_message(event_id)
realtime.room("group:7").forget(event_id)// In roomRule, the rows of your own: the one blocked by the other is kept out,
// a ban keeps them out of a group, and a mute lets them read alone.
if len(part) == 3 && part[0] == "chat" {
other := part[1]
if user == part[1] {
other = part[2]
}
if (user != part[1] && user != part[2]) || hasBlocked(other, user) {
return nil, "forbidden"
}
return &chat, ""
}
if len(part) == 2 && part[0] == "group" {
member := memberOf(part[1], user)
if member == nil || member.Banned {
return nil, "forbidden"
}
chat.Presence = true
chat.ReadOnly = member.Muted
return &chat, ""
}# Mute Cara: she reads on and sends nothing. recheck asks your rule again at once.
# In your database: UPDATE members SET muted = 1 WHERE group_id = 7 AND user_id = 56
wordplus POST /wordplus/realtime/rooms/group%3A7/recheck '{"user":"56"}'
# Out now. She is still a member, so she may come back.
wordplus POST /wordplus/realtime/rooms/group%3A7/kick '{"user":"56"}'
# Ban her: your rule says no from now on, then out now.
# In your database: UPDATE members SET banned = 1 WHERE group_id = 7 AND user_id = 56
wordplus POST /wordplus/realtime/rooms/group%3A7/kick '{"user":"56"}'
# Ann blocks Ben in their chat.
# In your database: INSERT INTO blocks (by_user, user_id) VALUES (34, 42)
wordplus POST /wordplus/realtime/rooms/chat%3A34%3A42/kick '{"user":"42"}'
# A message reported: out of your database, and out of what the room keeps.
# In your database: DELETE FROM messages WHERE id = '<its event id>'
wordplus DELETE "/wordplus/realtime/rooms/group%3A7/history?id=$EVENT_ID"Rozmowa z czatu
Z trasą dla swojego tokenu czat ma przycisk rozmowy wideo i przycisk rozmowy głosowej, a rozmowa pojawia się w czacie, obok wiadomości. Twoja trasa przepuszcza rozmowę, gdy obie osoby są w rozmowie na czacie.
// GET /api/chat-call-token?to=34&type=video&name=chat:34:42, from the chat's buttons.
export async function GET( request: Request ) {
const me = await currentUserId();
const query = new URL( request.url ).searchParams;
const to = query.get( 'to' ) ?? '';
const name = query.get( 'name' ) ?? '';
// Both in the conversation, as its room's own rule says. The name comes from the page.
if ( ! me || ! await realtime.mayJoin( name, me ) || ! await realtime.mayJoin( name, to ) ) {
return new Response( null, { status: 403 } );
}
// The call takes the chat's name, so it shows in the chat.
const type = query.get( 'type' ) === 'audio' ? 'audio' : 'video';
return Response.json( { token: await realtime.callToken( me, to, { type, name } ) } );
}// GET /api/chat-call-token?to=34&type=video&name=chat:34:42, from the chat's buttons.
app.get( '/api/chat-call-token', async ( req, res ) => {
const me = userOf( req );
const { to = '', name = '' } = req.query;
// Both in the conversation, as its room's own rule says. The name comes from the page.
if ( ! me || ! await realtime.mayJoin( name, me ) || ! await realtime.mayJoin( name, to ) ) {
return res.sendStatus( 403 );
}
// The call takes the chat's name, so it shows in the chat.
const type = req.query.type === 'audio' ? 'audio' : 'video';
res.json( { token: await realtime.callToken( me, to, { type, name } ) } );
} );// In your createServer(): GET /api/chat-call-token?to=34&type=video&name=chat:34:42.
if ( url.pathname === '/api/chat-call-token' ) {
const me = userOf( req );
const to = url.searchParams.get( 'to' ) ?? '';
const name = url.searchParams.get( 'name' ) ?? '';
// Both in the conversation, as its room's own rule says. The name comes from the page.
if ( ! me || ! await realtime.mayJoin( name, me ) || ! await realtime.mayJoin( name, to ) ) {
res.writeHead( 403 );
return res.end();
}
// The call takes the chat's name, so it shows in the chat.
const type = url.searchParams.get( 'type' ) === 'audio' ? 'audio' : 'video';
const token = await realtime.callToken( me, to, { type, name } );
res.writeHead( 200, { 'Content-Type': 'application/json' } );
return res.end( JSON.stringify( { token } ) );
}// GET /api/chat-call-token?to=34&type=video&name=chat:34:42, from the chat's buttons.
Route::get( '/api/chat-call-token', function ( Request $request ) {
$me = $request->user()->id;
$to = (string) $request->query( 'to' );
$name = (string) $request->query( 'name' );
// Both in the conversation, as its room's own rule says. The name comes from the page.
abort_unless( Realtime::mayJoin( $name, $me ) && Realtime::mayJoin( $name, $to ), 403 );
// The call takes the chat's name, so it shows in the chat.
return [ 'token' => Realtime::callToken( $me, $to, [
'type' => $request->query( 'type' ) === 'audio' ? 'audio' : 'video',
'name' => $name,
] ) ];
} )->middleware( 'auth' );require __DIR__ . '/../../src/realtime.php';
// GET /api/chat-call-token?to=34&type=video&name=chat:34:42, from the chat's buttons.
$me = current_user_id();
$to = (string) ( $_GET['to'] ?? '' );
$name = (string) ( $_GET['name'] ?? '' );
// Both in the conversation, as its room's own rule says. The name comes from the page.
if ( ! $me || ! $realtime->mayJoin( $name, $me ) || ! $realtime->mayJoin( $name, $to ) ) {
http_response_code( 403 );
exit;
}
// The call takes the chat's name, so it shows in the chat.
header( 'Content-Type: application/json' );
echo json_encode( [
'token' => $realtime->callToken( $me, $to, [
'type' => ( $_GET['type'] ?? '' ) === 'audio' ? 'audio' : 'video',
'name' => $name,
] ),
] );# In urls.py: path("api/chat-call-token", views.chat_call_token)
@login_required
def chat_call_token(request):
me = request.user.id
to = request.GET.get("to", "")
name = request.GET.get("name", "")
# Both in the conversation, as its room's own rule says. The name comes from the page.
if not realtime.may_join(name, me) or not realtime.may_join(name, to):
return HttpResponseForbidden()
# The call takes the chat's name, so it shows in the chat.
kind = "audio" if request.GET.get("type") == "audio" else "video"
return JsonResponse({"token": realtime.call_token(me, to, type=kind, name=name)})# GET /api/chat-call-token?to=34&type=video&name=chat:34:42, from the chat's buttons.
@app.get("/api/chat-call-token")
def chat_call_token(to: str, name: str, type: str = "video", me: int = Depends(current_user_id)):
# Both in the conversation, as its room's own rule says. The name comes from the page.
if not me or not realtime.may_join(name, me) or not realtime.may_join(name, to):
raise HTTPException(403)
# The call takes the chat's name, so it shows in the chat.
kind = "audio" if type == "audio" else "video"
return {"token": realtime.call_token(me, to, type=kind, name=name)}# GET /api/chat-call-token?to=34&type=video&name=chat:34:42, from the chat's buttons.
@app.get("/api/chat-call-token")
def chat_call_token():
me = session.get("user_id")
to = request.args.get("to", "")
name = request.args.get("name", "")
# Both in the conversation, as its room's own rule says. The name comes from the page.
if not me or not realtime.may_join(name, me) or not realtime.may_join(name, to):
abort(403)
# The call takes the chat's name, so it shows in the chat.
kind = "audio" if request.args.get("type") == "audio" else "video"
return {"token": realtime.call_token(me, to, type=kind, name=name)}// http.HandleFunc("GET /api/chat-call-token", chatCallToken)
func chatCallToken(w http.ResponseWriter, r *http.Request) {
me := userOf(r)
to := r.URL.Query().Get("to")
name := r.URL.Query().Get("name")
// Both in the conversation, as its room's rule says. The name comes from the page.
mine, _ := roomRule(name, me)
theirs, _ := roomRule(name, to)
if me == "" || mine == nil || theirs == nil {
w.WriteHeader(403)
return
}
// The example's CallToken names no call of its own, so this call
// rings and opens in the call window, over the chat.
kind := r.URL.Query().Get("type")
reply(w, map[string]string{"token": app.CallToken(me, to, kind, profile(me))})
}Hooki i komponenty dla każdej aplikacji React, z dowolnym serwerem powyżej.
import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>import { connect } from '@wordplus/realtime';
const rt = await connect();
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
// With to, the chat's bar has a video and an audio call button, which ask your
// route. The call shows beside the messages, or over them in a narrow chat.
// <chat-room room="chat:34:42" to="34" name="Ann"
// messages="/api/messages?room=chat:34:42"
// token-url="/api/chat-call-token"></chat-room>{{-- The call buttons on its bar ask your route, and the call shows in the chat. --}}
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
token-url="/api/chat-call-token"
style="height: 520px"></chat-room>
<script type="module">
// The chat and its calls: the ring and the call window too.
await window.Echo.connector.rt.callScreen();
</script>'use client'; // in Next.js
import { Chat, CallScreen } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
// The call buttons on its bar ask your route, and the call shows in the chat.
export function Conversation() {
return (
<>
<CallScreen />
<div style={ { height: 520 } }>
<Chat room="chat:34:42"
to={ 34 }
name="Ann"
messages="/api/messages?room=chat:34:42"
tokenUrl="/api/chat-call-token" />
</div>
</>
);
}<script setup>
import { watchEffect } from 'vue';
import { useRealtime } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat and its calls: the ring and the call window too.
watchEffect( () => rt.value?.callScreen() );
</script>
<!-- isCustomElement for this tag, in vite.config.js. The call buttons on its bar ask your route, and the call shows in the chat. -->
<template>
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
token-url="/api/chat-call-token"
style="height: 520px"></chat-room>
</template><script>
import { useRealtime } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const rt = useRealtime();
// The chat and its calls: the ring and the call window too.
$effect( () => { rt.current?.callScreen(); } );
</script>
<!-- The call buttons on its bar ask your route, and the call shows in the chat. -->
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
token-url="/api/chat-call-token"
style="height: 520px"></chat-room>import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
// realtime.ts, one connection for the whole app:
// export const realtime = connect();
import { realtime } from './realtime';
@Component( {
selector: 'app-conversation',
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
template: `
<!-- The call buttons on its bar ask your route, and the call shows in the chat. -->
<chat-room room="chat:34:42" to="34" name="Ann"
messages="/api/messages?room=chat:34:42"
token-url="/api/chat-call-token"
style="height: 520px"></chat-room>
`,
} )
export class Conversation {
async ngOnInit() {
const rt = await realtime;
// The chat and its calls: the ring and the call window too.
await rt.callScreen();
}
}Rozmowa z czatu to rozmowa między dwiema osobami: nasze API rozmów wideo ma wszystko, co robi rozmowa.
Czat w każdym stacku, z całą konfiguracją:
Gdzie działa
Gotowy czat w przeglądarce, własny na telefonach
Te same rozmowy docierają do przeglądarki, na iOS i Androida, przez te same pokoje. Oto co ma każda platforma.
W przeglądarce
Gotowy czat, kto jest online i kto pisze, jako elementy dla każdej strony i jako komponenty React. Albo te same zdarzenia na własnym ekranie, z funkcjami pomocniczymi dla React, Vue, Svelte i Angular.
Na iOS i Androidzie
Pokoje, wiadomości, pisanie, kto jest online i historia z Twojej trasy, w Swift i Kotlinie, z gotowymi ekranami rozmów. Gotowego ekranu czatu nie ma: Twoja aplikacja rysuje własny, we własnym wyglądzie, na tych samych pokojach.
W React Native i Flutterze
Pokoje, wiadomości, pisanie i kto jest online na iOS i Androidzie, na ekranie czatu rysowanym przez Twoją aplikację.
Na Twoim serwerze
Node.js, PHP i Python, z Laravelem, Django, FastAPI i Flaskiem, oraz API HTTP dla każdego innego języka: reguły, webhook, wiadomości z Twojego serwera i usuwanie kogoś z rozmowy.
Zastosowania
Co się buduje z czatem
Każde to cała aplikacja w dokumentacji, z serwerem w Node.js, PHP i Pythonie.
Czat
Rozmowy między dwiema osobami i w grupach, z pisaniem, znacznikami odczytu i reakcjami, przechowywane w Twojej własnej bazie danych.
Czat w marketplace
Kupujący pyta sprzedawcę o ogłoszenie, sprzedawca jest online albo widać, kiedy był ostatnio, a nieobecny dostaje powiadomienie lub e-mail.
Dział wsparcia z konsultantami
Każda nowa rozmowa trafia do dyżurnego konsultanta, pozostali czytają razem z nim, a konsultant dzwoni do klienta z rozmowy.
Czat z AI, potem człowiek
Asystent, który odpowiada w rozmowie, gdy pisze Twój własny model, i osoba z zespołu wsparcia, która przejmuje ten sam czat.
Kto jest online i kto tu jest
Kropka przy każdym awatarze, osoby w pokoju wraz z rolami i liczba osób, które oglądają stronę.
Wspólne oglądanie
Wideo, które odtwarza się, pauzuje i przeskakuje u wszystkich naraz, tak jak robi to gospodarz, a obok czat i rozmowa całej grupy.
Cennik
Cena według połączeń, nigdy według wiadomości
Od $11.99 miesięcznie za 1000 jednoczesnych połączeń przy rozliczeniu rocznym lub $14.99 przy rozliczeniu miesięcznym.
Cena zależy od jednoczesnych połączeń, od 1000, rozliczana miesięcznie lub rocznie. Wiadomości i transfer nigdy nie są rozliczane, a to, co wysyła Twój serwer, nie zużywa żadnych Twoich połączeń.
Ten sam plan i SDK dają też rozmowy wideo i transmisje na żywo, na tym samym połączeniu.
Pytania
Najczęstsze pytania
Czy przechowujecie nasze wiadomości?
Nie. Pokój trzyma swoje ostatnie zdarzenia przez około pięć minut, tylko po to, by strona, która łączy się ponownie, niczego nie przegapiła. Twój serwer zapisuje rozmowę we własnej bazie danych, z webhooka albo własnej trasy, a czat ładuje ją z Twojej trasy przy otwarciu.
Czy potrzebuję własnego serwera czatu?
Nie. Strony wysyłają sobie wiadomości przez nasze serwery, bez żądania do Twojego serwera, a wszyscy w rozmowie dostają je od razu, w każdej karcie i na każdym urządzeniu. Twój serwer mówi, kto może być w każdej rozmowie, i zapisuje to, co do niego trafia.
Czy jest gotowy czat?
Tak, w przeglądarce: rozmowa ze wskaźnikiem pisania, potwierdzeniami odczytu, reakcjami, plikami i rozmowami, jako element dla każdej strony i jako komponent React, obok list osób online. Aplikacje na iOS i Androida rysują własny ekran czatu na tych samych pokojach, ze wskaźnikiem pisania i statusem online.
Które stacki mogą używać SDK czatu?
Next.js i Express, Laravel i zwykłe PHP, Django, FastAPI i Flask, Capacitor, iOS i Android, każdy z przewodnikiem. Aplikacje React Native i Flutter też mają pokoje i obecność. Serwer w dowolnym innym języku używa HTTP API.
Czy możecie czytać nasze wiadomości?
Nie w prywatnej rozmowie. Jej wiadomości, historia i lista uczestników podróżują zapieczętowane kluczami, które tworzy Twój serwer, a chmura przenosi je bez możliwości odczytu. Twój serwer otwiera to, co przynosi jego webhook, żeby to zapisać.
Kto decyduje, kto może pisać do kogo?
Twój serwer, z regułą dla każdego rodzaju rozmowy, która czyta Twoje własne dane: kto w niej jest, kto może tylko czytać, a kto zostaje poza nią. Chmura egzekwuje każdą odpowiedź, a Twój serwer może od razu usunąć kogoś z rozmowy.
Czy można wysyłać pliki i zdjęcia?
Tak. Czat wysyła każdy plik do Twojej trasy, która zapisuje go we własnym magazynie, a wiadomość niesie tylko jego adres, nazwę, typ i rozmiar. Chmura nigdy nie ma pliku.
Czy mogę zbudować własny ekran czatu?
Tak. Gotowy czat jest opcjonalny. Zmień jego kolory i teksty albo narysuj rozmowę samodzielnie na tych samych zdarzeniach, tak by Twój ekran i gotowy czat rozmawiały ze sobą.
Ile kosztuje czat?
Cena czatu zależy od jednoczesnych połączeń, od 1000, rozliczana miesięcznie lub rocznie. Wiadomości, pisanie, potwierdzenia odczytu i pliki nigdy nie są rozliczane, a to, co wysyła Twój serwer, nie zużywa żadnych Twoich połączeń.
Pytania o Twoją integrację? Napisz do nas: pomagamy z SDK, ekranem rozmowy i Twoim stackiem.