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
30 changes: 29 additions & 1 deletion backend/src/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ export const ERROR_CODES = Object.freeze({
LOOKUP_LIMITED: "lookup_limited",
DM_OPEN_LIMITED: "dm_open_limited",
BLOCK_LIMIT: "block_limit",
// Recursos de mensagem (responder, editar, apagar, reagir, fixar)
MESSAGE_NOT_FOUND: "message_not_found",
NOT_ALLOWED: "not_allowed",
INVALID_REACTION: "invalid_reaction",
REACTION_LIMIT: "reaction_limit",
PIN_LIMIT: "pin_limit",
INVALID_DESCRIPTION: "invalid_description",
});

const { PROTOCOL, VALIDATION, AUTHORIZATION, RATE_LIMIT, INTERNAL } = ERROR_CATEGORIES;
Expand Down Expand Up @@ -88,7 +95,7 @@ const CATALOG = Object.freeze({
},
[ERROR_CODES.MUTED]: {
category: AUTHORIZATION,
message: "Você foi silenciado por um administrador e não pode enviar mensagens agora.",
message: "Quem modera a sala silenciou você por enquanto. Você pode continuar lendo.",
},
[ERROR_CODES.INTERNAL_ERROR]: { category: INTERNAL, message: "Erro interno do servidor" },
[ERROR_CODES.INVALID_ROOM_CODE]: {
Expand Down Expand Up @@ -163,6 +170,27 @@ const CATALOG = Object.freeze({
category: AUTHORIZATION,
message: "Você já bloqueou o número máximo de pessoas nesta sessão.",
},
[ERROR_CODES.MESSAGE_NOT_FOUND]: {
category: VALIDATION,
message: "Esta mensagem não está mais disponível.",
},
[ERROR_CODES.NOT_ALLOWED]: {
category: AUTHORIZATION,
message: "Você não pode fazer isso nesta conversa.",
},
[ERROR_CODES.INVALID_REACTION]: { category: VALIDATION, message: "Reação inválida." },
[ERROR_CODES.REACTION_LIMIT]: {
category: VALIDATION,
message: "Esta mensagem já tem o número máximo de reações diferentes.",
},
[ERROR_CODES.PIN_LIMIT]: {
category: VALIDATION,
message: "Esta conversa já tem o número máximo de mensagens fixadas. Desafixe uma antes.",
},
[ERROR_CODES.INVALID_DESCRIPTION]: {
category: VALIDATION,
message: "Descrição inválida. Use até 200 caracteres.",
},
});

/**
Expand Down
2 changes: 2 additions & 0 deletions backend/src/metrics.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ export const createMetrics = ({ now = () => Date.now(), startedAt = Date.now() }
dmsOpened: 0,
dmsClosed: 0,
blocks: 0,
// Recursos de mensagem (editar, apagar, reagir, fixar, descrição)
messageActions: {},
};

const buckets = new Array(PROCESSING_BUCKETS_MS.length + 1).fill(0);
Expand Down
74 changes: 72 additions & 2 deletions backend/src/protocol.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ export const LIMITS = Object.freeze({
awayTextMaxLength: 60,
/** Nome opcional de uma sala. */
roomNameMaxLength: 40,
/** Descrição de uma sala (definida por quem modera). */
roomDescriptionMaxLength: 200,
/** Código de convite como digitado (com espaços, hífens ou o link inteiro). */
roomCodeInputMaxLength: 200,
/** `conversationId` recebido do cliente. */
Expand Down Expand Up @@ -83,6 +85,16 @@ export const CLIENT_EVENTS = Object.freeze({
USER_BLOCK: "user_block",
/** Desfazer um bloqueio. */
USER_UNBLOCK: "user_unblock",
/** Editar a própria mensagem (`{conversationId, id, content}`). */
MESSAGE_EDIT: "message_edit",
/** Apagar uma mensagem (sua; ou qualquer uma, para quem modera a sala). */
MESSAGE_DELETE: "message_delete",
/** Ligar ou desligar a sua reação (`{conversationId, id, emoji}`). */
REACTION_TOGGLE: "reaction_toggle",
/** Fixar ou desafixar uma mensagem (`{conversationId, id, pinned}`). */
MESSAGE_PIN: "message_pin",
/** Mudar a descrição da sala (`{conversationId, description}`). */
ROOM_UPDATE: "room_update",
});

/** Eventos que o servidor envia. */
Expand Down Expand Up @@ -117,6 +129,14 @@ export const SERVER_EVENTS = Object.freeze({
DM_CLOSED: "dm_closed",
/** Quem você bloqueou nesta sessão (resposta a bloquear/desbloquear). */
BLOCK_LIST: "block_list",
/** Uma mensagem foi editada por quem a escreveu. */
MESSAGE_UPDATED: "message_updated",
/** Uma mensagem foi apagada (por quem escreveu ou pela moderação). */
MESSAGE_DELETED: "message_deleted",
/** As reações de uma mensagem mudaram. */
MESSAGE_REACTIONS: "message_reactions",
/** As mensagens fixadas da conversa mudaram (ou o estado ao entrar). */
PINS_UPDATED: "pins_updated",
});

/**
Expand Down Expand Up @@ -263,6 +283,7 @@ const authorOf = (user) => (typeof user.author === "number" ? { author: user.aut
* @property {number | null} author o SEU número de autor nesta sala
* @property {number} memberCount
* @property {number} historyVersion
* @property {string} [description] descrição da sala, quando houver
*/

/**
Expand Down Expand Up @@ -391,6 +412,7 @@ export const serverMessage = Object.freeze({
kind = MESSAGE_KINDS.TEXT,
format = null,
clientMsgId = null,
reference = null,
}) => ({
id,
type: SERVER_EVENTS.CHAT_MESSAGE,
Expand All @@ -403,9 +425,52 @@ export const serverMessage = Object.freeze({
...(kind !== MESSAGE_KINDS.TEXT ? { kind } : {}),
...(format ? { format } : {}),
...(clientMsgId ? { clientMsgId } : {}),
...(reference ? { reference } : {}),
},
}),

/**
* Mensagem editada por quem a escreveu.
* @param {string} id
* @param {string} content
* @param {string} editedAt
*/
messageUpdated: (id, content, editedAt) => ({
type: SERVER_EVENTS.MESSAGE_UPDATED,
payload: { id, content, editedAt },
}),

/**
* Mensagem apagada. `by` diz se foi quem escreveu ou a moderação (sem
* dizer quem moderou).
* @param {string} id
* @param {"author" | "moderation"} by
*/
messageDeleted: (id, by) => ({
type: SERVER_EVENTS.MESSAGE_DELETED,
payload: { id, by },
}),

/**
* Reações de uma mensagem. `authors` são chaves `@username#número` desta
* conversa (já públicas nela); nenhum id interno.
* @param {string} id
* @param {{emoji: string, count: number, authors: string[]}[]} reactions
*/
messageReactions: (id, reactions) => ({
type: SERVER_EVENTS.MESSAGE_REACTIONS,
payload: { id, reactions },
}),

/**
* Mensagens fixadas da conversa (cópias de trecho e autoria).
* @param {unknown[]} pins
*/
pinsUpdated: (pins) => ({
type: SERVER_EVENTS.PINS_UPDATED,
payload: { pins },
}),

/** @param {{name: string, username?: string}} user @param {string} timestamp */
joined: (user, timestamp) => ({
type: SERVER_EVENTS.USER_JOINED,
Expand Down Expand Up @@ -467,10 +532,15 @@ export const serverMessage = Object.freeze({
* @param {string | null} [ref] `clientMsgId` ou `requestId` recusado, quando houver
* @param {string | null} [conversationId] conversa a que o erro se refere
*/
error: (code, ref = null, conversationId = null) => ({
error: (code, ref = null, conversationId = null, detail = null) => ({
type: SERVER_EVENTS.ERROR,
...(conversationId ? { conversationId } : {}),
payload: { code, message: describeError(code).message, ...(ref ? { ref } : {}) },
payload: {
code,
message: describeError(code).message,
...(ref ? { ref } : {}),
...(detail ?? {}),
},
}),

/** @param {unknown[]} commands metadados do registro (ver commands/registry.js) */
Expand Down
61 changes: 60 additions & 1 deletion backend/src/room/direct.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@

import crypto from "node:crypto";
import { ERROR_CODES } from "../errors.js";
import { DM_CLOSED_REASONS, MESSAGE_KINDS, scoped, serverMessage } from "../protocol.js";
import { DM_CLOSED_REASONS, MESSAGE_KINDS, TONES, scoped, serverMessage } from "../protocol.js";
import { readClientId, readContent } from "../validation.js";
import { createTranscript } from "./transcript.js";
import { createMessageOps } from "./messageOps.js";

/** Limites padrão; configuráveis por variável de ambiente. */
export const DM_DEFAULTS = Object.freeze({
Expand Down Expand Up @@ -91,6 +92,34 @@ export const createDirectConversation = ({
deliver(identity.holder, JSON.stringify(message));
};

/** Para as duas (só quem já sabe da conversa). @param {Record<string, unknown>} message */
const broadcast = (message) => {
const data = scoped(id, message);
for (const identity of participants) if (announced.has(identity)) sendTo(identity, data);
};

/** Responder, editar, apagar, reagir e fixar (comum com as salas). */
const ops = createMessageOps({
transcript,
broadcast,
notice: (text) =>
broadcast(
serverMessage.notice({
id: newMessageId(),
tone: TONES.INFO,
text,
timestamp: now().toISOString(),
}),
),
timestamp: () => now().toISOString(),
log,
conversationId: id,
});

/** @param {Identity} identity */
const allowed = (identity) =>
closed || !has(identity) ? { ok: false, code: ERROR_CODES.CONVERSATION_NOT_FOUND } : null;

/**
* Resumo do ponto de vista de quem recebe: a outra pessoa e a presença dela.
* @param {Identity} identity
Expand Down Expand Up @@ -122,6 +151,7 @@ export const createDirectConversation = ({
sendTo(identity, serverMessage.dmOpened(summaryFor(identity), how));
const recent = transcript.recent(historyOnJoin);
if (recent.length > 0) sendTo(identity, scoped(id, serverMessage.history(recent)));
if (ops.pinCount > 0) sendTo(identity, scoped(id, ops.pinsUpdated()));
};

/** A outra pessoa (se já sabe da conversa) recebe o resumo atualizado. @param {Identity} identity */
Expand Down Expand Up @@ -187,11 +217,40 @@ export const createDirectConversation = ({
return publish(identity, {
content: content.content,
clientMsgId: readClientId(payload.clientMsgId),
reference: ops.reference(payload.replyTo),
});
},

publish,

/** @param {Identity} identity @param {Record<string, unknown>} payload */
edit(identity, payload) {
return allowed(identity) ?? ops.edit(persona(identity), payload);
},

/** Numa privada, cada pessoa apaga só as próprias mensagens. @param {Identity} identity @param {Record<string, unknown>} payload */
removeMessage(identity, payload) {
return (
allowed(identity) ??
ops.remove(persona(identity), payload, { moderator: false, actorId: identity.id })
);
},

/** @param {Identity} identity @param {Record<string, unknown>} payload */
react(identity, payload) {
return allowed(identity) ?? ops.react(persona(identity), payload);
},

/** Numa privada, as duas pessoas fixam. @param {Identity} identity @param {Record<string, unknown>} payload */
pin(identity, payload) {
return allowed(identity) ?? ops.pin(persona(identity), payload, true);
},

/** Privada não tem descrição. */
describe() {
return { ok: false, code: ERROR_CODES.NOT_ALLOWED };
},

/**
* Digitação, só para a outra pessoa — e só se ela já sabe da conversa.
* @param {Identity} identity
Expand Down
14 changes: 14 additions & 0 deletions backend/src/room/hub.js
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,20 @@ export const createHub = ({
return found.conversation.post(found.identity, payload);
},

/**
* Editar, apagar, reagir, fixar ou mudar a descrição, numa conversa
* de que a conexão participa. Permissão decidida pela conversa.
* @param {unknown} member
* @param {Record<string, unknown>} payload
* @param {"edit" | "removeMessage" | "react" | "pin" | "describe"} action
* @returns {{ok: true} | {ok: false, code: string, until?: string}}
*/
conversationAction(member, payload, action) {
const found = resolveConversation(member, payload.conversationId);
if (!found.ok) return found;
return found.conversation[action](found.identity, payload);
},

/**
* Procura alguém conectado pelo @ EXATO. Nunca lista, completa ou
* sugere: sem o @ certo, nada aparece. Quem bloqueou você também não
Expand Down
Loading
Loading