Move everything to src folder... it had to happen
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
// @ts-check
|
||||
|
||||
const assert = require("assert").strict
|
||||
const Ty = require("../../types")
|
||||
|
||||
const passthrough = require("../../passthrough")
|
||||
const {discord, sync, db, select} = passthrough
|
||||
/** @type {import("../converters/utils")} */
|
||||
const utils = sync.require("../converters/utils")
|
||||
/** @type {import("../converters/emoji")} */
|
||||
const emoji = sync.require("../converters/emoji")
|
||||
|
||||
/**
|
||||
* @param {Ty.Event.Outer<Ty.Event.M_Reaction>} event
|
||||
*/
|
||||
async function addReaction(event) {
|
||||
const channelID = select("channel_room", "channel_id", {room_id: event.room_id}).pluck().get()
|
||||
if (!channelID) return // We just assume the bridge has already been created
|
||||
const messageID = select("event_message", "message_id", {event_id: event.content["m.relates_to"].event_id}, "ORDER BY reaction_part").pluck().get()
|
||||
if (!messageID) return // Nothing can be done if the parent message was never bridged.
|
||||
|
||||
const key = event.content["m.relates_to"].key
|
||||
const discordPreferredEncoding = emoji.encodeEmoji(key, event.content.shortcode)
|
||||
if (!discordPreferredEncoding) return
|
||||
|
||||
await discord.snow.channel.createReaction(channelID, messageID, discordPreferredEncoding) // acting as the discord bot itself
|
||||
|
||||
db.prepare("REPLACE INTO reaction (hashed_event_id, message_id, encoded_emoji) VALUES (?, ?, ?)").run(utils.getEventIDHash(event.event_id), messageID, discordPreferredEncoding)
|
||||
}
|
||||
|
||||
module.exports.addReaction = addReaction
|
||||
@@ -0,0 +1,99 @@
|
||||
// @ts-check
|
||||
|
||||
const assert = require("assert").strict
|
||||
const DiscordTypes = require("discord-api-types/v10")
|
||||
const {Readable} = require("stream")
|
||||
const passthrough = require("../../passthrough")
|
||||
const {discord, db, select} = passthrough
|
||||
|
||||
/**
|
||||
* Look in the database to find webhook credentials for a channel.
|
||||
* (Note that the credentials may be invalid and need to be re-created if the webhook was interfered with from outside.)
|
||||
* @param {string} channelID
|
||||
* @param {boolean} forceCreate create a new webhook no matter what the database says about the state
|
||||
* @returns id and token for a webhook for that channel
|
||||
*/
|
||||
async function ensureWebhook(channelID, forceCreate = false) {
|
||||
if (!forceCreate) {
|
||||
const row = select("webhook", ["webhook_id", "webhook_token"], {channel_id: channelID}).get()
|
||||
if (row) {
|
||||
return {
|
||||
id: row.webhook_id,
|
||||
token: row.webhook_token,
|
||||
created: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we got here, we need to create a new webhook.
|
||||
const webhook = await discord.snow.webhook.createWebhook(channelID, {name: "Out Of Your Element: Matrix Bridge"})
|
||||
assert(webhook.token)
|
||||
db.prepare("REPLACE INTO webhook (channel_id, webhook_id, webhook_token) VALUES (?, ?, ?)").run(channelID, webhook.id, webhook.token)
|
||||
return {
|
||||
id: webhook.id,
|
||||
token: webhook.token,
|
||||
created: true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} channelID
|
||||
* @param {(webhook: import("../../types").WebhookCreds) => Promise<T>} callback
|
||||
* @returns Promise<T>
|
||||
* @template T
|
||||
*/
|
||||
async function withWebhook(channelID, callback) {
|
||||
const webhook = await ensureWebhook(channelID, false)
|
||||
return callback(webhook).catch(async e => {
|
||||
if (e.message === `{"message": "Unknown Webhook", "code": 10015}`) { // pathetic error handling from SnowTransfer
|
||||
// Our webhook is gone. Maybe somebody deleted it, or removed and re-added OOYE from the guild.
|
||||
const newWebhook = await ensureWebhook(channelID, true)
|
||||
return callback(newWebhook) // not caught; if the error happens again just throw it instead of looping
|
||||
}
|
||||
|
||||
throw e
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} channelID
|
||||
* @param {DiscordTypes.RESTPostAPIWebhookWithTokenJSONBody & {files?: {name: string, file: Buffer | Readable}[]}} data
|
||||
* @param {string} [threadID]
|
||||
*/
|
||||
async function sendMessageWithWebhook(channelID, data, threadID) {
|
||||
const result = await withWebhook(channelID, async webhook => {
|
||||
return discord.snow.webhook.executeWebhook(webhook.id, webhook.token, data, {wait: true, thread_id: threadID})
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} channelID
|
||||
* @param {string} messageID
|
||||
* @param {DiscordTypes.RESTPatchAPIWebhookWithTokenMessageJSONBody & {files?: {name: string, file: Buffer | Readable}[]}} data
|
||||
* @param {string} [threadID]
|
||||
*/
|
||||
async function editMessageWithWebhook(channelID, messageID, data, threadID) {
|
||||
const result = await withWebhook(channelID, async webhook => {
|
||||
return discord.snow.webhook.editWebhookMessage(webhook.id, webhook.token, messageID, {...data, thread_id: threadID})
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} channelID
|
||||
* @param {string} messageID
|
||||
* @param {string} [threadID]
|
||||
*/
|
||||
async function deleteMessageWithWebhook(channelID, messageID, threadID) {
|
||||
const result = await withWebhook(channelID, async webhook => {
|
||||
return discord.snow.webhook.deleteWebhookMessage(webhook.id, webhook.token, messageID, threadID)
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
module.exports.ensureWebhook = ensureWebhook
|
||||
module.exports.withWebhook = withWebhook
|
||||
module.exports.sendMessageWithWebhook = sendMessageWithWebhook
|
||||
module.exports.editMessageWithWebhook = editMessageWithWebhook
|
||||
module.exports.deleteMessageWithWebhook = deleteMessageWithWebhook
|
||||
@@ -0,0 +1,36 @@
|
||||
// @ts-check
|
||||
|
||||
const assert = require("assert")
|
||||
const fetch = require("node-fetch").default
|
||||
|
||||
const utils = require("../converters/utils")
|
||||
const {sync} = require("../../passthrough")
|
||||
|
||||
/** @type {import("../converters/emoji-sheet")} */
|
||||
const emojiSheetConverter = sync.require("../converters/emoji-sheet")
|
||||
|
||||
/**
|
||||
* Downloads the emoji from the web and converts to uncompressed PNG data.
|
||||
* @param {string} mxc a single mxc:// URL
|
||||
* @returns {Promise<Buffer | undefined>} uncompressed PNG data, or undefined if the downloaded emoji is not valid
|
||||
*/
|
||||
async function getAndConvertEmoji(mxc) {
|
||||
const abortController = new AbortController()
|
||||
|
||||
const url = utils.getPublicUrlForMxc(mxc)
|
||||
assert(url)
|
||||
|
||||
/** @type {import("node-fetch").Response} */
|
||||
// If it turns out to be a GIF, we want to abandon the connection without downloading the whole thing.
|
||||
// If we were using connection pooling, we would be forced to download the entire GIF.
|
||||
// So we set no agent to ensure we are not connection pooling.
|
||||
// @ts-ignore the signal is slightly different from the type it wants (still works fine)
|
||||
const res = await fetch(url, {agent: false, signal: abortController.signal})
|
||||
return emojiSheetConverter.convertImageStream(res.body, () => {
|
||||
abortController.abort()
|
||||
res.body.pause()
|
||||
res.body.emit("end")
|
||||
})
|
||||
}
|
||||
|
||||
module.exports.getAndConvertEmoji = getAndConvertEmoji
|
||||
@@ -0,0 +1,43 @@
|
||||
// @ts-check
|
||||
|
||||
const assert = require("assert").strict
|
||||
const Ty = require("../../types")
|
||||
|
||||
const passthrough = require("../../passthrough")
|
||||
const {discord, sync, db, select, from} = passthrough
|
||||
/** @type {import("../converters/utils")} */
|
||||
const utils = sync.require("../converters/utils")
|
||||
|
||||
/**
|
||||
* @param {Ty.Event.Outer_M_Room_Redaction} event
|
||||
*/
|
||||
async function deleteMessage(event) {
|
||||
const rows = from("event_message").join("message_channel", "message_id").select("channel_id", "message_id").where({event_id: event.redacts}).all()
|
||||
db.prepare("DELETE FROM event_message WHERE event_id = ?").run(event.event_id)
|
||||
for (const row of rows) {
|
||||
db.prepare("DELETE FROM message_channel WHERE message_id = ?").run(row.message_id)
|
||||
await discord.snow.channel.deleteMessage(row.channel_id, row.message_id, event.content.reason)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Ty.Event.Outer_M_Room_Redaction} event
|
||||
*/
|
||||
async function removeReaction(event) {
|
||||
const hash = utils.getEventIDHash(event.redacts)
|
||||
const row = from("reaction").join("message_channel", "message_id").select("channel_id", "message_id", "encoded_emoji").where({hashed_event_id: hash}).get()
|
||||
if (!row) return
|
||||
await discord.snow.channel.deleteReactionSelf(row.channel_id, row.message_id, row.encoded_emoji)
|
||||
db.prepare("DELETE FROM reaction WHERE hashed_event_id = ?").run(hash)
|
||||
}
|
||||
|
||||
/**
|
||||
* Try everything that could possibly be redacted.
|
||||
* @param {Ty.Event.Outer_M_Room_Redaction} event
|
||||
*/
|
||||
async function handle(event) {
|
||||
await deleteMessage(event)
|
||||
await removeReaction(event)
|
||||
}
|
||||
|
||||
module.exports.handle = handle
|
||||
@@ -0,0 +1,147 @@
|
||||
// @ts-check
|
||||
|
||||
const Ty = require("../../types")
|
||||
const DiscordTypes = require("discord-api-types/v10")
|
||||
const {Readable} = require("stream")
|
||||
const assert = require("assert").strict
|
||||
const crypto = require("crypto")
|
||||
const fetch = require("node-fetch").default
|
||||
const passthrough = require("../../passthrough")
|
||||
const {sync, discord, db, select} = passthrough
|
||||
|
||||
/** @type {import("./channel-webhook")} */
|
||||
const channelWebhook = sync.require("./channel-webhook")
|
||||
/** @type {import("../converters/event-to-message")} */
|
||||
const eventToMessage = sync.require("../converters/event-to-message")
|
||||
/** @type {import("../../matrix/api")}) */
|
||||
const api = sync.require("../../matrix/api")
|
||||
/** @type {import("../../d2m/actions/register-user")} */
|
||||
const registerUser = sync.require("../../d2m/actions/register-user")
|
||||
/** @type {import("../../d2m/actions/edit-message")} */
|
||||
const editMessage = sync.require("../../d2m/actions/edit-message")
|
||||
/** @type {import("../actions/emoji-sheet")} */
|
||||
const emojiSheet = sync.require("../actions/emoji-sheet")
|
||||
|
||||
/**
|
||||
* @param {DiscordTypes.RESTPostAPIWebhookWithTokenJSONBody & {files?: {name: string, file: Buffer | Readable}[], pendingFiles?: ({name: string, url: string} | {name: string, url: string, key: string, iv: string} | {name: string, buffer: Buffer | Readable})[]}} message
|
||||
* @returns {Promise<DiscordTypes.RESTPostAPIWebhookWithTokenJSONBody & {files?: {name: string, file: Buffer | Readable}[]}>}
|
||||
*/
|
||||
async function resolvePendingFiles(message) {
|
||||
if (!message.pendingFiles) return message
|
||||
const files = await Promise.all(message.pendingFiles.map(async p => {
|
||||
if ("buffer" in p) {
|
||||
return {
|
||||
name: p.name,
|
||||
file: p.buffer
|
||||
}
|
||||
}
|
||||
if ("key" in p) {
|
||||
// Encrypted file
|
||||
const d = crypto.createDecipheriv("aes-256-ctr", Buffer.from(p.key, "base64url"), Buffer.from(p.iv, "base64url"))
|
||||
// @ts-ignore
|
||||
fetch(p.url).then(res => res.body.pipe(d))
|
||||
return {
|
||||
name: p.name,
|
||||
file: d
|
||||
}
|
||||
} else {
|
||||
// Unencrypted file
|
||||
/** @type {Readable} */ // @ts-ignore
|
||||
const body = await fetch(p.url).then(res => res.body)
|
||||
return {
|
||||
name: p.name,
|
||||
file: body
|
||||
}
|
||||
}
|
||||
}))
|
||||
const newMessage = {
|
||||
...message,
|
||||
files: files.concat(message.files || [])
|
||||
}
|
||||
delete newMessage.pendingFiles
|
||||
return newMessage
|
||||
}
|
||||
|
||||
/** @param {Ty.Event.Outer_M_Room_Message | Ty.Event.Outer_M_Room_Message_File | Ty.Event.Outer_M_Sticker} event */
|
||||
async function sendEvent(event) {
|
||||
const row = select("channel_room", ["channel_id", "thread_parent"], {room_id: event.room_id}).get()
|
||||
if (!row) return // allow the bot to exist in unbridged rooms, just don't do anything with it
|
||||
let channelID = row.channel_id
|
||||
let threadID = undefined
|
||||
if (row.thread_parent) {
|
||||
threadID = channelID
|
||||
channelID = row.thread_parent // it's the thread's parent... get with the times...
|
||||
}
|
||||
// @ts-ignore
|
||||
const guildID = discord.channels.get(channelID).guild_id
|
||||
const guild = discord.guilds.get(guildID)
|
||||
assert(guild)
|
||||
|
||||
// no need to sync the matrix member to the other side. but if I did need to, this is where I'd do it
|
||||
|
||||
let {messagesToEdit, messagesToSend, messagesToDelete, ensureJoined} = await eventToMessage.eventToMessage(event, guild, {api, snow: discord.snow, fetch, mxcDownloader: emojiSheet.getAndConvertEmoji})
|
||||
|
||||
messagesToEdit = await Promise.all(messagesToEdit.map(async e => {
|
||||
e.message = await resolvePendingFiles(e.message)
|
||||
return e
|
||||
}))
|
||||
messagesToSend = await Promise.all(messagesToSend.map(message => {
|
||||
return resolvePendingFiles(message)
|
||||
}))
|
||||
|
||||
let eventPart = 0 // 0 is primary, 1 is supporting
|
||||
const pendingEdits = []
|
||||
|
||||
/** @type {DiscordTypes.APIMessage[]} */
|
||||
const messageResponses = []
|
||||
for (const data of messagesToEdit) {
|
||||
const messageResponse = await channelWebhook.editMessageWithWebhook(channelID, data.id, data.message, threadID)
|
||||
eventPart = 1
|
||||
messageResponses.push(messageResponse)
|
||||
}
|
||||
|
||||
for (const id of messagesToDelete) {
|
||||
db.prepare("DELETE FROM message_channel WHERE message_id = ?").run(id)
|
||||
db.prepare("DELETE FROM event_message WHERE message_id = ?").run(id)
|
||||
await channelWebhook.deleteMessageWithWebhook(channelID, id, threadID)
|
||||
}
|
||||
|
||||
for (const message of messagesToSend) {
|
||||
const reactionPart = messagesToEdit.length === 0 && message === messagesToSend[messagesToSend.length - 1] ? 0 : 1
|
||||
const messageResponse = await channelWebhook.sendMessageWithWebhook(channelID, message, threadID)
|
||||
db.prepare("REPLACE INTO message_channel (message_id, channel_id) VALUES (?, ?)").run(messageResponse.id, threadID || channelID)
|
||||
db.prepare("INSERT INTO event_message (event_id, event_type, event_subtype, message_id, part, reaction_part, source) VALUES (?, ?, ?, ?, ?, ?, 0)").run(event.event_id, event.type, event.content["msgtype"] || null, messageResponse.id, eventPart, reactionPart) // source 0 = matrix
|
||||
|
||||
eventPart = 1
|
||||
messageResponses.push(messageResponse)
|
||||
|
||||
/*
|
||||
If the Discord system has a cached link preview embed for one of the links just sent,
|
||||
it will be instantly added as part of `embeds` and there won't be a MESSAGE_UPDATE.
|
||||
To reflect the generated embed back to Matrix, we pretend the message was updated right away.
|
||||
*/
|
||||
const sentEmbedsCount = message.embeds?.length || 0
|
||||
if (messageResponse.embeds.length > sentEmbedsCount) {
|
||||
// not awaiting here because requests to Matrix shouldn't block requests to Discord
|
||||
pendingEdits.push(() =>
|
||||
// @ts-ignore this is a valid message edit payload
|
||||
editMessage.editMessage({
|
||||
id: messageResponse.id,
|
||||
channel_id: messageResponse.channel_id,
|
||||
guild_id: guild.id,
|
||||
embeds: messageResponse.embeds
|
||||
}, guild, null)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
for (const user of ensureJoined) {
|
||||
registerUser.ensureSimJoined(user, event.room_id)
|
||||
}
|
||||
|
||||
await Promise.all(pendingEdits.map(f => f())) // `await` will propagate any errors during editing
|
||||
|
||||
return messageResponses
|
||||
}
|
||||
|
||||
module.exports.sendEvent = sendEvent
|
||||
Reference in New Issue
Block a user