From 040a2d253ffdbdec78afc6dd2008b1e629d9caf2 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 17 Aug 2023 16:41:28 +1200 Subject: [PATCH] write editMessage action, connected to dispatcher --- d2m/actions/edit-message.js | 70 ++++++++++++++++++-------- d2m/actions/register-user.js | 4 +- d2m/converters/edit-to-changes.js | 10 ++-- d2m/converters/edit-to-changes.test.js | 4 +- d2m/event-dispatcher.js | 22 ++++++++ matrix/api.js | 14 +++++- types.d.ts | 4 ++ 7 files changed, 95 insertions(+), 33 deletions(-) diff --git a/d2m/actions/edit-message.js b/d2m/actions/edit-message.js index 6823602..9a329b6 100644 --- a/d2m/actions/edit-message.js +++ b/d2m/actions/edit-message.js @@ -1,28 +1,54 @@ -async function editMessage() { - // Action time! +// @ts-check + +const passthrough = require("../../passthrough") +const { sync, db } = passthrough +/** @type {import("../converters/edit-to-changes")} */ +const editToChanges = sync.require("../converters/edit-to-changes") +/** @type {import("../../matrix/api")} */ +const api = sync.require("../../matrix/api") + +/** + * @param {import("discord-api-types/v10").GatewayMessageCreateDispatchData} message + * @param {import("discord-api-types/v10").APIGuild} guild + */ +async function editMessage(message, guild) { + console.log(`*** applying edit for message ${message.id} in channel ${message.channel_id}`) + const {roomID, eventsToRedact, eventsToReplace, eventsToSend, senderMxid} = await editToChanges.editToChanges(message, guild, api) + console.log("making these changes:", {eventsToRedact, eventsToReplace, eventsToSend}) // 1. Replace all the things. + for (const {oldID, newContent} of eventsToReplace) { + const eventType = newContent.$type + /** @type {Pick> & { $type?: string }} */ + const newContentWithoutType = {...newContent} + delete newContentWithoutType.$type - - // 2. Redact all the things. - - // 3. Send all the things. - - // old code lies here - let eventPart = 0 // TODO: what to do about eventPart when editing? probably just need to make sure that exactly 1 value of '0' remains in the database? - for (const event of events) { - const eventType = event.$type - /** @type {Pick> & { $type?: string }} */ - const eventWithoutType = {...event} - delete eventWithoutType.$type - - const eventID = await api.sendEvent(roomID, eventType, event, senderMxid) - db.prepare("INSERT INTO event_message (event_id, message_id, channel_id, part, source) VALUES (?, ?, ?, ?, 1)").run(eventID, message.id, message.channel_id, eventPart) // source 1 = discord - - eventPart = 1 // TODO: use more intelligent algorithm to determine whether primary or supporting - eventIDs.push(eventID) + await api.sendEvent(roomID, eventType, newContentWithoutType, senderMxid) + // Ensure the database is up to date. + // The columns are event_id, event_type, event_subtype, message_id, channel_id, part, source. Only event_subtype could potentially be changed by a replacement event. + const subtype = newContentWithoutType.msgtype ?? null + db.prepare("UPDATE event_message SET event_subtype = ? WHERE event_id = ?").run(subtype, oldID) } - return eventIDs + // 2. Redact all the things. + // Not redacting as the last action because the last action is likely to be shown in the room preview in clients, and we don't want it to look like somebody actually deleted a message. + for (const eventID of eventsToRedact) { + await api.redactEvent(roomID, eventID, senderMxid) + // TODO: I should almost certainly remove the redacted event from our database now, shouldn't I? I mean, it's literally not there any more... you can't do anything else with it... + // TODO: If I just redacted part = 0, I should update one of the other events to make it the new part = 0, right? + // TODO: Consider whether this code could be reused between edited messages and deleted messages. + } -{eventsToReplace, eventsToRedact, eventsToSend} + // 3. Send all the things. + for (const content of eventsToSend) { + const eventType = content.$type + /** @type {Pick> & { $type?: string }} */ + const contentWithoutType = {...content} + delete contentWithoutType.$type + + const eventID = await api.sendEvent(roomID, eventType, contentWithoutType, senderMxid) + db.prepare("INSERT INTO event_message (event_id, event_type, event_subtype, message_id, channel_id, part, source) VALUES (?, ?, ?, ?, ?, 1, 1)").run(eventID, eventType, content.msgtype || null, message.id, message.channel_id) // part 1 = supporting; source 1 = discord + } +} + +module.exports.editMessage = editMessage diff --git a/d2m/actions/register-user.js b/d2m/actions/register-user.js index beb24bd..1455360 100644 --- a/d2m/actions/register-user.js +++ b/d2m/actions/register-user.js @@ -43,7 +43,7 @@ async function createSim(user) { * Ensure a sim is registered for the user. * If there is already a sim, use that one. If there isn't one yet, register a new sim. * @param {import("discord-api-types/v10").APIUser} user - * @returns mxid + * @returns {Promise} mxid */ async function ensureSim(user) { let mxid = null @@ -60,7 +60,7 @@ async function ensureSim(user) { * Ensure a sim is registered for the user and is joined to the room. * @param {import("discord-api-types/v10").APIUser} user * @param {string} roomID - * @returns mxid + * @returns {Promise} mxid */ async function ensureSimJoined(user, roomID) { // Ensure room ID is really an ID, not an alias diff --git a/d2m/converters/edit-to-changes.js b/d2m/converters/edit-to-changes.js index f055c90..4e6892d 100644 --- a/d2m/converters/edit-to-changes.js +++ b/d2m/converters/edit-to-changes.js @@ -82,7 +82,7 @@ async function editToChanges(message, guild, api) { eventsToRedact = oldEventRows // Now, everything in eventsToSend and eventsToRedact is a real change, but everything in eventsToReplace might not have actually changed! - // (Consider a MESSAGE_UPDATE for a text+image message - Discord does not allow the image to be changed, but the text might have been.) + // (Example: a MESSAGE_UPDATE for a text+image message - Discord does not allow the image to be changed, but the text might have been.) // So we'll remove entries from eventsToReplace that *definitely* cannot have changed. (This is category 4 mentioned above.) Everything remaining *may* have changed. eventsToReplace = eventsToReplace.filter(ev => { // Discord does not allow files, images, attachments, or videos to be edited. @@ -99,9 +99,9 @@ async function editToChanges(message, guild, api) { // Removing unnecessary properties before returning eventsToRedact = eventsToRedact.map(e => e.event_id) - eventsToReplace = eventsToReplace.map(e => ({oldID: e.old.event_id, new: eventToReplacementEvent(e.old.event_id, e.newFallbackContent, e.newInnerContent)})) + eventsToReplace = eventsToReplace.map(e => ({oldID: e.old.event_id, newContent: makeReplacementEventContent(e.old.event_id, e.newFallbackContent, e.newInnerContent)})) - return {eventsToReplace, eventsToRedact, eventsToSend, senderMxid} + return {roomID, eventsToReplace, eventsToRedact, eventsToSend, senderMxid} } /** @@ -111,7 +111,7 @@ async function editToChanges(message, guild, api) { * @param {T} newInnerContent * @returns {import("../../types").Event.ReplacementContent} content */ -function eventToReplacementEvent(oldID, newFallbackContent, newInnerContent) { +function makeReplacementEventContent(oldID, newFallbackContent, newInnerContent) { const content = { ...newFallbackContent, "m.mentions": {}, @@ -130,4 +130,4 @@ function eventToReplacementEvent(oldID, newFallbackContent, newInnerContent) { } module.exports.editToChanges = editToChanges -module.exports.eventToReplacementEvent = eventToReplacementEvent +module.exports.makeReplacementEventContent = makeReplacementEventContent diff --git a/d2m/converters/edit-to-changes.test.js b/d2m/converters/edit-to-changes.test.js index 8385cd0..bb3f3ec 100644 --- a/d2m/converters/edit-to-changes.test.js +++ b/d2m/converters/edit-to-changes.test.js @@ -29,7 +29,7 @@ test("edit2changes: bot response", async t => { t.deepEqual(eventsToSend, []) t.deepEqual(eventsToReplace, [{ oldID: "$fdD9OZ55xg3EAsfvLZza5tMhtjUO91Wg3Otuo96TplY", - new: { + newContent: { $type: "m.room.message", msgtype: "m.text", body: "* :ae_botrac4r: @cadence asked ``­``, I respond: Stop drinking paint. (No)\n\nHit :bn_re: to reroll.", @@ -82,7 +82,7 @@ test("edit2changes: edit of reply to skull webp attachment with content", async t.deepEqual(eventsToSend, []) t.deepEqual(eventsToReplace, [{ oldID: "$vgTKOR5ZTYNMKaS7XvgEIDaOWZtVCEyzLLi5Pc5Gz4M", - new: { + newContent: { $type: "m.room.message", msgtype: "m.text", body: "> Extremity: Image\n\n* Edit", diff --git a/d2m/event-dispatcher.js b/d2m/event-dispatcher.js index 1686b5f..4bb94ff 100644 --- a/d2m/event-dispatcher.js +++ b/d2m/event-dispatcher.js @@ -3,6 +3,9 @@ const {sync, db} = require("../passthrough") /** @type {import("./actions/send-message")}) */ const sendMessage = sync.require("./actions/send-message") +/** @type {import("./actions/edit-message")}) */ +const editMessage = sync.require("./actions/edit-message") + /** @type {import("./actions/add-reaction")}) */ const addReaction = sync.require("./actions/add-reaction") @@ -29,6 +32,25 @@ module.exports = { sendMessage.sendMessage(message, guild) }, + /** + * @param {import("./discord-client")} client + * @param {import("discord-api-types/v10").GatewayMessageUpdateDispatchData} message + */ + onMessageUpdate(client, data) { + // Based on looking at data they've sent me over the gateway, this is the best way to check for meaningful changes. + // If the message content is a string then it includes all interesting fields and is meaningful. + if (typeof data.content === "string") { + /** @type {import("discord-api-types/v10").GatewayMessageCreateDispatchData} */ + const message = data + /** @type {import("discord-api-types/v10").APIGuildChannel} */ + const channel = client.channels.get(message.channel_id) + if (!channel.guild_id) return // Nothing we can do in direct messages. + const guild = client.guilds.get(channel.guild_id) + if (message.guild_id !== "112760669178241024" && message.guild_id !== "497159726455455754") return // TODO: activate on other servers (requires the space creation flow to be done first) + editMessage.editMessage(message, guild) + } + }, + /** * @param {import("./discord-client")} client * @param {import("discord-api-types/v10").GatewayMessageReactionAddDispatchData} data diff --git a/matrix/api.js b/matrix/api.js index 9111909..ef3e199 100644 --- a/matrix/api.js +++ b/matrix/api.js @@ -14,7 +14,7 @@ const makeTxnId = sync.require("./txnid") /** * @param {string} p endpoint to access - * @param {string} [mxid] optional: user to act as, for the ?user_id parameter + * @param {string?} [mxid] optional: user to act as, for the ?user_id parameter * @param {{[x: string]: any}} [otherParams] optional: any other query parameters to add * @returns {string} the new endpoint */ @@ -119,7 +119,7 @@ async function sendState(roomID, type, stateKey, content, mxid) { * @param {string} roomID * @param {string} type * @param {any} content - * @param {string} [mxid] + * @param {string?} [mxid] * @param {number} [timestamp] timestamp of the newly created event, in unix milliseconds */ async function sendEvent(roomID, type, content, mxid, timestamp) { @@ -129,6 +129,15 @@ async function sendEvent(roomID, type, content, mxid, timestamp) { return root.event_id } +/** + * @returns {Promise} room ID + */ +async function redactEvent(roomID, eventID, mxid) { + /** @type {Ty.R.EventRedacted} */ + const root = await mreq.mreq("PUT", path(`/client/v3/rooms/${roomID}/redact/${eventID}/${makeTxnId.makeTxnId()}`, mxid)) + return root.event_id +} + async function profileSetDisplayname(mxid, displayname) { await mreq.mreq("PUT", path(`/client/v3/profile/${mxid}/displayname`, mxid), { displayname @@ -152,5 +161,6 @@ module.exports.getAllState = getAllState module.exports.getJoinedMembers = getJoinedMembers module.exports.sendState = sendState module.exports.sendEvent = sendEvent +module.exports.redactEvent = redactEvent module.exports.profileSetDisplayname = profileSetDisplayname module.exports.profileSetAvatarUrl = profileSetAvatarUrl diff --git a/types.d.ts b/types.d.ts index 76d3bd1..b9f7ed6 100644 --- a/types.d.ts +++ b/types.d.ts @@ -112,4 +112,8 @@ namespace R { export type EventSent = { event_id: string } + + export type EventRedacted = { + event_id: string + } }