Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 35 additions & 5 deletions backend/src/protocol.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@
* entregue a quem está na sala e nunca vai para o log.
*
* Pessoas: quem conversa se identifica pelo `@username` — é ele que vai em
* mensagens, listas, digitação e conversas privadas. O id interno de uma
* mensagens, listas, digitação e conversas privadas. Junto vai o `author`:
* um número que o servidor dá a cada participante DENTRO de uma conversa
* (1, 2, 3…), fixo para a vida da conversa. Ele distingue duas pessoas que
* usaram o mesmo @ em momentos diferentes, sem revelar nada fora daquela
* conversa: o mesmo número em outra conversa é outra contagem. O id interno de uma
* identidade NUNCA sai num evento: fica no servidor (índices, logs) e só
* administradores o veem, pelos comandos `/users`, `/profile` e `/id`.
*
Expand Down Expand Up @@ -240,6 +244,12 @@ export const errorCodeForEnvelope = (reason) =>
*/
export const scoped = (conversationId, message) => ({ ...message, conversationId });

/**
* Número de autor no payload, quando existe.
* @param {{author?: number}} user
*/
const authorOf = (user) => (typeof user.author === "number" ? { author: user.author } : {});

/**
* @typedef {object} RoomSummary
* @property {string} conversationId
Expand All @@ -248,6 +258,7 @@ export const scoped = (conversationId, message) => ({ ...message, conversationId
* @property {string} name
* @property {string} role papel de quem recebe NESTA sala
* @property {string | null} hostUsername @ de quem é anfitrião agora
* @property {number | null} author o SEU número de autor nesta sala
* @property {number} memberCount
* @property {number} historyVersion
*/
Expand All @@ -256,7 +267,8 @@ export const scoped = (conversationId, message) => ({ ...message, conversationId
* @typedef {object} DmSummary
* @property {string} conversationId
* @property {"dm"} kind
* @property {{name: string, username: string, online: boolean}} peer a outra pessoa
* @property {{name: string, username: string, online: boolean, author: number}} peer a outra pessoa
* @property {number} author o SEU número de autor nesta conversa
* @property {number} historyVersion
*/

Expand Down Expand Up @@ -383,6 +395,7 @@ export const serverMessage = Object.freeze({
payload: {
userName: user.name,
username: user.username ?? "",
...authorOf(user),
content,
timestamp,
...(kind !== MESSAGE_KINDS.TEXT ? { kind } : {}),
Expand All @@ -394,7 +407,12 @@ export const serverMessage = Object.freeze({
/** @param {{name: string, username?: string}} user @param {string} timestamp */
joined: (user, timestamp) => ({
type: SERVER_EVENTS.USER_JOINED,
payload: { userName: user.name, username: user.username ?? "", timestamp },
payload: {
userName: user.name,
username: user.username ?? "",
...authorOf(user),
timestamp,
},
}),

/**
Expand All @@ -404,7 +422,13 @@ export const serverMessage = Object.freeze({
*/
left: (user, timestamp, reason = "left") => ({
type: SERVER_EVENTS.USER_LEFT,
payload: { userName: user.name, username: user.username ?? "", timestamp, reason },
payload: {
userName: user.name,
username: user.username ?? "",
...authorOf(user),
timestamp,
reason,
},
}),

/**
Expand All @@ -418,6 +442,7 @@ export const serverMessage = Object.freeze({
payload: users.map((user) => ({
name: user.name,
username: user.username ?? "",
...authorOf(user),
status: user.away === null || user.away === undefined ? PRESENCE.ONLINE : PRESENCE.AWAY,
role: user.role ?? ROLES.MEMBER,
...(user.away ? { statusText: user.away } : {}),
Expand All @@ -427,7 +452,12 @@ export const serverMessage = Object.freeze({
/** @param {{name: string, username?: string}} user @param {boolean} isTyping */
typing: (user, isTyping) => ({
type: SERVER_EVENTS.USER_TYPING,
payload: { userName: user.name, username: user.username ?? "", isTyping },
payload: {
userName: user.name,
username: user.username ?? "",
...authorOf(user),
isTyping,
},
}),

/**
Expand Down
21 changes: 16 additions & 5 deletions backend/src/room/direct.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ export const createDirectConversation = ({

/** @param {Identity} identity */
const has = (identity) => identity === a || identity === b;
/** Número de autor: quem abriu é 1, a outra pessoa é 2. @param {Identity} identity */
const authorOf = (identity) => (identity === a ? 1 : 2);
/** @param {Identity} identity */
const persona = (identity) => ({
name: identity.name,
username: identity.username,
author: authorOf(identity),
});
/** @param {Identity} identity */
const peerOf = (identity) => (identity === a ? b : a);

Expand All @@ -97,7 +105,9 @@ export const createDirectConversation = ({
name: peer.name,
username: peer.username,
online: peer.holder !== null,
author: authorOf(peer),
},
author: authorOf(identity),
historyVersion: transcript.version,
};
};
Expand Down Expand Up @@ -129,10 +139,11 @@ export const createDirectConversation = ({
const publish = (identity, input) => {
if (closed || !has(identity))
return { ok: false, code: ERROR_CODES.CONVERSATION_NOT_FOUND };
const { message, duplicate } = transcript.append(identity, {
kind: MESSAGE_KINDS.TEXT,
...input,
});
const { message, duplicate } = transcript.append(
identity,
{ kind: MESSAGE_KINDS.TEXT, ...input },
authorOf(identity),
);
const scopedMessage = scoped(id, message);
if (duplicate) {
sendTo(identity, scopedMessage);
Expand Down Expand Up @@ -190,7 +201,7 @@ export const createDirectConversation = ({
if (closed || !has(identity)) return;
const peer = peerOf(identity);
if (announced.has(peer)) {
sendTo(peer, scoped(id, serverMessage.typing(identity, isTyping)));
sendTo(peer, scoped(id, serverMessage.typing(persona(identity), isTyping)));
}
},

Expand Down
51 changes: 39 additions & 12 deletions backend/src/room/room.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,31 @@ export const createRoom = ({
let quiet = false;
/** Ids removidos por moderação: não voltam enquanto a sala existir. */
const banned = new Set();
/**
* Números de autor desta sala (id interno → número), dados na primeira
* entrada e guardados até a sala acabar: quem sai e volta mantém o
* número; uma identidade nova com o mesmo @ recebe outro.
* @type {Map<string, number>}
*/
const authors = new Map();
let nextAuthor = 1;
/** @param {Identity} identity */
const authorOf = (identity) => {
let author = authors.get(identity.id);
if (author === undefined) {
author = nextAuthor;
nextAuthor += 1;
authors.set(identity.id, author);
}
return author;
};
/** Como a pessoa aparece nos quadros desta sala. @param {Identity} identity */
const persona = (identity) => ({
name: identity.name,
username: identity.username,
author: authorOf(identity),
});

/** Quem é anfitrião agora. @type {Identity | null} */
let host = null;

Expand Down Expand Up @@ -148,8 +173,7 @@ export const createRoom = ({
broadcast(
serverMessage.userList(
present().map(([identity, membership]) => ({
name: identity.name,
username: identity.username,
...persona(identity),
away: identity.away,
role: identity.role === ROLES.ADMIN ? ROLES.ADMIN : membership.role,
})),
Expand Down Expand Up @@ -183,7 +207,7 @@ export const createRoom = ({
if (quiet) return;
broadcast(
serverMessage.left(
identity,
persona(identity),
timestamp(),
reason === REMOVAL_REASONS.REMOVED ? "removed" : "left",
),
Expand All @@ -202,6 +226,7 @@ export const createRoom = ({
name,
role: members.get(identity)?.role ?? ROLES.MEMBER,
hostUsername: host?.username ?? null,
author: authors.get(identity.id) ?? null,
memberCount: members.size,
historyVersion: transcript.version,
});
Expand Down Expand Up @@ -276,12 +301,11 @@ export const createRoom = ({

// Reenvio da mesma mensagem (retentativa do cliente): a original volta
// só para quem enviou, sem duplicar na sala.
const { message, duplicate } = transcript.append(identity, {
content,
kind,
format,
clientMsgId,
});
const { message, duplicate } = transcript.append(
identity,
{ content, kind, format, clientMsgId },
authorOf(identity),
);
if (duplicate) {
sendTo(identity, message);
return { ok: true, duplicate: true };
Expand Down Expand Up @@ -354,14 +378,15 @@ export const createRoom = ({
pendingLeave: null,
});
identity.rooms.add(id);
authorOf(identity);
if (asHost) host = identity;
log("info", "room_member_joined", {
conversation: id,
user: identity.id,
host: asHost,
});
sendState(identity, { created });
broadcast(serverMessage.joined(identity, timestamp()), identity);
broadcast(serverMessage.joined(persona(identity), timestamp()), identity);
broadcastUserList();
return { ok: true, already: false };
},
Expand Down Expand Up @@ -403,7 +428,8 @@ export const createRoom = ({
membership.connected = true;
const silentReturn = wasConnected || cancelPendingLeave(membership);
sendState(identity, { resumed: true });
if (!silentReturn) broadcast(serverMessage.joined(identity, timestamp()), identity);
if (!silentReturn)
broadcast(serverMessage.joined(persona(identity), timestamp()), identity);
broadcastUserList();
},

Expand Down Expand Up @@ -436,7 +462,7 @@ export const createRoom = ({
*/
typing(identity, isTyping) {
if (!members.get(identity)?.connected) return;
broadcast(serverMessage.typing(identity, isTyping), identity);
broadcast(serverMessage.typing(persona(identity), isTyping), identity);
},

/**
Expand Down Expand Up @@ -616,6 +642,7 @@ export const createRoom = ({
for (const identity of members.keys()) identity.rooms.delete(id);
members.clear();
banned.clear();
authors.clear();
host = null;
log("info", "room_destroyed", { conversation: id });
},
Expand Down
6 changes: 5 additions & 1 deletion backend/src/room/transcript.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,13 @@ export const createTranscript = ({
* original em `duplicate`, sem registrar de novo.
* @param {Identity} identity
* @param {{content: string, kind?: string, format?: string | null, clientMsgId?: string | null}} message
* @param {number} [author] número de autor de quem escreve nesta conversa
* @returns {{message: ChatMessage, duplicate: boolean}}
*/
append(
identity,
{ content, kind = MESSAGE_KINDS.TEXT, format = null, clientMsgId = null },
author,
) {
const recentKey = clientMsgId ? prefix + clientMsgId : null;
if (recentKey) {
Expand All @@ -59,7 +61,9 @@ export const createTranscript = ({
}
const message = serverMessage.chat({
id: newMessageId(),
user: identity,
// A autoria fica gravada na mensagem: nome, @ e número de
// autor de QUANDO foi escrita, mesmo que a pessoa saia depois.
user: { name: identity.name, username: identity.username, author },
content,
timestamp: now().toISOString(),
kind,
Expand Down
2 changes: 2 additions & 0 deletions backend/test/integration/direct.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ describe("conversas privadas", () => {
name: "Bia",
username: bia.username,
online: true,
author: 2,
});
assert.equal(opened.payload.author, 1, "quem abre é o autor 1");
await settle(bia.client);
assert.equal(bia.client.count("dm_opened"), 0, "abrir não avisa a outra pessoa");

Expand Down
25 changes: 25 additions & 0 deletions backend/test/integration/rooms.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,31 @@ describe("várias salas", () => {
client.close();
});

test("número de autor por sala: dado pelo servidor, sem forja e sem ligar salas", async () => {
const ana = await session(server.url, "Ana");
const bia = await session(server.url, "Bia");
const roomA = await createRoom(ana.client, "Autores A");
const roomB = await createRoom(bia.client, "Autores B");
assert.equal(roomA.payload.author, 1);
const joinedA = await joinRoom(bia.client, roomA.payload.code);
const joinedB = await joinRoom(ana.client, roomB.payload.code);
assert.equal(joinedA.payload.author, 2, "Bia é a 2ª na sala A");
assert.equal(joinedB.payload.author, 2, "Ana é a 2ª na sala B: outra contagem");
bia.client.send("chat_message", {
conversationId: roomA.conversationId,
content: "tentando ser a 1",
author: 1,
username: ana.me.username,
});
const chat = await ana.client.take(
(m) => m.type === "chat_message" && m.conversationId === roomA.conversationId,
);
assert.equal(chat.payload.author, 2);
assert.equal(chat.payload.username, bia.me.username);
ana.client.close();
bia.client.close();
});

test("duas salas, uma pessoa nas duas: cada mensagem só na sua sala", async () => {
const ana = await session(server.url, "Ana");
const bia = await session(server.url, "Bia");
Expand Down
Loading
Loading