Compare commits
1 commit
main
...
ex/webhook
| Author | SHA1 | Date | |
|---|---|---|---|
| 419d61cf82 |
192 changed files with 4637 additions and 23766 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -3,8 +3,6 @@ config.js
|
||||||
registration.yaml
|
registration.yaml
|
||||||
ooye.db*
|
ooye.db*
|
||||||
events.db*
|
events.db*
|
||||||
backfill.db*
|
|
||||||
custom-webroot
|
|
||||||
|
|
||||||
# Automatically generated
|
# Automatically generated
|
||||||
node_modules
|
node_modules
|
||||||
|
|
|
||||||
12
addbot.js
12
addbot.js
|
|
@ -1,27 +1,17 @@
|
||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
// @ts-check
|
// @ts-check
|
||||||
|
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
|
||||||
|
|
||||||
const {reg} = require("./src/matrix/read-registration")
|
const {reg} = require("./src/matrix/read-registration")
|
||||||
const token = reg.ooye.discord_token
|
const token = reg.ooye.discord_token
|
||||||
const id = Buffer.from(token.split(".")[0], "base64").toString()
|
const id = Buffer.from(token.split(".")[0], "base64").toString()
|
||||||
const permissions =
|
|
||||||
( DiscordTypes.PermissionFlagsBits.ManageWebhooks
|
|
||||||
| DiscordTypes.PermissionFlagsBits.ManageGuildExpressions
|
|
||||||
| DiscordTypes.PermissionFlagsBits.ManageMessages
|
|
||||||
| DiscordTypes.PermissionFlagsBits.PinMessages
|
|
||||||
| DiscordTypes.PermissionFlagsBits.UseExternalEmojis)
|
|
||||||
|
|
||||||
function addbot() {
|
function addbot() {
|
||||||
return `Open this link to add the bot to a Discord server:\nhttps://discord.com/oauth2/authorize?client_id=${id}&scope=bot&permissions=${permissions} `
|
return `Open this link to add the bot to a Discord server:\nhttps://discord.com/oauth2/authorize?client_id=${id}&scope=bot&permissions=1610883072 `
|
||||||
}
|
}
|
||||||
|
|
||||||
/* c8 ignore next 3 */
|
|
||||||
if (process.argv.find(a => a.endsWith("addbot") || a.endsWith("addbot.js"))) {
|
if (process.argv.find(a => a.endsWith("addbot") || a.endsWith("addbot.js"))) {
|
||||||
console.log(addbot())
|
console.log(addbot())
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.id = id
|
module.exports.id = id
|
||||||
module.exports.addbot = addbot
|
module.exports.addbot = addbot
|
||||||
module.exports.permissions = permissions
|
|
||||||
|
|
|
||||||
52
docs/api.md
52
docs/api.md
|
|
@ -1,52 +0,0 @@
|
||||||
# API
|
|
||||||
|
|
||||||
There is a web API for getting information about things that are bridged with Out Of Your Element.
|
|
||||||
|
|
||||||
The base URL is the URL of the particular OOYE instance, for example, https://bridge.cadence.moe.
|
|
||||||
|
|
||||||
No authentication is required.
|
|
||||||
|
|
||||||
I'm happy to add more endpoints, just ask for them.
|
|
||||||
|
|
||||||
## Endpoint: GET /api/message
|
|
||||||
|
|
||||||
|Query parameter|Type|Description|
|
|
||||||
|---------------|----|-----------|
|
|
||||||
|`message_id`|regexp `/^[0-9]+$/`|Discord message ID to look up information for|
|
|
||||||
|
|
||||||
Response:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
{
|
|
||||||
source: "matrix" | "discord" // Which platform the message originated on
|
|
||||||
matrix_author?: { // Only for Matrix messages; should be up-to-date rather than historical data
|
|
||||||
displayname: string, // Matrix user's current display name
|
|
||||||
avatar_url: string | null, // Absolute HTTP(S) URL to download the Matrix user's current avatar
|
|
||||||
mxid: string // Matrix user ID, can never change
|
|
||||||
},
|
|
||||||
events: [ // Data about each individual event
|
|
||||||
{
|
|
||||||
metadata: { // Data from OOYE's database about how bridging was performed
|
|
||||||
sender: string, // Same as matrix user ID
|
|
||||||
event_id: string, // Unique ID of the event on Matrix, can never change
|
|
||||||
event_type: "m.room.message" | string, // Event type
|
|
||||||
event_subtype: "m.text" | string | null, // For m.room.message events, this is the msgtype property
|
|
||||||
part: 0 | 1, // For multi-event messages, 0 if this is the first part
|
|
||||||
reaction_part: 0 | 1, // For multi-event messages, 0 if this is the last part
|
|
||||||
room_id: string, // Room ID that the event was sent in, linked to the Discord channel
|
|
||||||
source: number
|
|
||||||
},
|
|
||||||
raw: { // Raw historical event data from the Matrix API. Contains at least these properties:
|
|
||||||
content: any, // The only non-metadata property, entirely client-generated
|
|
||||||
type: string,
|
|
||||||
room_id: string,
|
|
||||||
sender: string,
|
|
||||||
origin_server_ts: number,
|
|
||||||
unsigned?: any,
|
|
||||||
event_id: string,
|
|
||||||
user_id: string
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
@ -1,129 +0,0 @@
|
||||||
# Development setup
|
|
||||||
|
|
||||||
* Install development dependencies with `npm install --save-dev` so you can run the tests.
|
|
||||||
* Most files you change, such as actions, converters, and web, will automatically be reloaded.
|
|
||||||
* If developing on a different computer to the one running the homeserver, use SSH port forwarding so that Synapse can connect on its `localhost:6693` to reach the running bridge on your computer. Example: `ssh -T -v -R 6693:localhost:6693 me@matrix.cadence.moe`
|
|
||||||
* I recommend developing in Visual Studio Code so that the JSDoc x TypeScript annotation comments just work automatically. I don't know which other editors or language servers support annotations and type inference.
|
|
||||||
|
|
||||||
# Efficiency details
|
|
||||||
|
|
||||||
Using WeatherStack as a thin layer between the bridge application and the Discord API lets us control exactly what data is cached in memory. Only necessary information is cached. For example, member data, user data, message content, and past edits are never stored in memory. This keeps the memory usage low and also prevents it ballooning in size over the bridge's runtime.
|
|
||||||
|
|
||||||
The bridge uses a small SQLite database to store relationships like which Discord messages correspond to which Matrix messages. This is so the bridge knows what to edit when some message is edited on Discord. Using `without rowid` on the database tables stores the index and the data in the same B-tree. Since Matrix and Discord's internal IDs are quite long, this vastly reduces storage space because those IDs do not have to be stored twice separately. Some event IDs and URLs are actually stored as xxhash integers to reduce storage requirements even more. On my personal instance of OOYE, every 300,000 messages (representing a year of conversations) requires 40.6 MB of storage space in the SQLite database.
|
|
||||||
|
|
||||||
Only necessary data and columns are queried from the database. We only contact the homeserver API if the database doesn't contain what we need.
|
|
||||||
|
|
||||||
File uploads (like avatars from bridged members) are checked locally and deduplicated. Only brand new files are uploaded to the homeserver. This saves loads of space in the homeserver's media repo, especially for Synapse.
|
|
||||||
|
|
||||||
Switching to [WAL mode](https://www.sqlite.org/wal.html) could improve your database access speed even more. Run `node scripts/wal.js` if you want to switch to WAL mode. (This will also enable `synchronous = NORMAL`.)
|
|
||||||
|
|
||||||
|
|
||||||
# Repository structure
|
|
||||||
|
|
||||||
.
|
|
||||||
* Runtime configuration, like tokens and user info:
|
|
||||||
├── registration.yaml
|
|
||||||
* You are here! :)
|
|
||||||
├── readme.md
|
|
||||||
* The bridge's SQLite database is stored here:
|
|
||||||
├── ooye.db*
|
|
||||||
* Source code
|
|
||||||
└── src
|
|
||||||
* Database schema:
|
|
||||||
├── db
|
|
||||||
│ ├── orm.js, orm-defs.d.ts
|
|
||||||
│ * Migrations change the database schema when you update to a newer version of OOYE:
|
|
||||||
│ ├── migrate.js
|
|
||||||
│ └── migrations
|
|
||||||
│ └── *.sql, *.js
|
|
||||||
* Discord-to-Matrix bridging:
|
|
||||||
├── d2m
|
|
||||||
│ * Execute actions through the whole flow, like sending a Discord message to Matrix:
|
|
||||||
│ ├── actions
|
|
||||||
│ │ └── *.js
|
|
||||||
│ * Convert data from one form to another without depending on bridge state. Called by actions:
|
|
||||||
│ ├── converters
|
|
||||||
│ │ └── *.js
|
|
||||||
│ * Making Discord work:
|
|
||||||
│ ├── discord-*.js
|
|
||||||
│ * Listening to events from Discord and dispatching them to the correct `action`:
|
|
||||||
│ └── event-dispatcher.js
|
|
||||||
* Discord bot commands and menus:
|
|
||||||
├── discord
|
|
||||||
│ ├── interactions
|
|
||||||
│ │ └── *.js
|
|
||||||
│ └── discord-command-handler.js
|
|
||||||
* Matrix-to-Discord bridging:
|
|
||||||
├── m2d
|
|
||||||
│ * Execute actions through the whole flow, like sending a Matrix message to Discord:
|
|
||||||
│ ├── actions
|
|
||||||
│ │ └── *.js
|
|
||||||
│ * Convert data from one form to another without depending on bridge state. Called by actions:
|
|
||||||
│ ├── converters
|
|
||||||
│ │ └── *.js
|
|
||||||
│ * Listening to events from Matrix and dispatching them to the correct `action`:
|
|
||||||
│ └── event-dispatcher.js
|
|
||||||
* We aren't using the matrix-js-sdk, so here are all the functions for the Matrix C-S and Appservice APIs:
|
|
||||||
├── matrix
|
|
||||||
│ └── *.js
|
|
||||||
* Various files you can run once if you need them.
|
|
||||||
└── scripts
|
|
||||||
* First time running a new bridge? Run this file to set up prerequisites on the Matrix server:
|
|
||||||
├── setup.js
|
|
||||||
* Hopefully you won't need the rest of these. Code quality varies wildly.
|
|
||||||
└── *.js
|
|
||||||
|
|
||||||
# Read next
|
|
||||||
|
|
||||||
If you haven't set up Out Of Your Element yet, you might find [Simplified homeserver setup](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/simplified-homeserver-setup.md) helpful.
|
|
||||||
|
|
||||||
If you don't know what the Matrix event JSON generally looks like, turn on developer tools in your client (Element has pretty good ones). Right click a couple of messages and see what they look like on the inside.
|
|
||||||
|
|
||||||
I recommend first reading [How to add a new event type](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/how-to-add-a-new-event-type.md) as this will fill you in on key information in how the codebase is organised, which data structures are important, and what level of abstraction we're working on.
|
|
||||||
|
|
||||||
If you haven't seen the [Discord API documentation](https://discord.com/developers/docs/) before, have a quick look at one of the pages on there. Same with the [Matrix Client-Server APIs](https://spec.matrix.org/latest/client-server-api/). You don't need to know these inside out, they're primarily references, not stories. But it is useful to have an idea of what a couple of the API endpoints look like, the kind of data they tend to accept, and the kind of data they tend to return.
|
|
||||||
|
|
||||||
Then you might like to peruse the other files in the docs folder. Most of these were written stream-of-thought style as I try to work through a problem and find the best way to implement it. You might enjoy getting inside my head and seeing me invent and evaluate ways to solve the problem.
|
|
||||||
|
|
||||||
Whether you read those or not, I'm more than happy to help you 1-on-1 with coding your dream feature. Join the chatroom [#out-of-your-element:cadence.moe](https://matrix.to/#/#out-of-your-element:cadence.moe) or PM me [@cadence:cadence.moe](https://matrix.to/#/@cadence:cadence.moe) and ask away.
|
|
||||||
|
|
||||||
# Dependency justification
|
|
||||||
|
|
||||||
Total transitive production dependencies: 134
|
|
||||||
|
|
||||||
### <font size="+2">🦕</font>
|
|
||||||
|
|
||||||
* (31) better-sqlite3: SQLite is the best database, and this is the best library for it.
|
|
||||||
* (27) @cloudrac3r/pug: Language for dynamic web pages. This is my fork. (I released code that hadn't made it to npm, and removed the heavy pug-filters feature.)
|
|
||||||
* (16) stream-mime-type@1: This seems like the best option. Version 1 is used because version 2 is ESM-only.
|
|
||||||
* (9) h3: Web server. OOYE needs this for the appservice listener, authmedia proxy, self-service, and more.
|
|
||||||
* (11) sharp: Image resizing and compositing. OOYE needs this for the emoji sprite sheets.
|
|
||||||
|
|
||||||
### <font size="-1">🪱</font>
|
|
||||||
|
|
||||||
* (0) @chriscdn/promise-semaphore: It does what I want.
|
|
||||||
* (1) @cloudrac3r/discord-markdown: This is my fork.
|
|
||||||
* (0) @cloudrac3r/giframe: This is my fork.
|
|
||||||
* (1) @cloudrac3r/html-template-tag: This is my fork.
|
|
||||||
* (0) @cloudrac3r/in-your-element: This is my Matrix Appservice API library. It depends on h3 and zod, which are already pulled in by OOYE.
|
|
||||||
* (0) @cloudrac3r/mixin-deep: This is my fork. (It fixes a bug in regular mixin-deep.)
|
|
||||||
* (0) @cloudrac3r/pngjs: Lottie stickers are converted to bitmaps with the vendored Rlottie WASM build, then the bitmaps are converted to PNG with pngjs.
|
|
||||||
* (0) @cloudrac3r/turndown: This HTML-to-Markdown converter looked the most suitable. I forked it to change the escaping logic to match the way Discord works.
|
|
||||||
* (3) @stackoverflow/stacks: Stack Overflow design language and icons.
|
|
||||||
* (0) ansi-colors: Helps with interactive prompting for the initial setup, and it's already pulled in by enquirer.
|
|
||||||
* (1) chunk-text: It does what I want.
|
|
||||||
* (0) cloudstorm: Discord gateway library with bring-your-own-caching that I trust.
|
|
||||||
* (0) discord-api-types: Bitfields needed at runtime and types needed for development.
|
|
||||||
* (0) domino: DOM implementation that's already pulled in by turndown.
|
|
||||||
* (1) enquirer: Interactive prompting for the initial setup rather than forcing users to edit YAML non-interactively.
|
|
||||||
* (0) entities: Looks fine. No dependencies.
|
|
||||||
* (0) get-relative-path: Looks fine. No dependencies.
|
|
||||||
* (1) heatsync: Module hot-reloader that I trust.
|
|
||||||
* (0) lru-cache: For holding unused nonce in memory and letting them be overwritten later if never used.
|
|
||||||
* (0) mime-type: File extension to mime type mapping that's already pulled in by stream-mime-type.
|
|
||||||
* (0) prettier-bytes: It does what I want and has no dependencies.
|
|
||||||
* (0) snowtransfer: Discord API library with bring-your-own-caching that I trust.
|
|
||||||
* (0) try-to-catch: Not strictly necessary, but it's already pulled in by supertape, so I may as well.
|
|
||||||
* (0) uqr: QR code SVG generator. Used on the website to scan in an invite link.
|
|
||||||
* (0) xxhash-wasm: Used where cryptographically secure hashing is not required.
|
|
||||||
* (0) zod: Input validation for the web server. It's popular and easy to use.
|
|
||||||
|
|
@ -1,76 +0,0 @@
|
||||||
# Docker policy
|
|
||||||
|
|
||||||
**Out Of Your Element has no official support for Docker. There are no official files or images. If you choose to run Out Of Your Element in Docker, you must disclose this when asking for support. I may refuse to provide support/advice at any time. I may refuse to acknowledge issue reports.**
|
|
||||||
|
|
||||||
This also goes for Podman, Nix, and other similar technology that upends a program's understanding of what it's running on.
|
|
||||||
|
|
||||||
## What I recommend
|
|
||||||
|
|
||||||
I recommend [following the official setup guide,](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/get-started.md) which does not use Docker.
|
|
||||||
|
|
||||||
Ultimately, though, do what makes you happy. I can't stop you from doing what you want. As long as you read this page and understand my perspective, that's good enough for me.
|
|
||||||
|
|
||||||
## Why I advise against Docker
|
|
||||||
|
|
||||||
When misconfigured, Docker has terrible impacts. It can cause messages to go missing or even permanent data loss. These have happened to people.
|
|
||||||
|
|
||||||
Docker also makes it much harder for me to advise on debugging because it puts barriers between you and useful debugging tools, such as stdin, the database file, a shell, and the inspector. It's also not clear which version of the source code is running in the container, as there are many pieces of Docker (builder, container, image) that can cache old data, often making it so you didn't actually update when you thought you did. This has happened to people.
|
|
||||||
|
|
||||||
## Why I don't provide a good configuration myself
|
|
||||||
|
|
||||||
It is not possible for Docker to be correctly configured by default. The defaults are broken and will cause data loss.
|
|
||||||
|
|
||||||
It is also not possible for me to provide a correct configuration for everyone. Even if I provided a correct image, the YAMLs and command-line arguments must be written by individual end users. Incorrect YAMLs and command-line arguments may cause connection issues or permanent data loss.
|
|
||||||
|
|
||||||
## Why I don't provide assistance if you run OOYE in Docker
|
|
||||||
|
|
||||||
Problems you encounter, especially with the initial setup, are much more likely to be caused by nuances in your Docker setup than problems in my code. Therefore, my code is not responsible for the problem. The cause of the problem is different code that I can't advise on.
|
|
||||||
|
|
||||||
Also, if you reported an issue and I asked for additional information to help find the cause, you might be unable to provide it because of the debugging barriers discussed above.
|
|
||||||
|
|
||||||
## Why I don't provide Docker resources
|
|
||||||
|
|
||||||
I create OOYE unpaid in my spare time because I enjoy the process. I find great enjoyment in creating code and none at all in creating infrastructure.
|
|
||||||
|
|
||||||
## Why you're probably fine without Docker
|
|
||||||
|
|
||||||
### If you care about system footprint
|
|
||||||
|
|
||||||
OOYE was designed to be simple and courteous:
|
|
||||||
|
|
||||||
* It only creates files in its working directory
|
|
||||||
* It does not require any other processes to be running (e.g., no dependency on a Postgres process)
|
|
||||||
* It only requires node/npm executables in PATH, which you can store in any folder if you don't want to use your package manager
|
|
||||||
|
|
||||||
### If you care about ease of setup
|
|
||||||
|
|
||||||
In my opinion, the [official setup process](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/get-started.md) is straightforward. After installing prerequisites (Node.js and the repo clone), the rest of the process interactively guides you through providing necessary information. Your input is checked for correctness so the bridge will definitely work when you run it.
|
|
||||||
|
|
||||||
I find this easier than the usual Docker workflow of pasting values into a YAML and rolling the dice on whether it will start up or not.
|
|
||||||
|
|
||||||
### If you care about security in the case of compromise/RCE
|
|
||||||
|
|
||||||
There are no known vulnerabilities in dependencies. I [carefully selected simple, light dependencies](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/developer-orientation.md#dependency-justification) to reduce attack surface area.
|
|
||||||
|
|
||||||
For defense in depth, I suggest running OOYE as a different user.
|
|
||||||
|
|
||||||
### If you want to see all the processes when you run docker ps
|
|
||||||
|
|
||||||
Well, you got me there.
|
|
||||||
|
|
||||||
## Unofficial, independent, community-provided container setups
|
|
||||||
|
|
||||||
I acknowledge the demand for using OOYE in a container, so I will still point you in the right direction.
|
|
||||||
|
|
||||||
I had no hand in creating these and have not used or tested them whatsoever. I make no assurance that these will work reliably, or even at all. If you use these, you must do so with the understanding that if you run into any problems, **you must ask for support from the author of that setup, not from me, because you're running their code, not mine.**
|
|
||||||
|
|
||||||
***The following list is distributed for your information, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.***
|
|
||||||
|
|
||||||
- by melody: https://git.shork.ch/docker-images/out-of-your-element
|
|
||||||
- by sim2kid: https://github.com/sim2kid/ooye-docker
|
|
||||||
- by Katharos Technology: https://github.com/katharostech/docker_ooye
|
|
||||||
- by Emma: https://cgit.rory.gay/nix/OOYE-module.git/tree
|
|
||||||
|
|
||||||
## Making your own Docker setup
|
|
||||||
|
|
||||||
If you decide to make your own, I may provide advice or indicate problems at my discretion. You acknowledge that I am not required to provide evidence of problems I indicate, nor solutions to them. You acknowledge that it is not possible for me to exhaustively indicate every problem, so I cannot indicate correctness. Even if I have provided advice to an unofficial, independent, community-provided setup, I do not endorse it.
|
|
||||||
|
|
@ -1,98 +0,0 @@
|
||||||
# Foreign keys in the Out Of Your Element database
|
|
||||||
|
|
||||||
Historically, Out Of Your Element did not use foreign keys in the database, but since I found a need for them, I have decided to add them. Referential integrity is probably valuable as well.
|
|
||||||
|
|
||||||
The need is that unlinking a channel and room using the web interface should clear up all related entries from `message_channel`, `event_message`, `reaction`, etc. Without foreign keys, this requires multiple DELETEs with tricky queries. With foreign keys and ON DELETE CASCADE, this just works.
|
|
||||||
|
|
||||||
## Quirks
|
|
||||||
|
|
||||||
* **REPLACE INTO** internally causes a DELETE followed by an INSERT, and the DELETE part **will trigger any ON DELETE CASCADE** foreign key conditions on the table, even when the primary key being replaced is the same.
|
|
||||||
* ```sql
|
|
||||||
CREATE TABLE discord_channel (channel_id TEXT NOT NULL, name TEXT NOT NULL, PRIMARY KEY (channel_id));
|
|
||||||
CREATE TABLE discord_message (message_id TEXT NOT NULL, channel_id TEXT NOT NULL, PRIMARY KEY (message_id),
|
|
||||||
FOREIGN KEY (channel_id) REFERENCES discord_channel (channel_id) ON DELETE CASCADE);
|
|
||||||
INSERT INTO discord_channel (channel_id, name) VALUES ("c_1", "place");
|
|
||||||
INSERT INTO discord_message (message_id, channel_id) VALUES ("m_2", "c_1"); -- i love my message
|
|
||||||
REPLACE INTO discord_channel (channel_id, name) VALUES ("c_1", "new place"); -- replace into time
|
|
||||||
-- i love my message
|
|
||||||
SELECT * FROM discord_message; -- where is my message
|
|
||||||
```
|
|
||||||
* In SQLite, `pragma foreign_keys = on` must be set **for each connection** after it's established. I've added this at the start of `migrate.js`, which is called by all database connections.
|
|
||||||
* Pragma? Pragma keys
|
|
||||||
* Whenever a child row is inserted, SQLite will look up a row from the parent table to ensure referential integrity. This means **the parent table should be sufficiently keyed or indexed on columns referenced by foreign keys**, or SQLite won't let you do it, with a cryptic error message later on during DML. Due to normal forms, foreign keys naturally tend to reference the parent table's primary key, which is indexed, so that's okay. But still keep this in mind, since many of OOYE's tables effectively have two primary keys, for the Discord and Matrix IDs. A composite primary key doesn't count, even when it's the first column. A unique index counts.
|
|
||||||
|
|
||||||
## Where keys
|
|
||||||
|
|
||||||
Here are some tables that could potentially have foreign keys added between them, and my thought process of whether foreign keys would be a good idea:
|
|
||||||
|
|
||||||
* `guild_active` <--(PK guild_id FK)-- `channel_room` ✅
|
|
||||||
* Could be good for referential integrity.
|
|
||||||
* Linking to guild_space would be pretty scary in case the guild was being relinked to a different space - since rooms aren't tied to a space, this wouldn't actually disturb anything. So I pick guild_active instead.
|
|
||||||
* `channel_room` <--(PK channel_id FK)-- `message_channel` ✅
|
|
||||||
* Seems useful as we want message records to be deleted when a channel is unlinked.
|
|
||||||
* `message_channel` <--(PK message_id PK)-- `event_message` ✅
|
|
||||||
* Seems useful as we want event information to be deleted when a channel is unlinked.
|
|
||||||
* `guild_active` <--(PK guild_id PK)-- `guild_space` ✅
|
|
||||||
* All bridged guilds should have a corresponding guild_active entry, so referential integrity would be useful here to make sure we haven't got any weird states.
|
|
||||||
* `channel_room` <--(**C** room_id PK)-- `member_cache` ✅
|
|
||||||
* Seems useful as we want to clear the member cache when a channel is unlinked.
|
|
||||||
* There is no index on `channel_room.room_id` right now. It would be good to create this index. Will just make it UNIQUE in the table definition.
|
|
||||||
* `message_channel` <--(PK message_id FK)-- `reaction` ✅
|
|
||||||
* Seems useful as we want to clear the reactions cache when a channel is unlinked.
|
|
||||||
* `sim` <--(**C** mxid FK)-- `sim_member`
|
|
||||||
* OOYE inner joins on this.
|
|
||||||
* Sims are never deleted so if this was added it would only be used for enforcing referential integrity.
|
|
||||||
* The storage cost of the additional index on `sim` would not be worth the benefits.
|
|
||||||
* `channel_room` <--(**C** room_id PK)-- `sim_member`
|
|
||||||
* If a room is being permanently unlinked, it may be useful to see a populated member list. If it's about to be relinked to another channel, we want to keep the sims in the room for more speed and to avoid spamming state events into the timeline.
|
|
||||||
* Either way, the sims could remain in the room even after it's been unlinked. So no referential integrity is desirable here.
|
|
||||||
* `sim` <--(PK user_id PK)-- `sim_proxy`
|
|
||||||
* OOYE left joins on this. In normal operation, this relationship might not exist.
|
|
||||||
* `channel_room` <--(PK channel_id PK)-- `webhook` ✅
|
|
||||||
* Seems useful. Webhooks should be deleted from Discord just before the channel is unlinked. That should be mirrored in the database too.
|
|
||||||
|
|
||||||
## Occurrences of REPLACE INTO/DELETE FROM
|
|
||||||
|
|
||||||
* `edit-message.js` — `REPLACE INTO message_channel`
|
|
||||||
* Scary! Changed to INSERT OR IGNORE
|
|
||||||
* `send-message.js` — `REPLACE INTO message_channel`
|
|
||||||
* Changed to INSERT OR IGNORE
|
|
||||||
* `add-reaction.js` — `REPLACE INTO reaction`
|
|
||||||
* `channel-webhook.js` — `REPLACE INTO webhook`
|
|
||||||
* `send-event.js` — `REPLACE INTO message_channel`
|
|
||||||
* Seems incorrect? Maybe?? Originally added in fcbb045. Changed to INSERT
|
|
||||||
* `event-to-message.js` — `REPLACE INTO member_cache`
|
|
||||||
* `oauth.js` — `REPLACE INTO guild_active`
|
|
||||||
* Very scary!! Changed to INSERT .. ON CONFLICT DO UPDATE
|
|
||||||
* `create-room.js` — `DELETE FROM channel_room`
|
|
||||||
* Please cascade
|
|
||||||
* `delete-message.js`
|
|
||||||
* Removed redundant DELETEs
|
|
||||||
* `edit-message.js` — `DELETE FROM event_message`
|
|
||||||
* `register-pk-user.js` — `DELETE FROM sim`
|
|
||||||
* It's a failsafe during creation
|
|
||||||
* `register-user.js` — `DELETE FROM sim`
|
|
||||||
* It's a failsafe during creation
|
|
||||||
* `remove-reaction.js` — `DELETE FROM reaction`
|
|
||||||
* `event-dispatcher.js` — `DELETE FROM member_cache`
|
|
||||||
* `redact.js` — `DELETE FROM event_message`
|
|
||||||
* Removed this redundant DELETE
|
|
||||||
* `send-event.js` — `DELETE FROM event_message`
|
|
||||||
* Removed this redundant DELETE
|
|
||||||
|
|
||||||
## How keys
|
|
||||||
|
|
||||||
SQLite does not have a complete ALTER TABLE command, so I have to DROP and CREATE. According to [the docs](https://www.sqlite.org/lang_altertable.html), the correct strategy is:
|
|
||||||
|
|
||||||
1. (Not applicable) *If foreign key constraints are enabled, disable them using PRAGMA foreign_keys=OFF.*
|
|
||||||
2. Start a transaction.
|
|
||||||
3. (Not applicable) *Remember the format of all indexes, triggers, and views associated with table X. This information will be needed in step 8 below. One way to do this is to run a query like the following: SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'.*
|
|
||||||
4. Use CREATE TABLE to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
|
|
||||||
5. Transfer content from X into new_X using a statement like: INSERT INTO new_X SELECT ... FROM X.
|
|
||||||
6. Drop the old table X: DROP TABLE X.
|
|
||||||
7. Change the name of new_X to X using: ALTER TABLE new_X RENAME TO X.
|
|
||||||
8. (Not applicable) *Use CREATE INDEX, CREATE TRIGGER, and CREATE VIEW to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration.*
|
|
||||||
9. (Not applicable) *If any views refer to table X in a way that is affected by the schema change, then drop those views using DROP VIEW and recreate them with whatever changes are necessary to accommodate the schema change using CREATE VIEW.*
|
|
||||||
10. If foreign key constraints were originally enabled then run PRAGMA foreign_key_check to verify that the schema change did not break any foreign key constraints.
|
|
||||||
11. Commit the transaction started in step 2.
|
|
||||||
12. (Not applicable) *If foreign keys constraints were originally enabled, reenable them now.*
|
|
||||||
|
|
@ -1,116 +0,0 @@
|
||||||
# Setup
|
|
||||||
|
|
||||||
If you want Docker, [please read this first.](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/docker.md)
|
|
||||||
|
|
||||||
If you get stuck, you're welcome to message [#out-of-your-element:cadence.moe](https://matrix.to/#/#out-of-your-element:cadence.moe) or [@cadence:cadence.moe](https://matrix.to/#/@cadence:cadence.moe) to ask for help setting up OOYE!
|
|
||||||
|
|
||||||
You'll need:
|
|
||||||
|
|
||||||
* Administrative access to a homeserver
|
|
||||||
* Discord bot
|
|
||||||
* Domain name for the bridge's website - [more info](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/why-does-the-bridge-have-a-website.md)
|
|
||||||
* Reverse proxy for that domain - an interactive process will help you set this up in step 5!
|
|
||||||
|
|
||||||
Follow these steps:
|
|
||||||
|
|
||||||
1. [Get Node.js version 22 or later](https://nodejs.org/en/download/prebuilt-installer). If you're on Linux, you may prefer to install through system's package manager, though Debian and Ubuntu have hopelessly out of date packages.
|
|
||||||
|
|
||||||
1. Switch to a normal user account. (i.e. do not run any of the following commands as root or sudo.)
|
|
||||||
|
|
||||||
1. Clone this repo and checkout a specific tag. (Development happens on main. Stable versions are tagged.)
|
|
||||||
* The latest release tag is .
|
|
||||||
|
|
||||||
1. Install dependencies: `npm install`
|
|
||||||
|
|
||||||
1. Run `npm run setup` to check your setup and set the bot's initial state. You only need to run this once ever. This command will guide you precisely through the following steps:
|
|
||||||
|
|
||||||
* First, you'll be asked for information like your homeserver URL.
|
|
||||||
|
|
||||||
* Then you'll be prompted to set up a reverse proxy pointing from your domain to the bridge's web server. Sample configurations can be found at the end of this guide. It will check that the reverse proxy works before you continue.
|
|
||||||
|
|
||||||
* Then you'll need to provide information about your Discord bot, and you'll be asked to change some of its settings.
|
|
||||||
|
|
||||||
* Finally, a registration.yaml file will be generated, which you need to give to your homeserver. You'll be told how to do this. It will check that it's done properly.
|
|
||||||
|
|
||||||
1. Start the bridge: `npm run start`
|
|
||||||
|
|
||||||
## Update
|
|
||||||
|
|
||||||
New versions are announced in [#updates](https://matrix.to/#/#ooye-updates:cadence.moe) and listed on [releases](https://gitdab.com/cadence/out-of-your-element/releases). Here's how to update:
|
|
||||||
|
|
||||||
1. Fetch the repo and checkout the latest release tag.
|
|
||||||
|
|
||||||
1. Install dependencies: `npm install`
|
|
||||||
|
|
||||||
1. Restart the bridge: Stop the currently running process, and then start the new one with `npm run start`
|
|
||||||
|
|
||||||
# Get Started
|
|
||||||
|
|
||||||
Visit the website on the domain name you set up, and click the button to add the bot to your Discord server.
|
|
||||||
|
|
||||||
* If you click the Easy Mode button, it will automatically create a Matrix room corresponding to each Discord channel. This happens next time a message is sent on Discord (so that your Matrix-side isn't immediately cluttered with lots of inactive rooms).
|
|
||||||
|
|
||||||
* If you click the Self Service button, it won't create anything for you. You'll have to provide your own Matrix space and rooms. After you click, you'll be prompted through the process. Use this if you're migrating from another bridge!
|
|
||||||
|
|
||||||
After that, to get into the rooms on your Matrix account, use the invite form on the website, or the `/invite [your mxid here]` command on Discord.
|
|
||||||
|
|
||||||
I hope you enjoy Out Of Your Element!
|
|
||||||
|
|
||||||
----
|
|
||||||
<br><br><br><br><br>
|
|
||||||
|
|
||||||
# Appendix
|
|
||||||
|
|
||||||
## Example reverse proxy for nginx, dedicated domain name
|
|
||||||
|
|
||||||
Replace `bridge.cadence.moe` with the hostname you're using.
|
|
||||||
|
|
||||||
```nix
|
|
||||||
server {
|
|
||||||
listen 80;
|
|
||||||
listen [::]:80;
|
|
||||||
server_name bridge.cadence.moe;
|
|
||||||
|
|
||||||
return 301 https://bridge.cadence.moe$request_uri;
|
|
||||||
}
|
|
||||||
|
|
||||||
server {
|
|
||||||
listen 443 ssl http2;
|
|
||||||
listen [::]:443 ssl http2;
|
|
||||||
server_name bridge.cadence.moe;
|
|
||||||
|
|
||||||
# ssl parameters here...
|
|
||||||
client_max_body_size 5M;
|
|
||||||
|
|
||||||
location / {
|
|
||||||
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
|
|
||||||
proxy_pass http://127.0.0.1:6693;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Example reverse proxy for nginx, sharing a domain name
|
|
||||||
|
|
||||||
Same as above, but change the following:
|
|
||||||
|
|
||||||
- `location / {` -> `location /ooye/ {` (any sub-path you want; you MUST use a trailing slash or it won't work)
|
|
||||||
- `proxy_pass http://127.0.0.1:6693;` -> `proxy_pass http://127.0.0.1:6693/;` (you MUST use a trailing slash on this too or it won't work)
|
|
||||||
|
|
||||||
## Example reverse proxy for Caddy, dedicated domain name
|
|
||||||
|
|
||||||
```nix
|
|
||||||
bridge.cadence.moe {
|
|
||||||
log {
|
|
||||||
output file /var/log/caddy/access.log
|
|
||||||
format console
|
|
||||||
}
|
|
||||||
encode gzip
|
|
||||||
reverse_proxy 127.0.0.1:6693
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Example reverse proxy for traefik
|
|
||||||
|
|
||||||
Note: Out Of Your Element has no official Docker support. This guide is for using traefik when OOYE is ***not*** in a container.
|
|
||||||
|
|
||||||
See [third-party/reverse-proxy-traefik.md](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/third-party/reverse-proxy-traefik.md)
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 3.6 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 6.4 KiB |
|
|
@ -1,80 +0,0 @@
|
||||||
# Room upgrades
|
|
||||||
|
|
||||||
"Upgrading" a room is supposed to create a new room and then tries to set it up exactly like the old one. So it copies name, topic, power levels, space membership, etc. The old room is marked as old with an `m.room.tombstone` event, its power levels are adjusted to make it harder to send messages, and a hyperlink to the new room is added.
|
|
||||||
|
|
||||||
## What happens?
|
|
||||||
|
|
||||||
A room upgrade is triggered by a POST request to `/_matrix/client/v3/rooms/{roomId}/upgrade`. The upgrade process is done by the server, and involves multiple events across multiple rooms. Since this is server-specific, what will _actually_ happen depends on the server's implementation, but the spec says it does this:
|
|
||||||
|
|
||||||
1. Checks that the user has permission to send `m.room.tombstone` events in the room.
|
|
||||||
2. Creates a replacement room with a `m.room.create` event containing a predecessor field, the applicable `room_version`, and a `type` field which is copied from the predecessor room. If no `type` is set on the previous room, no `type` is specified on the new room’s create event either.
|
|
||||||
3. Replicates transferable state events to the new room. The exact details for what is transferred is left as an implementation detail, however the recommended state events to transfer are:
|
|
||||||
* `m.room.server_acl`
|
|
||||||
* `m.room.encryption`
|
|
||||||
* `m.room.name`
|
|
||||||
* `m.room.avatar`
|
|
||||||
* `m.room.topic`
|
|
||||||
* `m.room.guest_access`
|
|
||||||
* `m.room.history_visibility`
|
|
||||||
* `m.room.join_rules`
|
|
||||||
* `m.room.power_levels`
|
|
||||||
|
|
||||||
(Membership can't be transferred by the server.)
|
|
||||||
|
|
||||||
4. Moves any local aliases to the new room.
|
|
||||||
5. Sends a `m.room.tombstone` event to the old room to indicate that it is not intended to be used any further.
|
|
||||||
6. If possible, the power levels in the old room should also be modified to prevent sending of events and inviting new users. For example, setting `events_default` and `invite` to the greater of `50` and `users_default + 1`.
|
|
||||||
|
|
||||||
### Synapse additionally:
|
|
||||||
|
|
||||||
1. Copies its `m.space.child` events (if it was a space).
|
|
||||||
* This is good for OOYE, because it automatically tries to join new rooms when they're added to a registered space.
|
|
||||||
2. Copies bans.
|
|
||||||
3. Un/publishes to the public room directory as applicable.
|
|
||||||
4. Copies user tags and push rules.
|
|
||||||
|
|
||||||
Conduwuit does not do those!
|
|
||||||
|
|
||||||
### Element additionally:
|
|
||||||
|
|
||||||
1. May invite all users from the old room to the new room, depending on if the checkbox is checked in the dialog.
|
|
||||||
2. Update parent spaces to remove the old room and add the new room.
|
|
||||||
|
|
||||||
Cinny does not do those! The new room is totally detached! The hyperlink from the old room (and the moved alias by server) is the only way to find it!
|
|
||||||
|
|
||||||
* This is probably still okay for OOYE? Since the join rules are preserved, and if they were `restricted`, OOYE is able to join via the tombstone hyperlink. Then, after it joins, it's already PL 100 since the power levels are preserved. It's very bad if the join rules were `invite`, but OOYE never sets this join rule - it's either `restricted` or `public`.
|
|
||||||
|
|
||||||
### Other clients
|
|
||||||
|
|
||||||
Nheko doesn't support room upgrades at all. Cinyy, NeoChat and FluffyChat just call the API and don't do anything. FluffyChat invites all joined/invited users to the new room if the join rule is restricted.
|
|
||||||
|
|
||||||
### Notable things that don't happen at all:
|
|
||||||
|
|
||||||
* Add `m.space.parent` pointing to the space it was in (if it was a room in a space).
|
|
||||||
|
|
||||||
## What should OOYE do?
|
|
||||||
|
|
||||||
### Ideal case (Element, Synapse)
|
|
||||||
|
|
||||||
The new room is added to the space and OOYE autojoins it. It already has the correct power levels and join rules.
|
|
||||||
|
|
||||||
OOYE still needs to do this:
|
|
||||||
|
|
||||||
1. Un/set `m.room.parent` in the rooms.
|
|
||||||
2. Update `channel_room` and `historical_channel_room` tables.
|
|
||||||
|
|
||||||
### Not ideal case (everyone else)
|
|
||||||
|
|
||||||
OOYE should:
|
|
||||||
|
|
||||||
1. Join the room by following the hyperlink from the tombstone, if able
|
|
||||||
* If not able, somebody messed with the join rules. Send a PM to the user who upgraded - the new room's creator - asking for an invite.
|
|
||||||
2. Wait for join.
|
|
||||||
3. Un/set `m.space.child` events on the space.
|
|
||||||
4. Un/set `m.room.parent` in the rooms.
|
|
||||||
5. Update `channel_room` and `historical_channel_room` tables.
|
|
||||||
6. Un/publish to the room directory.
|
|
||||||
|
|
||||||
### It's actually fine to do all the steps always
|
|
||||||
|
|
||||||
Even by blindly following the entire list, each step is a no-op or atomic, so it doesn't matter if Element is also trying to do them.
|
|
||||||
|
|
@ -63,15 +63,8 @@ Pressing buttons on web or using the /invite command on a guild will insert a ro
|
||||||
|
|
||||||
So here's all the technical changes needed to support self-service in v3:
|
So here's all the technical changes needed to support self-service in v3:
|
||||||
|
|
||||||
- New guild_active table showing whether, and how, a guild is bridged.
|
- New guild_active table showing whether, and how, a guild is bridged
|
||||||
- When /invite command is used, INSERT OR IGNORE INTO state 1 and ensureRoom + ensureSpace.
|
- When /invite command is used, INSERT OR IGNORE INTO state 1 and ensureRoom + ensureSpace.
|
||||||
- When bot is added through "easy mode" web button, REPLACE INTO state 1 and ensureSpace.
|
- When bot is added through "easy mode" web button, REPLACE INTO state 1 and ensureSpace.
|
||||||
- When bot is added through "self-service" web button, REPLACE INTO state 0.
|
- When bot is added through "self-service" web button, REPLACE INTO state 2.
|
||||||
- Event dispatcher will only ensureRoom if the guild_active state is 1.
|
- Event dispatcher will only ensureRoom if the guild_active state is 1
|
||||||
- createRoom will only create other dependencies if the guild is autocreate.
|
|
||||||
|
|
||||||
## Enough with your theory. How do rooms actually get bridged now?
|
|
||||||
|
|
||||||
After clicking the easy mode button on web and adding the bot to a server, it will create new Matrix rooms on-demand when any invite features are used (web or command) OR just when any message is sent on Discord.
|
|
||||||
|
|
||||||
Alternatively, pressing the self-service mode button and adding the bot to a server will prompt the web user to link it with a space. After doing so, they'll be on the standard guild management page where they can invite to the space and manually link rooms. Nothing will be autocreated.
|
|
||||||
|
|
|
||||||
113
docs/third-party/reverse-proxy-traefik.md
vendored
113
docs/third-party/reverse-proxy-traefik.md
vendored
|
|
@ -1,113 +0,0 @@
|
||||||
> This guide was written by @bgtlover:stealthy.club, a community contributor. The author of Out Of Your Element hopes it will be useful, but cannot say whether the information is accurate or complete.
|
|
||||||
|
|
||||||
## Example reverse proxy configuration with traefik
|
|
||||||
|
|
||||||
Note: This guide describes setting up the reverse proxy configuration when OOYE is ***not*** in a Docker container.
|
|
||||||
|
|
||||||
Because traefik is generally used in Docker, this guide assumes the user already has it configured properly. However, given that Docker is very complex and the smallest mistakes can cascade in catastrophic, not immediately observable, and unpredictable ways, a fairly complete setup will be reproduced. Therefore, system administrators are advised to diff this sample setup against theirs rather than copy it wholesale.
|
|
||||||
|
|
||||||
### Note on variable substitution
|
|
||||||
|
|
||||||
Variables will be denoted as `{{var}}`. This syntax has been chosen because that's also how YAML substitution works. The values that fit each variable will be explained after the code block containing the placeholder.
|
|
||||||
|
|
||||||
### Base compose configuration for traefik
|
|
||||||
|
|
||||||
This file defines the traefik service stack. It's responsible for mounting volumes correctly, declaring ports that should be opened on the host side, and the external traefik network (created manually).
|
|
||||||
|
|
||||||
In compose.yml, put the following:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
services:
|
|
||||||
traefik:
|
|
||||||
image: "traefik:latest"
|
|
||||||
restart: always
|
|
||||||
command:
|
|
||||||
- "--configFile=/etc/traefik/static_config.yml"
|
|
||||||
ports:
|
|
||||||
- "80:80" #http
|
|
||||||
- "443:443" #https
|
|
||||||
networks:
|
|
||||||
- traefik
|
|
||||||
volumes:
|
|
||||||
- ./letsencrypt:/letsencrypt
|
|
||||||
- /etc/localtime:/etc/localtime:ro
|
|
||||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
|
||||||
- ./static_config.yml:/etc/traefik/static_config.yml
|
|
||||||
- ./config:/etc/traefik/config
|
|
||||||
networks:
|
|
||||||
traefik:
|
|
||||||
external: true
|
|
||||||
```
|
|
||||||
|
|
||||||
### Static traefik configuration
|
|
||||||
|
|
||||||
The static traefik configuration is used to define base traefik behavior, for example entry points, access and runtime logs, a file or directory for per-service configuration, etc.
|
|
||||||
|
|
||||||
In static_config.yml, put the following:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
api:
|
|
||||||
dashboard: true
|
|
||||||
|
|
||||||
providers:
|
|
||||||
docker:
|
|
||||||
endpoint: "unix:///var/run/docker.sock"
|
|
||||||
exposedByDefault: false
|
|
||||||
network: "traefik"
|
|
||||||
file:
|
|
||||||
directory: /etc/traefik/config/
|
|
||||||
watch: true
|
|
||||||
|
|
||||||
entryPoints:
|
|
||||||
web-secure:
|
|
||||||
address: ":443"
|
|
||||||
asDefault: true
|
|
||||||
http3: {}
|
|
||||||
http:
|
|
||||||
tls:
|
|
||||||
certResolver: default
|
|
||||||
web:
|
|
||||||
address: ":80"
|
|
||||||
http:
|
|
||||||
redirections:
|
|
||||||
entryPoint:
|
|
||||||
to: web-secure
|
|
||||||
|
|
||||||
certificatesResolvers:
|
|
||||||
default:
|
|
||||||
acme:
|
|
||||||
email: {{email}}
|
|
||||||
storage: "/letsencrypt/acme.json"
|
|
||||||
tlsChallenge: {}
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
Replace `{{email}}` with a valid email address.
|
|
||||||
|
|
||||||
### Out of your element traefik dynamic configuration
|
|
||||||
|
|
||||||
Traefik's dynamic configuration files configure proxy behaviors on a per-application level.
|
|
||||||
|
|
||||||
In config/out-of-your-element.yml, put the following:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
http:
|
|
||||||
routers:
|
|
||||||
out-of-your-element:
|
|
||||||
rule: Host(`bridge.stealthy.club`)
|
|
||||||
service: out-of-your-element-service
|
|
||||||
services:
|
|
||||||
out-of-your-element-service:
|
|
||||||
loadBalancer:
|
|
||||||
servers:
|
|
||||||
- url: "http://{{ip}}:{{port}}"
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
The `{{port}}` is 6693 unless you changed it during Out Of Your Element's first time setup.
|
|
||||||
|
|
||||||
Replace `{{ip}}` with the ***external*** IP of your server.
|
|
||||||
|
|
||||||
Make sure the port is allowed through your firewall if applicable.
|
|
||||||
|
|
||||||
For context, the external IP is required because of Docker networking. Because Docker modifies the host-side iptables firewall and creates virtual interfaces for its networks, and because the networking inside containers is configured such that localhost points to the IP of the container instead of the actual host, placing localhost in the url field above would make the traefik container establish an HTTP connection to itself, which would cause a bad gateway error.
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
# Why does the bridge have a website?
|
|
||||||
|
|
||||||
## It's essential for making images work
|
|
||||||
|
|
||||||
Matrix has a feature called [Authenticated Media](https://matrix.org/blog/2024/06/26/sunsetting-unauthenticated-media/), where uploaded media (like user avatars and uploaded files) is restricted to Matrix users only. This means Discord users wouldn't be able to see important parts of the conversation.
|
|
||||||
|
|
||||||
To keep things working for Discord users, OOYE's web server can act as a proxy files that were uploaded on Matrix-side. This will automatically take effect when needed, so Discord users shouldn't notice any issues.
|
|
||||||
|
|
||||||
## Why now?
|
|
||||||
|
|
||||||
I knew a web interface had a lot of potential, but I was reluctant to add one because it would make the initial setup more complicated. However, when authenticated media forced my hand, I saw an opportunity to introduce new useful features. Hopefully you'll agree that it's worth it!
|
|
||||||
|
|
||||||
# What else does it do?
|
|
||||||
|
|
||||||
## Makes it easy to invite the bot
|
|
||||||
|
|
||||||
The home page of the website has buttons to add the bridge bot to a Discord server. If you are primarly a Matrix user and you want somebody else (who may be less technical) to add the bot to their own Discord server, this should make it a lot more intuitive for them.
|
|
||||||
|
|
||||||
## Makes it easy to invite yourself or others
|
|
||||||
|
|
||||||
After your hypothetical less-technical friend adds the bot to their Discord server, you need to generate an invite for your Matrix account on Matrix-side. Without the website, you might need to guide them through running a /invite command with your user ID. With the website, they don't have to do anything extra. You can use your phone to scan the QR code on their screen, which lets you invite your user ID in your own time.
|
|
||||||
|
|
||||||
You can also set the person's permissions when you invite them, so you can easily bootstrap the Matrix side with your trusted ones as moderators.
|
|
||||||
|
|
||||||
## To link channels and rooms
|
|
||||||
|
|
||||||
Without a website, to link Discord channels to existing Matrix rooms, you'd need to run a /link command with the internal IDs of each room. This is tedious and error-prone, especially if you want to set up a lot of channels. With the web interface, you can see a list of all the available rooms and click them to link them together.
|
|
||||||
|
|
||||||
## To change settings
|
|
||||||
|
|
||||||
Important settings, like whether the Matrix rooms should be private or publicly accessible, can be configured by clicking buttons rather than memorising commands. Changes take effect immediately.
|
|
||||||
|
|
||||||
# Permissions
|
|
||||||
|
|
||||||
## Bot invites
|
|
||||||
|
|
||||||
Anybody who can access the home page can use the buttons to add your bot - but even without the website, they can already do this by manually constructing a URL. If you want to make it so _only you_ can add your bot to servers, you need to edit [your Discord application](https://discord.com/developers/applications), go to the Bot section, and turn off the switch that says Public Bot.
|
|
||||||
|
|
||||||
## Server settings
|
|
||||||
|
|
||||||
If you have either the Administrator or Manage Server permissions in a Discord server, you can use the website to manage that server, including linking channels and changing settings.
|
|
||||||
|
|
||||||
# Initial setup
|
|
||||||
|
|
||||||
The website is built in to OOYE and is always running as part of the bridge. For authenticated media proxy to work, you'll need to make the web server accessible on the public internet over HTTPS, presumably using a reverse proxy.
|
|
||||||
|
|
||||||
When you use `npm run setup` as part of OOYE's initial setup, it will guide you through this process, and it will do a thorough self-test to make sure it's configured correctly. If you get stuck or want a configuration template, check the notes below.
|
|
||||||
|
|
||||||
## Reverse proxy
|
|
||||||
|
|
||||||
When OOYE is running, the web server runs on port 6693. (To use a different port or a UNIX socket, edit registration.yaml's `socket` setting and restart.)
|
|
||||||
|
|
||||||
It doesn't have to have its own dedicated domain name, you can also use a sub-path on an existing domain, like the domain of your Matrix homeserver. You are likely already using a reverse proxy to run your homeserver, so this should just be a configuration change.
|
|
||||||
|
|
||||||
[See here for sample configurations!](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/get-started.md#appendix)
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "es2024",
|
|
||||||
"module": "nodenext",
|
|
||||||
"lib": ["ESNext"],
|
|
||||||
"strict": true,
|
|
||||||
"noImplicitAny": false,
|
|
||||||
"useUnknownInCatchVariables": false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
1667
package-lock.json
generated
1667
package-lock.json
generated
File diff suppressed because it is too large
Load diff
57
package.json
57
package.json
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "out-of-your-element",
|
"name": "out-of-your-element",
|
||||||
"version": "3.4.0",
|
"version": "1.1.1",
|
||||||
"description": "A bridge between Matrix and Discord",
|
"description": "A bridge between Matrix and Discord",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"repository": {
|
"repository": {
|
||||||
|
|
@ -12,61 +12,58 @@
|
||||||
"discord",
|
"discord",
|
||||||
"bridge"
|
"bridge"
|
||||||
],
|
],
|
||||||
"author": "Cadence",
|
"author": "Cadence, PapiOphidian",
|
||||||
"license": "AGPL-3.0-or-later",
|
"license": "AGPL-3.0-or-later",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=22"
|
"node": ">=20"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@chriscdn/promise-semaphore": "^3.0.1",
|
"@chriscdn/promise-semaphore": "^2.0.1",
|
||||||
"@cloudrac3r/discord-markdown": "^2.6.10",
|
"@cloudrac3r/discord-markdown": "^2.6.3",
|
||||||
"@cloudrac3r/giframe": "^0.4.3",
|
"@cloudrac3r/giframe": "^0.4.3",
|
||||||
"@cloudrac3r/html-template-tag": "^5.0.1",
|
"@cloudrac3r/html-template-tag": "^5.0.1",
|
||||||
"@cloudrac3r/in-your-element": "^1.1.1",
|
"@cloudrac3r/in-your-element": "^1.0.0",
|
||||||
"@cloudrac3r/mixin-deep": "^3.0.1",
|
"@cloudrac3r/mixin-deep": "^3.0.0",
|
||||||
"@cloudrac3r/pngjs": "^7.0.3",
|
"@cloudrac3r/pngjs": "^7.0.3",
|
||||||
"@cloudrac3r/pug": "^4.0.4",
|
"@cloudrac3r/pug": "^4.0.4",
|
||||||
"@cloudrac3r/turndown": "^7.1.4",
|
"@cloudrac3r/turndown": "^7.1.4",
|
||||||
"@stackoverflow/stacks": "^2.5.4",
|
"@stackoverflow/stacks": "^2.5.7",
|
||||||
"@stackoverflow/stacks-icons": "^6.0.2",
|
"@stackoverflow/stacks-icons": "^6.0.2",
|
||||||
"ansi-colors": "^4.1.3",
|
"ansi-colors": "^4.1.3",
|
||||||
"better-sqlite3": "^12.2.0",
|
"better-sqlite3": "^11.1.2",
|
||||||
"chunk-text": "^2.0.1",
|
"chunk-text": "^2.0.1",
|
||||||
"cloudstorm": "^0.15.2",
|
"cloudstorm": "^0.10.10",
|
||||||
"discord-api-types": "^0.38.38",
|
|
||||||
"domino": "^2.1.6",
|
"domino": "^2.1.6",
|
||||||
"enquirer": "^2.4.1",
|
"enquirer": "^2.4.1",
|
||||||
"entities": "^5.0.0",
|
"entities": "^5.0.0",
|
||||||
"get-relative-path": "^1.0.2",
|
"get-stream": "^6.0.1",
|
||||||
"h3": "^1.15.1",
|
"h3": "^1.12.0",
|
||||||
"heatsync": "^2.7.2",
|
"heatsync": "^2.5.3",
|
||||||
"htmx.org": "^2.0.4",
|
"lru-cache": "^10.4.3",
|
||||||
"lru-cache": "^11.0.2",
|
"minimist": "^1.2.8",
|
||||||
"mime-types": "^2.1.35",
|
"node-fetch": "^2.6.7",
|
||||||
"prettier-bytes": "^1.0.4",
|
"prettier-bytes": "^1.0.4",
|
||||||
"sharp": "^0.34.5",
|
"sharp": "^0.33.4",
|
||||||
"snowtransfer": "^0.17.1",
|
"snowtransfer": "^0.10.5",
|
||||||
"stream-mime-type": "^1.0.2",
|
"stream-mime-type": "^1.0.2",
|
||||||
"try-to-catch": "^3.0.1",
|
"try-to-catch": "^3.0.1",
|
||||||
"uqr": "^0.1.2",
|
|
||||||
"xxhash-wasm": "^1.0.2",
|
"xxhash-wasm": "^1.0.2",
|
||||||
"zod": "^4.0.17"
|
"zod": "^3.23.8"
|
||||||
},
|
|
||||||
"overrides": {
|
|
||||||
"glob@<11.1": "^12"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@cloudrac3r/tap-dot": "^2.0.3",
|
"@cloudrac3r/tap-dot": "^2.0.3",
|
||||||
"@types/node": "^22.17.1",
|
"@types/node": "^18.16.0",
|
||||||
|
"@types/node-fetch": "^2.6.3",
|
||||||
"c8": "^10.1.2",
|
"c8": "^10.1.2",
|
||||||
"cross-env": "^7.0.3",
|
"cross-env": "^7.0.3",
|
||||||
"supertape": "^12.0.12"
|
"discord-api-types": "^0.37.60",
|
||||||
|
"supertape": "^10.4.0"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node --enable-source-maps start.js",
|
"start": "node start.js",
|
||||||
"setup": "node --enable-source-maps scripts/setup.js",
|
|
||||||
"addbot": "node addbot.js",
|
"addbot": "node addbot.js",
|
||||||
"test": "cross-env FORCE_COLOR=true supertape --no-check-assertions-count --format tap --no-worker test/test.js | tap-dot",
|
"test": "cross-env FORCE_COLOR=true supertape --no-check-assertions-count --format tap test/test.js | tap-dot",
|
||||||
"cover": "c8 -o test/coverage --skip-full -x db/migrations -x src/m2d/event-dispatcher.js -x src/matrix/file.js -x src/matrix/api.js -x src/d2m/converters/rlottie-wasm.js -r html -r text supertape --no-check-assertions-count --format fail --no-worker test/test.js -- --slow"
|
"test-slow": "cross-env FORCE_COLOR=true supertape --no-check-assertions-count --format tap --no-worker test/test.js -- --slow | tap-dot",
|
||||||
|
"cover": "c8 -o test/coverage --skip-full -x db/migrations -x matrix/file.js -x matrix/api.js -x matrix/mreq.js -x d2m/converters/rlottie-wasm.js -r html -r text supertape --no-check-assertions-count --format fail --no-worker test/test.js -- --slow"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
184
readme.md
184
readme.md
|
|
@ -6,13 +6,15 @@ Modern Matrix-to-Discord appservice bridge, created by [@cadence:cadence.moe](ht
|
||||||
|
|
||||||
[](https://gitdab.com/cadence/out-of-your-element/releases) [](https://matrix.to/#/#out-of-your-element:cadence.moe)
|
[](https://gitdab.com/cadence/out-of-your-element/releases) [](https://matrix.to/#/#out-of-your-element:cadence.moe)
|
||||||
|
|
||||||

|
## Docs
|
||||||
|
|
||||||
|
This readme has the most important info. The rest is [in the docs folder.](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs)
|
||||||
|
|
||||||
## Why a new bridge?
|
## Why a new bridge?
|
||||||
|
|
||||||
* Modern: Supports new Discord features like replies, threads and stickers, and new Matrix features like edits, spaces and space membership.
|
* Modern: Supports new Discord features like replies, threads and stickers, and new Matrix features like edits, spaces and space membership.
|
||||||
* Efficient: Special attention has been given to memory usage, database indexes, disk footprint, runtime algorithms, and queries to the homeserver. [Efficiency details.](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/developer-orientation.md)
|
* Efficient: Special attention has been given to memory usage, database indexes, disk footprint, runtime algorithms, and queries to the homeserver.
|
||||||
* Reliable: Any errors on either side are notified on Matrix and can be retried. Messages sent during bridge downtime will still be bridged after it comes back up.
|
* Reliable: Any errors on either side are notified on Matrix and can be retried.
|
||||||
* Tested: A test suite and code coverage make sure all the logic and special cases work.
|
* Tested: A test suite and code coverage make sure all the logic and special cases work.
|
||||||
* Simple development: No build step (it's JavaScript, not TypeScript), minimal/lightweight dependencies, and abstraction only where necessary so that less background knowledge is required. No need to learn about Intents or library functions.
|
* Simple development: No build step (it's JavaScript, not TypeScript), minimal/lightweight dependencies, and abstraction only where necessary so that less background knowledge is required. No need to learn about Intents or library functions.
|
||||||
* No locking algorithm: Other bridges use a locking algorithm which is a source of frequent bugs. This bridge avoids the need for one.
|
* No locking algorithm: Other bridges use a locking algorithm which is a source of frequent bugs. This bridge avoids the need for one.
|
||||||
|
|
@ -20,17 +22,27 @@ Modern Matrix-to-Discord appservice bridge, created by [@cadence:cadence.moe](ht
|
||||||
|
|
||||||
## What works?
|
## What works?
|
||||||
|
|
||||||
Most features you'd expect in both directions: messages, edits, deletions, formatting (including spoilers), reactions, custom emojis, custom emoji reactions, mentions, channel mentions, replies, threads, stickers (all formats: PNG, APNG, GIF, Lottie), attachments, spoiler attachments (compatible with most clients), embeds, URL previews, presence, discord.com hyperlinks, and more.
|
Most features you'd expect in both directions, plus a little extra spice:
|
||||||
|
|
||||||
Metadata is also synced: people's names, avatars, usernames; channel names, icons, topics; spaces containing rooms; custom emoji lists. Syncing Matrix rooms, room icons, and topics is optional: you can keep them different from the Discord ones if you prefer.
|
* Messages
|
||||||
|
* Edits
|
||||||
I've also added some interesting features that I haven't seen in any other bridge:
|
* Deletions
|
||||||
|
* Text formatting, including spoilers
|
||||||
* Members using the PluralKit bot each get their own persistent accounts
|
* Reactions
|
||||||
* Replies from PluralKit members are restyled into native Matrix replies
|
* Mentions
|
||||||
|
* Replies
|
||||||
|
* Threads
|
||||||
|
* Stickers (all formats: PNG, APNG, GIF, and Lottie)
|
||||||
|
* Attachments
|
||||||
|
* Spoiler attachments
|
||||||
|
* Embeds
|
||||||
|
* Guild-Space details syncing
|
||||||
|
* Channel-Room details syncing
|
||||||
|
* Custom emoji list syncing
|
||||||
|
* Custom emojis in messages
|
||||||
|
* Custom room names/avatars can be applied on Matrix-side
|
||||||
|
* Larger files from Discord are linked instead of reuploaded to Matrix (links don't expire)
|
||||||
* Simulated user accounts are named @the_persons_username rather than @112233445566778899
|
* Simulated user accounts are named @the_persons_username rather than @112233445566778899
|
||||||
* Matrix custom emojis from private rooms are still visible on Discord as a sprite sheet
|
|
||||||
* To save space, larger files from Discord are linked instead of reuploaded to Matrix (links don't expire)
|
|
||||||
|
|
||||||
For more information about features, [see the user guide.](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/user-guide.md)
|
For more information about features, [see the user guide.](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/user-guide.md)
|
||||||
|
|
||||||
|
|
@ -38,8 +50,150 @@ For more information about features, [see the user guide.](https://gitdab.com/ca
|
||||||
|
|
||||||
* This bridge is not designed for puppetting.
|
* This bridge is not designed for puppetting.
|
||||||
* Direct Messaging is not supported until I figure out a good way of doing it.
|
* Direct Messaging is not supported until I figure out a good way of doing it.
|
||||||
* Encrypted messages are not supported. Decryption is often unreliable on Matrix, and your messages end up in plaintext on Discord anyway, so there's not much advantage.
|
|
||||||
|
|
||||||
## Get started!
|
## Efficiency details
|
||||||
|
|
||||||
[Read the installation instructions →](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/get-started.md)
|
Using WeatherStack as a thin layer between the bridge application and the Discord API lets us control exactly what data is cached in memory. Only necessary information is cached. For example, member data, user data, message content, and past edits are never stored in memory. This keeps the memory usage low and also prevents it ballooning in size over the bridge's runtime.
|
||||||
|
|
||||||
|
The bridge uses a small SQLite database to store relationships like which Discord messages correspond to which Matrix messages. This is so the bridge knows what to edit when some message is edited on Discord. Using `without rowid` on the database tables stores the index and the data in the same B-tree. Since Matrix and Discord's internal IDs are quite long, this vastly reduces storage space because those IDs do not have to be stored twice separately. Some event IDs and URLs are actually stored as xxhash integers to reduce storage requirements even more. On my personal instance of OOYE, every 300,000 messages (representing a year of conversations) requires 47.3 MB of storage space in the SQLite database.
|
||||||
|
|
||||||
|
Only necessary data and columns are queried from the database. We only contact the homeserver API if the database doesn't contain what we need.
|
||||||
|
|
||||||
|
File uploads (like avatars from bridged members) are checked locally and deduplicated. Only brand new files are uploaded to the homeserver. This saves loads of space in the homeserver's media repo, especially for Synapse.
|
||||||
|
|
||||||
|
Switching to [WAL mode](https://www.sqlite.org/wal.html) could improve your database access speed even more. Run `node scripts/wal.js` if you want to switch to WAL mode. This will also enable `synchronous = NORMAL`.
|
||||||
|
|
||||||
|
# Setup
|
||||||
|
|
||||||
|
If you get stuck, you're welcome to message [#out-of-your-element:cadence.moe](https://matrix.to/#/#out-of-your-element:cadence.moe) or [@cadence:cadence.moe](https://matrix.to/#/@cadence:cadence.moe) to ask for help setting up OOYE!
|
||||||
|
|
||||||
|
You'll need:
|
||||||
|
|
||||||
|
* Administrative access to a homeserver
|
||||||
|
* Discord bot
|
||||||
|
|
||||||
|
Follow these steps:
|
||||||
|
|
||||||
|
1. [Get Node.js version 20 or later](https://nodejs.org/en/download/prebuilt-installer)
|
||||||
|
|
||||||
|
1. Clone this repo and checkout a specific tag. (Development happens on main. Stable versions are tagged.)
|
||||||
|
* The latest release tag is .
|
||||||
|
|
||||||
|
1. Install dependencies: `npm install`
|
||||||
|
|
||||||
|
1. Run `node scripts/seed.js` to check your setup and set the bot's initial state. It will prompt you for information. You only need to run this once ever.
|
||||||
|
|
||||||
|
1. Start the bridge: `npm start`
|
||||||
|
|
||||||
|
1. Add the bot to a server - use any *one* of the following commands for an invite link:
|
||||||
|
* (in the REPL) `addbot`
|
||||||
|
* $ `node addbot.js`
|
||||||
|
* $ `npm run addbot`
|
||||||
|
* $ `./addbot.sh`
|
||||||
|
|
||||||
|
Now any message on Discord will create the corresponding rooms on Matrix-side. After the rooms have been created, Matrix and Discord users can chat back and forth.
|
||||||
|
|
||||||
|
To get into the rooms on your Matrix account, use the `/invite [your mxid here]` command on Discord.
|
||||||
|
|
||||||
|
# Development setup
|
||||||
|
|
||||||
|
* Install development dependencies with `npm install --save-dev` so you can run the tests.
|
||||||
|
* Most files you change, such as actions, converters, and web, will automatically be reloaded.
|
||||||
|
* If developing on a different computer to the one running the homeserver, use SSH port forwarding so that Synapse can connect on its `localhost:6693` to reach the running bridge on your computer. Example: `ssh -T -v -R 6693:localhost:6693 me@matrix.cadence.moe`
|
||||||
|
* I recommend developing in Visual Studio Code so that the JSDoc x TypeScript annotation comments work. I don't know which other editors or language servers support annotations and type inference.
|
||||||
|
|
||||||
|
## Repository structure
|
||||||
|
|
||||||
|
.
|
||||||
|
* Runtime configuration, like tokens and user info:
|
||||||
|
├── registration.yaml
|
||||||
|
* You are here! :)
|
||||||
|
├── readme.md
|
||||||
|
* The bridge's SQLite database is stored here:
|
||||||
|
├── ooye.db*
|
||||||
|
* Source code
|
||||||
|
└── src
|
||||||
|
* Database schema:
|
||||||
|
├── db
|
||||||
|
│ ├── orm.js, orm-defs.d.ts
|
||||||
|
│ * Migrations change the database schema when you update to a newer version of OOYE:
|
||||||
|
│ ├── migrate.js
|
||||||
|
│ └── migrations
|
||||||
|
│ └── *.sql, *.js
|
||||||
|
* Discord-to-Matrix bridging:
|
||||||
|
├── d2m
|
||||||
|
│ * Execute actions through the whole flow, like sending a Discord message to Matrix:
|
||||||
|
│ ├── actions
|
||||||
|
│ │ └── *.js
|
||||||
|
│ * Convert data from one form to another without depending on bridge state. Called by actions:
|
||||||
|
│ ├── converters
|
||||||
|
│ │ └── *.js
|
||||||
|
│ * Making Discord work:
|
||||||
|
│ ├── discord-*.js
|
||||||
|
│ * Listening to events from Discord and dispatching them to the correct `action`:
|
||||||
|
│ └── event-dispatcher.js
|
||||||
|
* Discord bot commands and menus:
|
||||||
|
├── discord
|
||||||
|
│ ├── interactions
|
||||||
|
│ │ └── *.js
|
||||||
|
│ └── discord-command-handler.js
|
||||||
|
* Matrix-to-Discord bridging:
|
||||||
|
├── m2d
|
||||||
|
│ * Execute actions through the whole flow, like sending a Matrix message to Discord:
|
||||||
|
│ ├── actions
|
||||||
|
│ │ └── *.js
|
||||||
|
│ * Convert data from one form to another without depending on bridge state. Called by actions:
|
||||||
|
│ ├── converters
|
||||||
|
│ │ └── *.js
|
||||||
|
│ * Listening to events from Matrix and dispatching them to the correct `action`:
|
||||||
|
│ └── event-dispatcher.js
|
||||||
|
* We aren't using the matrix-js-sdk, so here are all the functions for the Matrix C-S and Appservice APIs:
|
||||||
|
├── matrix
|
||||||
|
│ └── *.js
|
||||||
|
* Various files you can run once if you need them.
|
||||||
|
└── scripts
|
||||||
|
* First time running a new bridge? Run this file to plant a seed, which will flourish into state for the bridge:
|
||||||
|
├── seed.js
|
||||||
|
* Hopefully you won't need the rest of these. Code quality varies wildly.
|
||||||
|
└── *.js
|
||||||
|
|
||||||
|
## Dependency justification
|
||||||
|
|
||||||
|
Total transitive production dependencies: 147
|
||||||
|
|
||||||
|
### <font size="+2">🦕</font>
|
||||||
|
|
||||||
|
* (31) better-sqlite3: SQLite3 is the best database, and this is the best library for it.
|
||||||
|
* (27) @cloudrac3r/pug: Language for dynamic web pages. This is my fork. (I released code that hadn't made it to npm, and removed the heavy pug-filters feature.)
|
||||||
|
* (16) stream-mime-type@1: This seems like the best option. Version 1 is used because version 2 is ESM-only.
|
||||||
|
* (14) h3: Web server. OOYE needs this for the appservice listener, authmedia proxy, and more. 14 transitive dependencies is on the low end for a web server.
|
||||||
|
* (11) sharp: Image resizing and compositing. OOYE needs this for the emoji sprite sheets.
|
||||||
|
|
||||||
|
### <font size="-1">🪱</font>
|
||||||
|
|
||||||
|
* (0) @chriscdn/promise-semaphore: It does what I want.
|
||||||
|
* (1) @cloudrac3r/discord-markdown: This is my fork.
|
||||||
|
* (0) @cloudrac3r/giframe: This is my fork.
|
||||||
|
* (1) @cloudrac3r/html-template-tag: This is my fork.
|
||||||
|
* (0) @cloudrac3r/in-your-element: This is my Matrix Appservice API library. It depends on h3 and zod, which are already pulled in by OOYE.
|
||||||
|
* (0) @cloudrac3r/mixin-deep: This is my fork. (It fixes a bug in regular mixin-deep.)
|
||||||
|
* (0) @cloudrac3r/pngjs: Lottie stickers are converted to bitmaps with the vendored Rlottie WASM build, then the bitmaps are converted to PNG with pngjs.
|
||||||
|
* (0) @cloudrac3r/turndown: This HTML-to-Markdown converter looked the most suitable. I forked it to change the escaping logic to match the way Discord works.
|
||||||
|
* (3) @stackoverflow/stacks: Stack Overflow design language and icons.
|
||||||
|
* (0) ansi-colors: Helps with interactive prompting for the initial setup, and it's already pulled in by enquirer.
|
||||||
|
* (1) chunk-text: It does what I want.
|
||||||
|
* (0) cloudstorm: Discord gateway library with bring-your-own-caching that I trust.
|
||||||
|
* (0) domino: DOM implementation that's already pulled in by turndown.
|
||||||
|
* (1) enquirer: Interactive prompting for the initial setup rather than forcing users to edit YAML non-interactively.
|
||||||
|
* (0) entities: Looks fine. No dependencies.
|
||||||
|
* (0) get-stream: Only needed if content_length_workaround is true.
|
||||||
|
* (1) heatsync: Module hot-reloader that I trust.
|
||||||
|
* (1) js-yaml: Will be removed in the future after registration.yaml is converted to JSON.
|
||||||
|
* (0) lru-cache: For holding unused nonce in memory and letting them be overwritten later if never used.
|
||||||
|
* (0) minimist: It's already pulled in by better-sqlite3->prebuild-install.
|
||||||
|
* (3) node-fetch@2: I like it and it does what I want. Version 2 is used because version 3 is ESM-only.
|
||||||
|
* (0) prettier-bytes: It does what I want and has no dependencies.
|
||||||
|
* (2) snowtransfer: Discord API library with bring-your-own-caching that I trust.
|
||||||
|
* (0) try-to-catch: Not strictly necessary, but it's already pulled in by supertape, so I may as well.
|
||||||
|
* (0) xxhash-wasm: Used where cryptographically secure hashing is not required.
|
||||||
|
* (0) zod: Input validation for the web server. It's popular and easy to use.
|
||||||
|
|
|
||||||
25
registration.example.yaml
Normal file
25
registration.example.yaml
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
id: de8c56117637cb5d9f4ac216f612dc2adb1de4c09ae8d13553f28c33a28147c7
|
||||||
|
hs_token: [a unique 64 character hex string]
|
||||||
|
as_token: [a unique 64 character hex string]
|
||||||
|
url: http://localhost:6693
|
||||||
|
sender_localpart: _ooye_bot
|
||||||
|
protocols:
|
||||||
|
- discord
|
||||||
|
namespaces:
|
||||||
|
users:
|
||||||
|
- exclusive: true
|
||||||
|
regex: '@_ooye_.*'
|
||||||
|
aliases:
|
||||||
|
- exclusive: true
|
||||||
|
regex: '#_ooye_.*'
|
||||||
|
rate_limited: false
|
||||||
|
ooye:
|
||||||
|
namespace_prefix: _ooye_
|
||||||
|
max_file_size: 5000000
|
||||||
|
server_name: [the part after the colon in your matrix id, like cadence.moe]
|
||||||
|
server_origin: [the full protocol and domain of your actual matrix server's location, with no trailing slash, like https://matrix.cadence.moe]
|
||||||
|
content_length_workaround: false
|
||||||
|
include_user_id_in_mxid: false
|
||||||
|
invite:
|
||||||
|
# uncomment this to auto-invite the named user to newly created spaces and mark them as admin (PL 100) everywhere
|
||||||
|
# - '@cadence:cadence.moe'
|
||||||
|
|
@ -1,82 +0,0 @@
|
||||||
#!/usr/bin/env node
|
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
console.log("-=- This script is experimental. It WILL mess up the room history on Matrix. -=-")
|
|
||||||
console.log()
|
|
||||||
|
|
||||||
const {channel: channelID} = require("minimist")(process.argv.slice(2), {string: ["channel"]})
|
|
||||||
if (!channelID) {
|
|
||||||
console.error("Usage: ./scripts/backfill.js --channel=<channel id here>")
|
|
||||||
process.exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
const assert = require("assert/strict")
|
|
||||||
const sqlite = require("better-sqlite3")
|
|
||||||
const backfill = new sqlite("scripts/backfill.db")
|
|
||||||
backfill.prepare("CREATE TABLE IF NOT EXISTS backfill (channel_id TEXT NOT NULL, message_id INTEGER NOT NULL, PRIMARY KEY (channel_id, message_id))").run()
|
|
||||||
|
|
||||||
const HeatSync = require("heatsync")
|
|
||||||
|
|
||||||
const {reg} = require("../src/matrix/read-registration")
|
|
||||||
const passthrough = require("../src/passthrough")
|
|
||||||
|
|
||||||
const sync = new HeatSync({watchFS: false})
|
|
||||||
const db = new sqlite("ooye.db")
|
|
||||||
Object.assign(passthrough, {sync, db})
|
|
||||||
|
|
||||||
const DiscordClient = require("../src/d2m/discord-client")
|
|
||||||
|
|
||||||
const discord = new DiscordClient(reg.ooye.discord_token, "half")
|
|
||||||
passthrough.discord = discord
|
|
||||||
|
|
||||||
const {as} = require("../src/matrix/appservice")
|
|
||||||
passthrough.as = as
|
|
||||||
|
|
||||||
const orm = sync.require("../src/db/orm")
|
|
||||||
passthrough.from = orm.from
|
|
||||||
passthrough.select = orm.select
|
|
||||||
|
|
||||||
/** @type {import("../src/d2m/event-dispatcher")}*/
|
|
||||||
const eventDispatcher = sync.require("../src/d2m/event-dispatcher")
|
|
||||||
|
|
||||||
const roomID = passthrough.select("channel_room", "room_id", {channel_id: channelID}).pluck().get()
|
|
||||||
if (!roomID) {
|
|
||||||
console.error("Please choose a channel that's already bridged.")
|
|
||||||
process.exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
;(async () => {
|
|
||||||
await discord.cloud.connect()
|
|
||||||
console.log("Connected, waiting for data about requested channel...")
|
|
||||||
|
|
||||||
discord.cloud.on("event", event)
|
|
||||||
})()
|
|
||||||
|
|
||||||
const preparedInsert = backfill.prepare("INSERT INTO backfill (channel_id, message_id) VALUES (?, ?)")
|
|
||||||
|
|
||||||
async function event(event) {
|
|
||||||
if (event.t !== "GUILD_CREATE") return
|
|
||||||
const channel = event.d.channels.find(c => c.id === channelID)
|
|
||||||
if (!channel) return
|
|
||||||
const guild_id = event.d.id
|
|
||||||
|
|
||||||
let last = backfill.prepare("SELECT cast(max(message_id) as TEXT) FROM backfill WHERE channel_id = ?").pluck().get(channelID) || "0"
|
|
||||||
console.log(`OK, processing messages for #${channel.name}, continuing from ${last}`)
|
|
||||||
|
|
||||||
while (last) {
|
|
||||||
const messages = await discord.snow.channel.getChannelMessages(channelID, {limit: 50, after: String(last)})
|
|
||||||
messages.reverse() // More recent messages come first -> More recent messages come last
|
|
||||||
for (const message of messages) {
|
|
||||||
const simulatedGatewayDispatchData = {
|
|
||||||
guild_id,
|
|
||||||
backfill: true,
|
|
||||||
...message
|
|
||||||
}
|
|
||||||
await eventDispatcher.MESSAGE_CREATE(discord, simulatedGatewayDispatchData)
|
|
||||||
preparedInsert.run(channelID, message.id)
|
|
||||||
}
|
|
||||||
last = messages.at(-1)?.id
|
|
||||||
}
|
|
||||||
|
|
||||||
process.exit()
|
|
||||||
}
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const fs = require("fs")
|
|
||||||
const {join} = require("path")
|
|
||||||
const s = fs.readFileSync(join(__dirname, "..", "src", "m2d", "converters", "emojis.txt"), "utf8").split("\n").map(x => encodeURIComponent(x))
|
|
||||||
const searchPattern = "%EF%B8%8F"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* adapted from es.map.group-by.js in core-js
|
|
||||||
* @template K,V
|
|
||||||
* @param {V[]} items
|
|
||||||
* @param {(item: V) => K} fn
|
|
||||||
* @returns {Map<K, V[]>}
|
|
||||||
*/
|
|
||||||
function groupBy(items, fn) {
|
|
||||||
var map = new Map();
|
|
||||||
for (const value of items) {
|
|
||||||
var key = fn(value);
|
|
||||||
if (!map.has(key)) map.set(key, [value]);
|
|
||||||
else map.get(key).push(value);
|
|
||||||
}
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {number[]} items
|
|
||||||
* @param {number} width
|
|
||||||
*/
|
|
||||||
function xhistogram(items, width) {
|
|
||||||
const chars = " ▏▎▍▌▋▊▉"
|
|
||||||
const max = items.reduce((a, c) => c > a ? c : a, 0)
|
|
||||||
return items.map(v => {
|
|
||||||
const p = v / max * (width-1)
|
|
||||||
return (
|
|
||||||
Array(Math.floor(p)).fill("█").join("") /* whole part */
|
|
||||||
+ chars[Math.ceil((p % 1) * (chars.length-1))] /* decimal part */
|
|
||||||
).padEnd(width)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {number[]} items
|
|
||||||
* @param {[number, number]} xrange
|
|
||||||
*/
|
|
||||||
function yhistogram(items, xrange, printHeader = false) {
|
|
||||||
const chars = "░▁_▂▃▄▅▆▇█"
|
|
||||||
const ones = "₀₁₂₃₄₅₆₇₈₉"
|
|
||||||
const tens = "0123456789"
|
|
||||||
const xy = []
|
|
||||||
let max = 0
|
|
||||||
/** value (x) -> frequency (y) */
|
|
||||||
const grouped = groupBy(items, x => x)
|
|
||||||
for (let i = xrange[0]; i <= xrange[1]; i++) {
|
|
||||||
if (printHeader) {
|
|
||||||
if (i === -1) process.stdout.write("-")
|
|
||||||
else if (i.toString().at(-1) === "0") process.stdout.write(tens[i/10])
|
|
||||||
else process.stdout.write(ones[i%10])
|
|
||||||
}
|
|
||||||
const y = grouped.get(i)?.length ?? 0
|
|
||||||
if (y > max) max = y
|
|
||||||
xy.push(y)
|
|
||||||
}
|
|
||||||
if (printHeader) console.log()
|
|
||||||
return xy.map(y => chars[Math.ceil(y / max * (chars.length-1))]).join("")
|
|
||||||
}
|
|
||||||
|
|
||||||
const grouped = groupBy(s, x => x.length)
|
|
||||||
const sortedGroups = [...grouped.entries()].sort((a, b) => b[0] - a[0])
|
|
||||||
let length = 0
|
|
||||||
const lengthHistogram = xhistogram(sortedGroups.map(v => v[1].length), 10)
|
|
||||||
for (let i = 0; i < sortedGroups.length; i++) {
|
|
||||||
const [k, v] = sortedGroups[i]
|
|
||||||
const l = lengthHistogram[i]
|
|
||||||
const h = yhistogram(v.map(x => x.indexOf(searchPattern)), [-1, k - searchPattern.length], i === 0)
|
|
||||||
if (i === 0) length = h.length + 1
|
|
||||||
console.log(`${h.padEnd(length, i % 2 === 0 ? "⸱" : " ")}length ${k.toString().padEnd(3)} ${l} ${v.length}`)
|
|
||||||
}
|
|
||||||
|
|
@ -1,65 +0,0 @@
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const pb = require("prettier-bytes")
|
|
||||||
const sqlite = require("better-sqlite3")
|
|
||||||
const HeatSync = require("heatsync")
|
|
||||||
|
|
||||||
const {reg} = require("../src/matrix/read-registration")
|
|
||||||
const passthrough = require("../src/passthrough")
|
|
||||||
|
|
||||||
const sync = new HeatSync({watchFS: false})
|
|
||||||
Object.assign(passthrough, {reg, sync})
|
|
||||||
|
|
||||||
const DiscordClient = require("../src/d2m/discord-client")
|
|
||||||
|
|
||||||
const discord = new DiscordClient(reg.ooye.discord_token, "no")
|
|
||||||
passthrough.discord = discord
|
|
||||||
|
|
||||||
const db = new sqlite("ooye.db")
|
|
||||||
passthrough.db = db
|
|
||||||
|
|
||||||
const api = require("../src/matrix/api")
|
|
||||||
|
|
||||||
const {room: roomID} = require("minimist")(process.argv.slice(2), {string: ["room"]})
|
|
||||||
if (!roomID) {
|
|
||||||
console.error("Usage: ./scripts/estimate-size.js --room=<!room id here>")
|
|
||||||
process.exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
const {channel_id, guild_id} = db.prepare("SELECT channel_id, guild_id FROM channel_room WHERE room_id = ?").get(roomID)
|
|
||||||
|
|
||||||
const max = 1000
|
|
||||||
|
|
||||||
;(async () => {
|
|
||||||
let total = 0
|
|
||||||
let size = 0
|
|
||||||
let from
|
|
||||||
|
|
||||||
while (total < max) {
|
|
||||||
const events = await api.getEvents(roomID, "b", {limit: 1000, from})
|
|
||||||
total += events.chunk.length
|
|
||||||
from = events.end
|
|
||||||
console.log(`Fetched ${total} events so far`)
|
|
||||||
|
|
||||||
for (const e of events.chunk) {
|
|
||||||
if (e.content?.info?.size) {
|
|
||||||
size += e.content.info.size
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (events.chunk.length === 0 || !events.end) break
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`Total size of uploads: ${pb(size)}`)
|
|
||||||
|
|
||||||
const searchResults = await discord.snow.requestHandler.request(`/guilds/${guild_id}/messages/search`, {
|
|
||||||
channel_id,
|
|
||||||
offset: "0",
|
|
||||||
limit: "1"
|
|
||||||
}, "get", "json")
|
|
||||||
|
|
||||||
const totalAllTime = searchResults.total_results
|
|
||||||
const fractionCounted = total / totalAllTime
|
|
||||||
console.log(`That counts for ${(fractionCounted*100).toFixed(2)}% of the history on Discord (${totalAllTime.toLocaleString()} messages)`)
|
|
||||||
console.log(`The size of uploads for the whole history would be approx: ${pb(Math.floor(size/total*totalAllTime))}`)
|
|
||||||
})()
|
|
||||||
|
|
@ -2,7 +2,8 @@
|
||||||
// @ts-check
|
// @ts-check
|
||||||
|
|
||||||
const assert = require("assert").strict
|
const assert = require("assert").strict
|
||||||
const {Semaphore} = require("@chriscdn/promise-semaphore")
|
/** @type {any} */ // @ts-ignore bad types from semaphore
|
||||||
|
const Semaphore = require("@chriscdn/promise-semaphore")
|
||||||
const sqlite = require("better-sqlite3")
|
const sqlite = require("better-sqlite3")
|
||||||
const HeatSync = require("heatsync")
|
const HeatSync = require("heatsync")
|
||||||
|
|
||||||
|
|
@ -37,9 +38,7 @@ const createRoom = sync.require("../d2m/actions/create-room")
|
||||||
/** @type {import("../src/matrix/mreq")} */
|
/** @type {import("../src/matrix/mreq")} */
|
||||||
const mreq = sync.require("../matrix/mreq")
|
const mreq = sync.require("../matrix/mreq")
|
||||||
/** @type {import("../src/matrix/api")} */
|
/** @type {import("../src/matrix/api")} */
|
||||||
const api = sync.require("../src/matrix/api")
|
const api = sync.require("../matrix/api")
|
||||||
/** @type {import("../src/matrix/utils")} */
|
|
||||||
const utils = sync.require("../src/matrix/utils")
|
|
||||||
|
|
||||||
const sema = new Semaphore()
|
const sema = new Semaphore()
|
||||||
|
|
||||||
|
|
@ -82,8 +81,16 @@ async function migrateGuild(guild) {
|
||||||
// Step 2: (Using old bridge access token) Join the new bridge to the old rooms and give it PL 100
|
// Step 2: (Using old bridge access token) Join the new bridge to the old rooms and give it PL 100
|
||||||
console.log(`-- Joining channel ${channel.name}...`)
|
console.log(`-- Joining channel ${channel.name}...`)
|
||||||
await mreq.withAccessToken(oldAT, async () => {
|
await mreq.withAccessToken(oldAT, async () => {
|
||||||
|
try {
|
||||||
await api.inviteToRoom(roomID, newBridgeMxid)
|
await api.inviteToRoom(roomID, newBridgeMxid)
|
||||||
await utils.setUserPower(roomID, newBridgeMxid, 100, api)
|
} catch (e) {
|
||||||
|
if (e.message.includes("is already in the room")) {
|
||||||
|
// Great!
|
||||||
|
} else {
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await api.setUserPower(roomID, newBridgeMxid, 100)
|
||||||
})
|
})
|
||||||
await api.joinRoom(roomID)
|
await api.joinRoom(roomID)
|
||||||
|
|
||||||
|
|
@ -108,7 +115,7 @@ async function migrateGuild(guild) {
|
||||||
// (By the way, thread_parent is always null here because thread rooms would never be migrated because they are not in the old bridge.)
|
// (By the way, thread_parent is always null here because thread rooms would never be migrated because they are not in the old bridge.)
|
||||||
db.transaction(() => {
|
db.transaction(() => {
|
||||||
db.prepare("DELETE FROM channel_room WHERE channel_id = ?").run(channel.id)
|
db.prepare("DELETE FROM channel_room WHERE channel_id = ?").run(channel.id)
|
||||||
db.prepare("INSERT INTO channel_room (channel_id, room_id, name, nick, custom_avatar, guild_id) VALUES (?, ?, ?, ?, ?, ?)").run(channel.id, row.matrix_id, channel.name, preMigrationRow.nick, preMigrationRow.custom_avatar, guild.id)
|
db.prepare("INSERT INTO channel_room (channel_id, room_id, name, nick, custom_avatar) VALUES (?, ?, ?, ?, ?)").run(channel.id, row.matrix_id, channel.name, preMigrationRow.nick, preMigrationRow.custom_avatar)
|
||||||
console.log(`-- -- Added to database (transferred properties from previous OOYE room)`)
|
console.log(`-- -- Added to database (transferred properties from previous OOYE room)`)
|
||||||
})()
|
})()
|
||||||
} else {
|
} else {
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,6 @@ const passthrough = require("../src/passthrough")
|
||||||
Object.assign(passthrough, {db, sync})
|
Object.assign(passthrough, {db, sync})
|
||||||
|
|
||||||
const api = require("../src/matrix/api")
|
const api = require("../src/matrix/api")
|
||||||
const utils = require("../src/matrix/utils")
|
|
||||||
const mreq = require("../src/matrix/mreq")
|
const mreq = require("../src/matrix/mreq")
|
||||||
|
|
||||||
const rooms = db.prepare("select room_id from channel_room").pluck().all()
|
const rooms = db.prepare("select room_id from channel_room").pluck().all()
|
||||||
|
|
@ -26,7 +25,7 @@ const rooms = db.prepare("select room_id from channel_room").pluck().all()
|
||||||
await api.leaveRoom(roomID, mxid)
|
await api.leaveRoom(roomID, mxid)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await utils.setUserPower(roomID, "@_discord_bot:cadence.moe", 0, api)
|
await api.setUserPower(roomID, "@_discord_bot:cadence.moe", 0)
|
||||||
await api.leaveRoom(roomID)
|
await api.leaveRoom(roomID)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e.message.includes("Appservice not in room")) {
|
if (e.message.includes("Appservice not in room")) {
|
||||||
|
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const {reg, writeRegistration, registrationFilePath} = require("../src/matrix/read-registration")
|
|
||||||
const {prompt} = require("enquirer")
|
|
||||||
|
|
||||||
;(async () => {
|
|
||||||
/** @type {{web_password: string}} */
|
|
||||||
const passwordResponse = await prompt({
|
|
||||||
type: "text",
|
|
||||||
name: "web_password",
|
|
||||||
message: "Choose a simple password (optional)"
|
|
||||||
})
|
|
||||||
|
|
||||||
reg.ooye.web_password = passwordResponse.web_password
|
|
||||||
writeRegistration(reg)
|
|
||||||
console.log("Saved. Restart Out Of Your Element to apply this change.")
|
|
||||||
})()
|
|
||||||
332
scripts/seed.js
Executable file
332
scripts/seed.js
Executable file
|
|
@ -0,0 +1,332 @@
|
||||||
|
#!/usr/bin/env node
|
||||||
|
// @ts-check
|
||||||
|
|
||||||
|
const assert = require("assert").strict
|
||||||
|
const fs = require("fs")
|
||||||
|
const sqlite = require("better-sqlite3")
|
||||||
|
const {scheduler} = require("timers/promises")
|
||||||
|
const {isDeepStrictEqual} = require("util")
|
||||||
|
const {createServer} = require("http")
|
||||||
|
|
||||||
|
const {prompt} = require("enquirer")
|
||||||
|
const Input = require("enquirer/lib/prompts/input")
|
||||||
|
const fetch = require("node-fetch").default
|
||||||
|
const {magenta, bold, cyan} = require("ansi-colors")
|
||||||
|
const HeatSync = require("heatsync")
|
||||||
|
const {SnowTransfer} = require("snowtransfer")
|
||||||
|
const {createApp, defineEventHandler, toNodeListener} = require("h3")
|
||||||
|
|
||||||
|
const args = require("minimist")(process.argv.slice(2), {string: ["emoji-guild"]})
|
||||||
|
|
||||||
|
// Move database file if it's still in the old location
|
||||||
|
if (fs.existsSync("db")) {
|
||||||
|
if (fs.existsSync("db/ooye.db")) {
|
||||||
|
fs.renameSync("db/ooye.db", "ooye.db")
|
||||||
|
}
|
||||||
|
const files = fs.readdirSync("db")
|
||||||
|
if (files.length) {
|
||||||
|
console.error("The db folder is deprecated and must be removed. Your ooye.db database file has already been moved to the root of the repo. You must manually move or delete the remaining files:")
|
||||||
|
for (const file of files) {
|
||||||
|
console.error(file)
|
||||||
|
}
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
fs.rmSync("db", {recursive: true})
|
||||||
|
}
|
||||||
|
|
||||||
|
const passthrough = require("../src/passthrough")
|
||||||
|
const db = new sqlite("ooye.db")
|
||||||
|
const migrate = require("../src/db/migrate")
|
||||||
|
|
||||||
|
/** @type {import("heatsync").default} */ // @ts-ignore
|
||||||
|
const sync = new HeatSync({watchFS: false})
|
||||||
|
|
||||||
|
Object.assign(passthrough, {sync, db})
|
||||||
|
|
||||||
|
const orm = sync.require("../src/db/orm")
|
||||||
|
passthrough.from = orm.from
|
||||||
|
passthrough.select = orm.select
|
||||||
|
|
||||||
|
let registration = require("../src/matrix/read-registration")
|
||||||
|
let {reg, getTemplateRegistration, writeRegistration, readRegistration, checkRegistration, registrationFilePath} = registration
|
||||||
|
|
||||||
|
function die(message) {
|
||||||
|
console.error(message)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadAutoEmoji(snow, guild, name, filename) {
|
||||||
|
let emoji = guild.emojis.find(e => e.name === name)
|
||||||
|
if (!emoji) {
|
||||||
|
console.log(` Uploading ${name}...`)
|
||||||
|
const data = fs.readFileSync(filename, null)
|
||||||
|
emoji = await snow.guildAssets.createEmoji(guild.id, {name, image: "data:image/png;base64," + data.toString("base64")})
|
||||||
|
} else {
|
||||||
|
console.log(` Reusing ${name}...`)
|
||||||
|
}
|
||||||
|
db.prepare("REPLACE INTO auto_emoji (name, emoji_id, guild_id) VALUES (?, ?, ?)").run(emoji.name, emoji.id, guild.id)
|
||||||
|
return emoji
|
||||||
|
}
|
||||||
|
|
||||||
|
async function validateHomeserverOrigin(serverUrlPrompt, url) {
|
||||||
|
if (!url.match(/^https?:\/\//)) return "Must be a URL"
|
||||||
|
if (url.match(/\/$/)) return "Must not end with a slash"
|
||||||
|
process.stdout.write(magenta(" checking, please wait..."))
|
||||||
|
try {
|
||||||
|
var json = await fetch(`${url}/.well-known/matrix/client`).then(res => res.json())
|
||||||
|
let baseURL = json["m.homeserver"].base_url.replace(/\/$/, "")
|
||||||
|
if (baseURL && baseURL !== url) {
|
||||||
|
serverUrlPrompt.initial = baseURL
|
||||||
|
return `Did you mean: ${bold(baseURL)}? (Enter to accept)`
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
try {
|
||||||
|
var res = await fetch(`${url}/_matrix/client/versions`)
|
||||||
|
} catch (e) {
|
||||||
|
return e.message
|
||||||
|
}
|
||||||
|
if (res.status !== 200) return `There is no Matrix server at that URL (${url}/_matrix/client/versions returned ${res.status})`
|
||||||
|
try {
|
||||||
|
var json = await res.json()
|
||||||
|
if (!Array.isArray(json?.versions) || !json.versions.includes("v1.11")) {
|
||||||
|
return `OOYE needs Matrix version v1.11, but ${url} doesn't support this`
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
return `There is no Matrix server at that URL (${url}/_matrix/client/versions is not JSON)`
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
;(async () => {
|
||||||
|
// create registration file with prompts...
|
||||||
|
if (!reg) {
|
||||||
|
console.log("What is the name of your homeserver? This is the part after : in your username.")
|
||||||
|
/** @type {{server_name: string}} */
|
||||||
|
const serverNameResponse = await prompt({
|
||||||
|
type: "input",
|
||||||
|
name: "server_name",
|
||||||
|
message: "Homeserver name",
|
||||||
|
validate: serverName => !!serverName.match(/[a-z][a-z.]+[a-z]/)
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log("What is the URL of your homeserver?")
|
||||||
|
const serverOriginPrompt = new Input({
|
||||||
|
type: "input",
|
||||||
|
name: "server_origin",
|
||||||
|
message: "Homeserver URL",
|
||||||
|
initial: () => `https://${serverNameResponse.server_name}`,
|
||||||
|
validate: url => validateHomeserverOrigin(serverOriginPrompt, url)
|
||||||
|
})
|
||||||
|
/** @type {string} */ // @ts-ignore
|
||||||
|
const serverOrigin = await serverOriginPrompt.run()
|
||||||
|
|
||||||
|
const app = createApp()
|
||||||
|
app.use(defineEventHandler(() => "Out Of Your Element is listening.\n"))
|
||||||
|
const server = createServer(toNodeListener(app))
|
||||||
|
await server.listen(6693)
|
||||||
|
|
||||||
|
console.log("OOYE has its own web server. It needs to be accessible on the public internet.")
|
||||||
|
console.log("You need to enter a public URL where you will be able to host this web server.")
|
||||||
|
console.log("OOYE listens on localhost:6693, so you will probably have to set up a reverse proxy.")
|
||||||
|
console.log("Now listening on port 6693. Feel free to send some test requests.")
|
||||||
|
/** @type {{bridge_origin: string}} */
|
||||||
|
const bridgeOriginResponse = await prompt({
|
||||||
|
type: "input",
|
||||||
|
name: "bridge_origin",
|
||||||
|
message: "URL to reach OOYE",
|
||||||
|
initial: () => `https://bridge.${serverNameResponse.server_name}`,
|
||||||
|
validate: async url => {
|
||||||
|
process.stdout.write(magenta(" checking, please wait..."))
|
||||||
|
try {
|
||||||
|
const res = await fetch(url)
|
||||||
|
if (res.status !== 200) return `Server returned status code ${res.status}`
|
||||||
|
const text = await res.text()
|
||||||
|
if (text !== "Out Of Your Element is listening.\n") return `Server does not point to OOYE`
|
||||||
|
return true
|
||||||
|
} catch (e) {
|
||||||
|
return e.message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
await server.close()
|
||||||
|
|
||||||
|
console.log("What is your Discord bot token?")
|
||||||
|
/** @type {{discord_token: string}} */
|
||||||
|
const discordTokenResponse = await prompt({
|
||||||
|
type: "input",
|
||||||
|
name: "discord_token",
|
||||||
|
message: "Bot token",
|
||||||
|
validate: async token => {
|
||||||
|
process.stdout.write(magenta(" checking, please wait..."))
|
||||||
|
try {
|
||||||
|
const snow = new SnowTransfer(token)
|
||||||
|
await snow.user.getSelf()
|
||||||
|
return true
|
||||||
|
} catch (e) {
|
||||||
|
return e.message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log("What is your Discord client secret?")
|
||||||
|
/** @type {{discord_client_secret: string}} */
|
||||||
|
const clientSecretResponse = await prompt({
|
||||||
|
type: "input",
|
||||||
|
name: "discord_client_secret",
|
||||||
|
message: "Client secret"
|
||||||
|
})
|
||||||
|
|
||||||
|
const template = getTemplateRegistration(serverNameResponse.server_name)
|
||||||
|
reg = {
|
||||||
|
...template,
|
||||||
|
url: bridgeOriginResponse.bridge_origin,
|
||||||
|
ooye: {
|
||||||
|
...template.ooye,
|
||||||
|
...serverNameResponse,
|
||||||
|
...bridgeOriginResponse,
|
||||||
|
server_origin: serverOrigin,
|
||||||
|
...discordTokenResponse,
|
||||||
|
...clientSecretResponse
|
||||||
|
}
|
||||||
|
}
|
||||||
|
registration.reg = reg
|
||||||
|
checkRegistration(reg)
|
||||||
|
writeRegistration(reg)
|
||||||
|
console.log(`✅ Registration file saved as ${registrationFilePath}`)
|
||||||
|
} else {
|
||||||
|
console.log(`✅ Valid registration file found at ${registrationFilePath}`)
|
||||||
|
}
|
||||||
|
console.log(` In ${cyan("Synapse")}, you need to add it to homeserver.yaml and ${cyan("restart Synapse")}.`)
|
||||||
|
console.log(" https://element-hq.github.io/synapse/latest/application_services.html")
|
||||||
|
console.log(` In ${cyan("Conduit")}, you need to send the file contents to the #admins room.`)
|
||||||
|
console.log(" https://docs.conduit.rs/appservices.html")
|
||||||
|
console.log()
|
||||||
|
|
||||||
|
// Done with user prompts, reg is now guaranteed to be valid
|
||||||
|
const api = require("../src/matrix/api")
|
||||||
|
const file = require("../src/matrix/file")
|
||||||
|
const utils = require("../src/m2d/converters/utils")
|
||||||
|
const DiscordClient = require("../src/d2m/discord-client")
|
||||||
|
const discord = new DiscordClient(reg.ooye.discord_token, "no")
|
||||||
|
passthrough.discord = discord
|
||||||
|
|
||||||
|
const {as} = require("../src/matrix/appservice")
|
||||||
|
console.log("⏳ Waiting until homeserver registration works... (Ctrl+C to cancel)")
|
||||||
|
|
||||||
|
let itWorks = false
|
||||||
|
let lastError = null
|
||||||
|
do {
|
||||||
|
const result = await api.ping().catch(e => ({ok: false, status: "net", root: e.message}))
|
||||||
|
// If it didn't work, log details and retry after some time
|
||||||
|
itWorks = result.ok
|
||||||
|
if (!itWorks) {
|
||||||
|
// Log the full error data if the error is different to last time
|
||||||
|
if (!isDeepStrictEqual(lastError, result.root)) {
|
||||||
|
if (typeof result.root === "string") {
|
||||||
|
console.log(`\nCannot reach homeserver: ${result.root}`)
|
||||||
|
} else if (result.root.error) {
|
||||||
|
console.log(`\nHomeserver said: [${result.status}] ${result.root.error}`)
|
||||||
|
} else {
|
||||||
|
console.log(`\nHomeserver said: [${result.status}] ${JSON.stringify(result.root)}`)
|
||||||
|
}
|
||||||
|
lastError = result.root
|
||||||
|
} else {
|
||||||
|
process.stderr.write(".")
|
||||||
|
}
|
||||||
|
await scheduler.wait(5000)
|
||||||
|
}
|
||||||
|
} while (!itWorks)
|
||||||
|
console.log("")
|
||||||
|
|
||||||
|
as.close().catch(() => {})
|
||||||
|
|
||||||
|
const mxid = `@${reg.sender_localpart}:${reg.ooye.server_name}`
|
||||||
|
|
||||||
|
// ensure registration is correctly set...
|
||||||
|
assert(reg.sender_localpart.startsWith(reg.ooye.namespace_prefix), "appservice's localpart must be in the namespace it controls")
|
||||||
|
assert(utils.eventSenderIsFromDiscord(mxid), "appservice's mxid must be in the namespace it controls")
|
||||||
|
assert(reg.ooye.server_origin.match(/^https?:\/\//), "server origin must start with http or https")
|
||||||
|
assert.notEqual(reg.ooye.server_origin.slice(-1), "/", "server origin must not end in slash")
|
||||||
|
const botID = Buffer.from(reg.ooye.discord_token.split(".")[0], "base64").toString()
|
||||||
|
assert(botID.match(/^[0-9]{10,}$/), "discord token must follow the correct format")
|
||||||
|
assert.match(reg.url, /^https?:/, "url must start with http:// or https://")
|
||||||
|
|
||||||
|
console.log("✅ Configuration looks good...")
|
||||||
|
|
||||||
|
// database ddl...
|
||||||
|
await migrate.migrate(db)
|
||||||
|
|
||||||
|
// add initial rows to database, like adding the bot to sim...
|
||||||
|
db.prepare("INSERT OR IGNORE INTO sim (user_id, sim_name, localpart, mxid) VALUES (?, ?, ?, ?)").run(botID, reg.sender_localpart.slice(reg.ooye.namespace_prefix.length), reg.sender_localpart, mxid)
|
||||||
|
|
||||||
|
console.log("✅ Database is ready...")
|
||||||
|
|
||||||
|
// ensure appservice bot user is registered...
|
||||||
|
try {
|
||||||
|
await api.register(reg.sender_localpart)
|
||||||
|
} catch (e) {
|
||||||
|
if (e.errcode === "M_USER_IN_USE" || e.data?.error === "Internal server error") {
|
||||||
|
// "Internal server error" is the only OK error because older versions of Synapse say this if you try to register the same username twice.
|
||||||
|
} else {
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// upload initial images...
|
||||||
|
const avatarUrl = await file.uploadDiscordFileToMxc("https://cadence.moe/friends/out_of_your_element.png")
|
||||||
|
|
||||||
|
console.log("✅ Matrix appservice login works...")
|
||||||
|
|
||||||
|
// upload the L1 L2 emojis to some guild
|
||||||
|
const emojis = db.prepare("SELECT name FROM auto_emoji WHERE name = 'L1' OR name = 'L2'").pluck().all()
|
||||||
|
if (emojis.length !== 2) {
|
||||||
|
// If an argument was supplied, always use that one
|
||||||
|
let guild = null
|
||||||
|
if (args["emoji-guild"]) {
|
||||||
|
if (typeof args["emoji-guild"] === "string") {
|
||||||
|
guild = await discord.snow.guild.getGuild(args["emoji-guild"])
|
||||||
|
}
|
||||||
|
if (!guild) return die(`Error: You asked emojis to be uploaded to guild ID ${args["emoji-guild"]}, but the bot isn't in that guild.`)
|
||||||
|
}
|
||||||
|
// Otherwise, check if we have already registered an auto emoji guild
|
||||||
|
if (!guild) {
|
||||||
|
const guildID = passthrough.select("auto_emoji", "guild_id", {name: "_"}).pluck().get()
|
||||||
|
if (guildID) {
|
||||||
|
guild = await discord.snow.guild.getGuild(guildID, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Otherwise, check if we should create a new guild
|
||||||
|
if (!guild) {
|
||||||
|
const guilds = await discord.snow.user.getGuilds({limit: 11, with_counts: false})
|
||||||
|
if (guilds.length < 10) {
|
||||||
|
console.log(" Creating a guild for emojis...")
|
||||||
|
guild = await discord.snow.guild.createGuild({name: "OOYE Emojis"})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Otherwise, it's the user's problem
|
||||||
|
if (!guild) {
|
||||||
|
return die(`Error: The bot needs to upload some emojis. Please say where to upload them to. Run seed.js again with --emoji-guild=GUILD_ID`)
|
||||||
|
}
|
||||||
|
// Upload those emojis to the chosen location
|
||||||
|
db.prepare("REPLACE INTO auto_emoji (name, emoji_id, guild_id) VALUES ('_', '_', ?)").run(guild.id)
|
||||||
|
await uploadAutoEmoji(discord.snow, guild, "L1", "docs/img/L1.png")
|
||||||
|
await uploadAutoEmoji(discord.snow, guild, "L2", "docs/img/L2.png")
|
||||||
|
}
|
||||||
|
console.log("✅ Emojis are ready...")
|
||||||
|
|
||||||
|
// set profile data on discord...
|
||||||
|
const avatarImageBuffer = await fetch("https://cadence.moe/friends/out_of_your_element.png").then(res => res.arrayBuffer())
|
||||||
|
await discord.snow.user.updateSelf({avatar: "data:image/png;base64," + Buffer.from(avatarImageBuffer).toString("base64")})
|
||||||
|
await discord.snow.requestHandler.request(`/applications/@me`, {}, "patch", "json", {description: "Powered by **Out Of Your Element**\nhttps://gitdab.com/cadence/out-of-your-element"})
|
||||||
|
console.log("✅ Discord profile updated...")
|
||||||
|
|
||||||
|
// set profile data on homeserver...
|
||||||
|
console.log("⏩ Updating Matrix profile... (If you've joined lots of rooms, this is slow. Please allow at least 30 seconds.)")
|
||||||
|
await api.profileSetDisplayname(mxid, "Out Of Your Element")
|
||||||
|
await api.profileSetAvatarUrl(mxid, avatarUrl)
|
||||||
|
console.log("✅ Matrix profile updated...")
|
||||||
|
|
||||||
|
console.log("Good to go. I hope you enjoy Out Of Your Element.")
|
||||||
|
process.exit()
|
||||||
|
})()
|
||||||
373
scripts/setup.js
373
scripts/setup.js
|
|
@ -1,373 +0,0 @@
|
||||||
#!/usr/bin/env node
|
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const Ty = require("../src/types")
|
|
||||||
const assert = require("assert").strict
|
|
||||||
const fs = require("fs")
|
|
||||||
const sqlite = require("better-sqlite3")
|
|
||||||
const {scheduler} = require("timers/promises")
|
|
||||||
const {isDeepStrictEqual} = require("util")
|
|
||||||
const {createServer} = require("http")
|
|
||||||
const {join} = require("path")
|
|
||||||
|
|
||||||
const {prompt} = require("enquirer")
|
|
||||||
const Input = require("enquirer/lib/prompts/input")
|
|
||||||
const {magenta, bold, cyan} = require("ansi-colors")
|
|
||||||
const HeatSync = require("heatsync")
|
|
||||||
const {SnowTransfer} = require("snowtransfer")
|
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
|
||||||
const {createApp, defineEventHandler, toNodeListener} = require("h3")
|
|
||||||
|
|
||||||
const passthrough = require("../src/passthrough")
|
|
||||||
const db = new sqlite("ooye.db")
|
|
||||||
const migrate = require("../src/db/migrate")
|
|
||||||
|
|
||||||
const sync = new HeatSync({watchFS: false})
|
|
||||||
|
|
||||||
Object.assign(passthrough, {sync, db})
|
|
||||||
|
|
||||||
const orm = sync.require("../src/db/orm")
|
|
||||||
passthrough.from = orm.from
|
|
||||||
passthrough.select = orm.select
|
|
||||||
|
|
||||||
let registration = require("../src/matrix/read-registration")
|
|
||||||
let {reg, getTemplateRegistration, writeRegistration, readRegistration, checkRegistration, registrationFilePath} = registration
|
|
||||||
|
|
||||||
const {setupEmojis} = require("../src/m2d/actions/setup-emojis")
|
|
||||||
|
|
||||||
async function suggestWellKnown(serverUrlPrompt, url, otherwise) {
|
|
||||||
try {
|
|
||||||
var json = await fetch(`${url}/.well-known/matrix/client`).then(res => res.json())
|
|
||||||
let baseURL = json["m.homeserver"].base_url.replace(/\/$/, "")
|
|
||||||
if (baseURL && baseURL !== url) {
|
|
||||||
serverUrlPrompt.initial = baseURL
|
|
||||||
return `Did you mean: ${bold(baseURL)}? (Enter to accept)`
|
|
||||||
}
|
|
||||||
} catch (e) {}
|
|
||||||
return otherwise
|
|
||||||
}
|
|
||||||
|
|
||||||
async function validateHomeserverOrigin(serverUrlPrompt, url) {
|
|
||||||
if (!url.match(/^https?:\/\//)) return "Must be a URL"
|
|
||||||
if (url.match(/\/$/)) return "Must not end with a slash"
|
|
||||||
process.stdout.write(magenta(" checking, please wait..."))
|
|
||||||
try {
|
|
||||||
var res = await fetch(`${url}/_matrix/client/versions`)
|
|
||||||
if (res.status !== 200) {
|
|
||||||
return suggestWellKnown(serverUrlPrompt, url, `There is no Matrix server at that URL (${url}/_matrix/client/versions returned ${res.status})`)
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
return e.message
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
/** @type {any} */
|
|
||||||
var json = await res.json()
|
|
||||||
if (!Array.isArray(json?.versions) || !json.versions.includes("v1.11")) {
|
|
||||||
return `OOYE needs Matrix version v1.11, but ${url} doesn't support this`
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
return suggestWellKnown(serverUrlPrompt, url, `There is no Matrix server at that URL (${url}/_matrix/client/versions is not JSON)`)
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
function defineEchoHandler() {
|
|
||||||
return defineEventHandler(event => {
|
|
||||||
return "Out Of Your Element is listening.\n" +
|
|
||||||
`Received a ${event.method} request on path ${event.path}\n`
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
;(async () => {
|
|
||||||
// create registration file with prompts...
|
|
||||||
if (!reg) {
|
|
||||||
console.log("What is the name of your homeserver? This is the part after : in your username.")
|
|
||||||
/** @type {{server_name: string}} */
|
|
||||||
const serverNameResponse = await prompt({
|
|
||||||
type: "input",
|
|
||||||
name: "server_name",
|
|
||||||
message: "Homeserver name",
|
|
||||||
validate: serverName => !!serverName.match(/[a-z0-9][.a-z0-9-]+[a-z]/)
|
|
||||||
})
|
|
||||||
|
|
||||||
console.log("What is the URL of your homeserver?")
|
|
||||||
const serverOriginPrompt = new Input({
|
|
||||||
type: "input",
|
|
||||||
name: "server_origin",
|
|
||||||
message: "Homeserver URL",
|
|
||||||
initial: () => `https://${serverNameResponse.server_name}`,
|
|
||||||
validate: url => validateHomeserverOrigin(serverOriginPrompt, url)
|
|
||||||
})
|
|
||||||
/** @type {string} */ // @ts-ignore
|
|
||||||
const serverOrigin = await serverOriginPrompt.run()
|
|
||||||
|
|
||||||
console.log("OOYE has its own web server. It needs to be accessible on the public internet.")
|
|
||||||
console.log("What port would you like OOYE to use? You can connect your reverse proxy to this port later.")
|
|
||||||
/** @type {{socket: string | number}} */
|
|
||||||
const portResponse = await prompt({
|
|
||||||
type: "input",
|
|
||||||
name: "socket",
|
|
||||||
message: "Web server port",
|
|
||||||
initial: "6693"
|
|
||||||
})
|
|
||||||
portResponse.socket = +portResponse.socket || portResponse.socket // convert to number if numeric
|
|
||||||
|
|
||||||
const app = createApp()
|
|
||||||
app.use(defineEchoHandler())
|
|
||||||
const server = createServer(toNodeListener(app))
|
|
||||||
await server.listen(portResponse.socket)
|
|
||||||
|
|
||||||
console.log("Now you need to enter a public URL that OOYE's web server will live on.")
|
|
||||||
console.log("Set up your reverse proxy so that this URL accesses OOYE.")
|
|
||||||
console.log("Examples: https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/get-started.md#appendix")
|
|
||||||
if (typeof portResponse.socket === "number") {
|
|
||||||
console.log(`Now listening on http://localhost:${portResponse.socket}. Feel free to send some test requests.`)
|
|
||||||
}
|
|
||||||
/** @type {{bridge_origin: string}} */
|
|
||||||
const bridgeOriginResponse = await prompt({
|
|
||||||
type: "input",
|
|
||||||
name: "bridge_origin",
|
|
||||||
message: "URL to reach OOYE",
|
|
||||||
initial: () => `https://bridge.${serverNameResponse.server_name}`,
|
|
||||||
validate: async url => {
|
|
||||||
process.stdout.write(magenta(" checking, please wait..."))
|
|
||||||
try {
|
|
||||||
const res = await fetch(url)
|
|
||||||
if (res.status !== 200) return `Server returned status code ${res.status}`
|
|
||||||
const text = await res.text()
|
|
||||||
if (!text.startsWith("Out Of Your Element is listening.")) return `Server does not point to OOYE`
|
|
||||||
return true
|
|
||||||
} catch (e) {
|
|
||||||
return e.message
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
bridgeOriginResponse.bridge_origin = bridgeOriginResponse.bridge_origin.replace(/\/+$/, "") // remove trailing slash
|
|
||||||
|
|
||||||
await server.close()
|
|
||||||
|
|
||||||
console.log("What is your Discord bot token?")
|
|
||||||
console.log("Go to https://discord.com/developers, create or pick an app, go to the Bot section, and reset the token.")
|
|
||||||
/** @type {SnowTransfer} */ // @ts-ignore
|
|
||||||
let snow = null
|
|
||||||
/** @type {{id: string, flags: number, redirect_uris: string[], description: string}} */ // @ts-ignore
|
|
||||||
let client = null
|
|
||||||
/** @type {{discord_token: string}} */
|
|
||||||
const discordTokenResponse = await prompt({
|
|
||||||
type: "input",
|
|
||||||
name: "discord_token",
|
|
||||||
message: "Bot token",
|
|
||||||
validate: async token => {
|
|
||||||
process.stdout.write(magenta(" checking, please wait..."))
|
|
||||||
try {
|
|
||||||
snow = new SnowTransfer(token)
|
|
||||||
client = await snow.requestHandler.request(`/applications/@me`, {}, "get", "json")
|
|
||||||
return true
|
|
||||||
} catch (e) {
|
|
||||||
return e.message
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const intentFlagPossibilities = [
|
|
||||||
DiscordTypes.ApplicationFlags.GatewayMessageContent | DiscordTypes.ApplicationFlags.GatewayPresence | DiscordTypes.ApplicationFlags.GatewayGuildMembers,
|
|
||||||
DiscordTypes.ApplicationFlags.GatewayMessageContentLimited | DiscordTypes.ApplicationFlags.GatewayPresenceLimited | DiscordTypes.ApplicationFlags.GatewayGuildMembersLimited
|
|
||||||
]
|
|
||||||
const intentFlagMask = intentFlagPossibilities.reduce((a, c) => a | c, 0)
|
|
||||||
if (!intentFlagPossibilities.includes(client.flags & intentFlagMask)) {
|
|
||||||
console.log(`On that same page, scroll down to Privileged Gateway Intents and enable all switches.`)
|
|
||||||
await prompt({
|
|
||||||
type: "invisible",
|
|
||||||
name: "intents",
|
|
||||||
message: "Press Enter when you've enabled them",
|
|
||||||
validate: async () => {
|
|
||||||
process.stdout.write(magenta("checking, please wait..."))
|
|
||||||
client = await snow.requestHandler.request(`/applications/@me`, {}, "get", "json")
|
|
||||||
if (intentFlagPossibilities.includes(client.flags & intentFlagMask)) {
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
return "Switches have not been enabled yet"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log("Would you like to require a password to add your bot to servers? This will discourage others from using your bridge.")
|
|
||||||
console.log("Important: To make it truly private, you MUST ALSO disable Public Bot in the Discord bot configuration page.")
|
|
||||||
/** @type {{web_password: string}} */
|
|
||||||
const passwordResponse = await prompt({
|
|
||||||
type: "text",
|
|
||||||
name: "web_password",
|
|
||||||
message: "Choose a simple password (optional)"
|
|
||||||
})
|
|
||||||
|
|
||||||
console.log("To fulfill license obligations, I recommend mentioning Out Of Your Element in your Discord bot's profile.")
|
|
||||||
console.log("On the Discord bot configuration page, go to General and add something like this to the description:")
|
|
||||||
console.log(cyan("Powered by **Out Of Your Element**"))
|
|
||||||
console.log(cyan("https://gitdab.com/cadence/out-of-your-element"))
|
|
||||||
await prompt({
|
|
||||||
type: "invisible",
|
|
||||||
name: "description",
|
|
||||||
message: "Press Enter to acknowledge",
|
|
||||||
validate: async () => {
|
|
||||||
process.stdout.write(magenta("checking, please wait..."))
|
|
||||||
client = await snow.requestHandler.request(`/applications/@me`, {}, "get", "json")
|
|
||||||
if (client.description?.match(/out.of.your.element/i)) {
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
return "Description must name or link Out Of Your Element"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
console.log("What is your Discord client secret?")
|
|
||||||
console.log(`You can find it in the application's OAuth2 section: https://discord.com/developers/applications/${client.id}/oauth2`)
|
|
||||||
/** @type {{discord_client_secret: string}} */
|
|
||||||
const clientSecretResponse = await prompt({
|
|
||||||
type: "input",
|
|
||||||
name: "discord_client_secret",
|
|
||||||
message: "Client secret",
|
|
||||||
validate: secret => !!secret
|
|
||||||
})
|
|
||||||
|
|
||||||
const expectedUri = `${bridgeOriginResponse.bridge_origin}/oauth`
|
|
||||||
if (!client.redirect_uris.includes(expectedUri)) {
|
|
||||||
console.log(`On that same page, scroll down to Redirects and add this URI: ${cyan(expectedUri)}`)
|
|
||||||
await prompt({
|
|
||||||
type: "invisible",
|
|
||||||
name: "redirect_uri",
|
|
||||||
message: "Press Enter when you've added it",
|
|
||||||
validate: async () => {
|
|
||||||
process.stdout.write(magenta("checking, please wait..."))
|
|
||||||
client = await snow.requestHandler.request(`/applications/@me`, {}, "get", "json")
|
|
||||||
if (client.redirect_uris.includes(expectedUri)) {
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
return "Redirect URI has not been added yet"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const template = getTemplateRegistration(serverNameResponse.server_name)
|
|
||||||
reg = {
|
|
||||||
...template,
|
|
||||||
url: bridgeOriginResponse.bridge_origin,
|
|
||||||
...portResponse,
|
|
||||||
ooye: {
|
|
||||||
...template.ooye,
|
|
||||||
...bridgeOriginResponse,
|
|
||||||
server_origin: serverOrigin,
|
|
||||||
...discordTokenResponse,
|
|
||||||
...clientSecretResponse,
|
|
||||||
...passwordResponse
|
|
||||||
}
|
|
||||||
}
|
|
||||||
registration.reg = reg
|
|
||||||
checkRegistration(reg)
|
|
||||||
writeRegistration(reg)
|
|
||||||
console.log(`✅ Your responses have been saved as ${registrationFilePath}`)
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
checkRegistration(reg)
|
|
||||||
console.log(`✅ Skipped questions - reusing data from ${registrationFilePath}`)
|
|
||||||
} catch (e) {
|
|
||||||
console.log(`❌ Failed to reuse data from ${registrationFilePath}`)
|
|
||||||
console.log("Consider deleting this file. You can re-run setup to safely make a new one.")
|
|
||||||
console.log("")
|
|
||||||
console.log(e.toString().replace(/^ *\n/gm, ""))
|
|
||||||
process.exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
console.log(` In ${cyan("Synapse")}, you need to reference that file in your homeserver.yaml and ${cyan("restart Synapse")}.`)
|
|
||||||
console.log(" https://element-hq.github.io/synapse/latest/application_services.html")
|
|
||||||
console.log(` In ${cyan("Conduit")}, you need to send the file contents to the #admins room.`)
|
|
||||||
console.log(" https://docs.conduit.rs/appservices.html")
|
|
||||||
console.log()
|
|
||||||
|
|
||||||
// Done with user prompts, reg is now guaranteed to be valid
|
|
||||||
const mreq = require("../src/matrix/mreq")
|
|
||||||
const api = require("../src/matrix/api")
|
|
||||||
const DiscordClient = require("../src/d2m/discord-client")
|
|
||||||
const discord = new DiscordClient(reg.ooye.discord_token, "no")
|
|
||||||
passthrough.discord = discord
|
|
||||||
|
|
||||||
const {as} = require("../src/matrix/appservice")
|
|
||||||
as.router.use("/**", defineEchoHandler())
|
|
||||||
await as.listen()
|
|
||||||
|
|
||||||
console.log("⏳ Waiting for you to register the file with your homeserver... (Ctrl+C to cancel)")
|
|
||||||
process.once("SIGINT", () => {
|
|
||||||
console.log("(Ctrl+C) Quit early. Please re-run setup later and allow it to complete.")
|
|
||||||
process.exit(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
let itWorks = false
|
|
||||||
let lastError = null
|
|
||||||
do {
|
|
||||||
const result = await api.ping().catch(e => ({ok: false, status: "net", root: e.message}))
|
|
||||||
// If it didn't work, log details and retry after some time
|
|
||||||
itWorks = result.ok
|
|
||||||
if (!itWorks) {
|
|
||||||
// Log the full error data if the error is different to last time
|
|
||||||
if (!isDeepStrictEqual(lastError, result.root)) {
|
|
||||||
if (typeof result.root === "string") {
|
|
||||||
console.log(`\nCannot reach homeserver: ${result.root}`)
|
|
||||||
} else if (result.root.error) {
|
|
||||||
console.log(`\nHomeserver said: [${result.status}] ${result.root.error}`)
|
|
||||||
} else {
|
|
||||||
console.log(`\nHomeserver said: [${result.status}] ${JSON.stringify(result.root)}`)
|
|
||||||
}
|
|
||||||
lastError = result.root
|
|
||||||
} else {
|
|
||||||
process.stderr.write(".")
|
|
||||||
}
|
|
||||||
await scheduler.wait(5000)
|
|
||||||
}
|
|
||||||
} while (!itWorks)
|
|
||||||
console.log("")
|
|
||||||
|
|
||||||
as.close().catch(() => {})
|
|
||||||
|
|
||||||
const mxid = `@${reg.sender_localpart}:${reg.ooye.server_name}`
|
|
||||||
|
|
||||||
// database ddl...
|
|
||||||
await migrate.migrate(db)
|
|
||||||
|
|
||||||
// add initial rows to database, like adding the bot to sim...
|
|
||||||
const client = await discord.snow.user.getSelf()
|
|
||||||
db.prepare("INSERT INTO sim (user_id, username, sim_name, mxid) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING").run(client.id, client.username, reg.sender_localpart.slice(reg.ooye.namespace_prefix.length), mxid)
|
|
||||||
|
|
||||||
console.log("✅ Database is ready...")
|
|
||||||
|
|
||||||
// ensure appservice bot user is registered...
|
|
||||||
await api.register(reg.sender_localpart)
|
|
||||||
|
|
||||||
// upload initial images...
|
|
||||||
const avatarBuffer = await fs.promises.readFile(join(__dirname, "..", "docs", "img", "icon.png"), null)
|
|
||||||
/** @type {Ty.R.FileUploaded} */
|
|
||||||
const root = await mreq.mreq("POST", "/media/v3/upload", avatarBuffer, {
|
|
||||||
headers: {"Content-Type": "image/png"}
|
|
||||||
})
|
|
||||||
const avatarUrl = root.content_uri
|
|
||||||
assert(avatarUrl)
|
|
||||||
|
|
||||||
console.log("✅ Matrix appservice login works...")
|
|
||||||
|
|
||||||
// upload the L1 L2 emojis to user emojis
|
|
||||||
await setupEmojis()
|
|
||||||
console.log("✅ Emojis are ready...")
|
|
||||||
|
|
||||||
// set profile data on discord...
|
|
||||||
await discord.snow.user.updateSelf({avatar: "data:image/png;base64," + avatarBuffer.toString("base64")})
|
|
||||||
console.log("✅ Discord profile updated...")
|
|
||||||
|
|
||||||
// set profile data on homeserver...
|
|
||||||
console.log("⏩ Updating Matrix profile... (If you've joined lots of rooms, this is slow. Please allow at least 30 seconds.)")
|
|
||||||
await api.profileSetDisplayname(mxid, "Out Of Your Element")
|
|
||||||
await api.profileSetAvatarUrl(mxid, avatarUrl)
|
|
||||||
console.log("✅ Matrix profile updated...")
|
|
||||||
|
|
||||||
console.log("Good to go. I hope you enjoy Out Of Your Element.")
|
|
||||||
process.exit()
|
|
||||||
})()
|
|
||||||
|
|
@ -12,6 +12,7 @@ const {reg} = require("../src/matrix/read-registration")
|
||||||
const passthrough = require("../src/passthrough")
|
const passthrough = require("../src/passthrough")
|
||||||
const db = new sqlite("ooye.db")
|
const db = new sqlite("ooye.db")
|
||||||
|
|
||||||
|
/** @type {import("heatsync").default} */ // @ts-ignore
|
||||||
const sync = new HeatSync()
|
const sync = new HeatSync()
|
||||||
|
|
||||||
Object.assign(passthrough, {sync, db})
|
Object.assign(passthrough, {sync, db})
|
||||||
|
|
@ -21,7 +22,12 @@ const DiscordClient = require("../src/d2m/discord-client")
|
||||||
const discord = new DiscordClient(reg.ooye.discord_token, "half")
|
const discord = new DiscordClient(reg.ooye.discord_token, "half")
|
||||||
passthrough.discord = discord
|
passthrough.discord = discord
|
||||||
|
|
||||||
const {as} = require("../src/matrix/appservice")
|
const app = createApp()
|
||||||
|
const router = createRouter()
|
||||||
|
app.use(router)
|
||||||
|
const server = createServer(toNodeListener(app))
|
||||||
|
server.listen(reg.socket || new URL(reg.url).port)
|
||||||
|
const as = Object.assign(new EventEmitter(), {app, router, server}) // @ts-ignore
|
||||||
passthrough.as = as
|
passthrough.as = as
|
||||||
|
|
||||||
const orm = sync.require("../src/db/orm")
|
const orm = sync.require("../src/db/orm")
|
||||||
|
|
@ -33,10 +39,4 @@ passthrough.select = orm.select
|
||||||
await discord.cloud.connect()
|
await discord.cloud.connect()
|
||||||
console.log("Discord gateway started")
|
console.log("Discord gateway started")
|
||||||
sync.require("../src/web/server")
|
sync.require("../src/web/server")
|
||||||
|
|
||||||
discord.cloud.once("ready", () => {
|
|
||||||
as.listen()
|
|
||||||
})
|
|
||||||
|
|
||||||
require("../src/stdin")
|
|
||||||
})()
|
})()
|
||||||
|
|
|
||||||
|
|
@ -1,65 +0,0 @@
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const Ty = require("../src/types")
|
|
||||||
const fs = require("fs")
|
|
||||||
const domino = require("domino")
|
|
||||||
const repl = require("repl")
|
|
||||||
|
|
||||||
const pres = (() => {
|
|
||||||
const pres = []
|
|
||||||
for (const file of process.argv.slice(2)) {
|
|
||||||
const data = JSON.parse(fs.readFileSync(file, "utf8"))
|
|
||||||
/** @type {Ty.Event.Outer<{msgtype?: string}>[]} */
|
|
||||||
const events = data.messages
|
|
||||||
for (const event of events) {
|
|
||||||
if (event.type !== "m.room.message" || event.content.msgtype !== "m.text") continue
|
|
||||||
/** @type {Ty.Event.M_Room_Message} */ // @ts-ignore
|
|
||||||
const content = event.content
|
|
||||||
if (content.format !== "org.matrix.custom.html") continue
|
|
||||||
if (!content.formatted_body) continue
|
|
||||||
|
|
||||||
const document = domino.createDocument(content.formatted_body)
|
|
||||||
// @ts-ignore
|
|
||||||
for (const pre of document.querySelectorAll("pre").cache) {
|
|
||||||
const content = pre.textContent
|
|
||||||
if (content.length < 100) continue
|
|
||||||
pres.push(content)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return pres
|
|
||||||
})()
|
|
||||||
|
|
||||||
// @ts-ignore
|
|
||||||
global.gc()
|
|
||||||
|
|
||||||
/** @param {string} text */
|
|
||||||
function probablyFixedWidthIntended(text) {
|
|
||||||
// if internal spaces are used, seems like they want a fixed-width font
|
|
||||||
if (text.match(/[^ ] {3,}[^ ]/)) return true
|
|
||||||
// if characters from Unicode General_Category "Symbol, other" are used, seems like they're doing ascii art and they want a fixed-width font
|
|
||||||
if (text.match(/\p{So}/v)) return true
|
|
||||||
// check start of line indentation
|
|
||||||
let indents = new Set()
|
|
||||||
for (const line of text.trimEnd().split("\n")) {
|
|
||||||
indents.add(line.match(/^ */)?.[0].length || 0)
|
|
||||||
// if there are more than 3 different indents (counting 0) then it's code
|
|
||||||
if (indents.size >= 3) return true
|
|
||||||
}
|
|
||||||
// if everything is indented then it's code
|
|
||||||
if (!indents.has(0)) return true
|
|
||||||
// if there is a high proportion of symbols then it's code (this filter works remarkably well on its own)
|
|
||||||
if ([...text.matchAll(/[\\`~;+|<>%$@*&"'=(){}[\]_^]|\.[a-zA-Z]|[a-z][A-Z]/g)].length / text.length >= 0.04) return true
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
Object.assign(repl.start().context, {pres, probablyFixedWidthIntended})
|
|
||||||
|
|
||||||
/*
|
|
||||||
if it has a lot of symbols then it's code
|
|
||||||
if it has >=3 levels of indentation then it's code
|
|
||||||
if it is all indented then it's code
|
|
||||||
if it has many spaces in a row in the middle then it's ascii art
|
|
||||||
if it has many non-latin characters then it's language
|
|
||||||
-> except if they are ascii art characters e.g. ⣿⣿⡇⢸⣿⠃ then it's ascii art
|
|
||||||
*/
|
|
||||||
|
|
@ -21,11 +21,11 @@ async function addReaction(data) {
|
||||||
const user = data.member?.user
|
const user = data.member?.user
|
||||||
assert.ok(user && user.username)
|
assert.ok(user && user.username)
|
||||||
|
|
||||||
const parentID = select("event_message", "event_id", {message_id: data.message_id}, "ORDER BY reaction_part").pluck().get()
|
const parentID = select("event_message", "event_id", {message_id: data.message_id, reaction_part: 0}).pluck().get()
|
||||||
if (!parentID) return // Nothing can be done if the parent message was never bridged.
|
if (!parentID) return // Nothing can be done if the parent message was never bridged.
|
||||||
assert.equal(typeof parentID, "string")
|
assert.equal(typeof parentID, "string")
|
||||||
|
|
||||||
const key = await emojiToKey.emojiToKey(data.emoji, data.message_id)
|
const key = await emojiToKey.emojiToKey(data.emoji)
|
||||||
const shortcode = key.startsWith("mxc://") ? `:${data.emoji.name}:` : undefined
|
const shortcode = key.startsWith("mxc://") ? `:${data.emoji.name}:` : undefined
|
||||||
|
|
||||||
const roomID = await createRoom.ensureRoom(data.channel_id)
|
const roomID = await createRoom.ensureRoom(data.channel_id)
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
// @ts-check
|
// @ts-check
|
||||||
|
|
||||||
const assert = require("assert").strict
|
const assert = require("assert")
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
const passthrough = require("../../passthrough")
|
||||||
const {discord, sync, db, select} = passthrough
|
const {discord, sync, db, select} = passthrough
|
||||||
|
|
|
||||||
|
|
@ -6,21 +6,17 @@ const Ty = require("../../types")
|
||||||
const {reg} = require("../../matrix/read-registration")
|
const {reg} = require("../../matrix/read-registration")
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
const passthrough = require("../../passthrough")
|
||||||
const {discord, sync, db, select, from} = passthrough
|
const {discord, sync, db, select} = passthrough
|
||||||
/** @type {import("../../matrix/file")} */
|
/** @type {import("../../matrix/file")} */
|
||||||
const file = sync.require("../../matrix/file")
|
const file = sync.require("../../matrix/file")
|
||||||
/** @type {import("../../matrix/api")} */
|
/** @type {import("../../matrix/api")} */
|
||||||
const api = sync.require("../../matrix/api")
|
const api = sync.require("../../matrix/api")
|
||||||
/** @type {import("../../matrix/mreq")} */
|
|
||||||
const mreq = sync.require("../../matrix/mreq")
|
|
||||||
/** @type {import("../../matrix/kstate")} */
|
/** @type {import("../../matrix/kstate")} */
|
||||||
const ks = sync.require("../../matrix/kstate")
|
const ks = sync.require("../../matrix/kstate")
|
||||||
/** @type {import("../../discord/utils")} */
|
/** @type {import("../../discord/utils")} */
|
||||||
const dUtils = sync.require("../../discord/utils")
|
const utils = sync.require("../../discord/utils")
|
||||||
/** @type {import("../../matrix/utils")} */
|
/** @type {import("./create-space")}) */
|
||||||
const mUtils = sync.require("../../matrix/utils")
|
const createSpace = sync.require("./create-space") // watch out for the require loop
|
||||||
/** @type {import("./create-space")} */
|
|
||||||
const createSpace = sync.require("./create-space")
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* There are 3 levels of room privacy:
|
* There are 3 levels of room privacy:
|
||||||
|
|
@ -30,7 +26,7 @@ const createSpace = sync.require("./create-space")
|
||||||
*/
|
*/
|
||||||
const PRIVACY_ENUMS = {
|
const PRIVACY_ENUMS = {
|
||||||
PRESET: ["private_chat", "public_chat", "public_chat"],
|
PRESET: ["private_chat", "public_chat", "public_chat"],
|
||||||
VISIBILITY: ["private", "private", "private"],
|
VISIBILITY: ["private", "private", "public"],
|
||||||
SPACE_HISTORY_VISIBILITY: ["invited", "world_readable", "world_readable"], // copying from element client
|
SPACE_HISTORY_VISIBILITY: ["invited", "world_readable", "world_readable"], // copying from element client
|
||||||
ROOM_HISTORY_VISIBILITY: ["shared", "shared", "world_readable"], // any events sent after <value> are visible, but for world_readable anybody can read without even joining
|
ROOM_HISTORY_VISIBILITY: ["shared", "shared", "world_readable"], // any events sent after <value> are visible, but for world_readable anybody can read without even joining
|
||||||
GUEST_ACCESS: ["can_join", "forbidden", "forbidden"], // whether guests can join space if other conditions are met
|
GUEST_ACCESS: ["can_join", "forbidden", "forbidden"], // whether guests can join space if other conditions are met
|
||||||
|
|
@ -40,11 +36,29 @@ const PRIVACY_ENUMS = {
|
||||||
|
|
||||||
const DEFAULT_PRIVACY_LEVEL = 0
|
const DEFAULT_PRIVACY_LEVEL = 0
|
||||||
|
|
||||||
const READ_ONLY_ROOM_EVENTS_DEFAULT_POWER = 50
|
|
||||||
|
|
||||||
/** @type {Map<string, Promise<string>>} channel ID -> Promise<room ID> */
|
/** @type {Map<string, Promise<string>>} channel ID -> Promise<room ID> */
|
||||||
const inflightRoomCreate = new Map()
|
const inflightRoomCreate = new Map()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Async because it gets all room state from the homeserver.
|
||||||
|
* @param {string} roomID
|
||||||
|
*/
|
||||||
|
async function roomToKState(roomID) {
|
||||||
|
const root = await api.getAllState(roomID)
|
||||||
|
return ks.stateToKState(root)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} roomID
|
||||||
|
* @param {any} kstate
|
||||||
|
*/
|
||||||
|
async function applyKStateDiffToRoom(roomID, kstate) {
|
||||||
|
const events = await ks.kstateToState(kstate)
|
||||||
|
return Promise.all(events.map(({type, state_key, content}) =>
|
||||||
|
api.sendState(roomID, type, state_key, content)
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {{id: string, name: string, topic?: string?, type: number, parent_id?: string?}} channel
|
* @param {{id: string, name: string, topic?: string?, type: number, parent_id?: string?}} channel
|
||||||
* @param {{id: string}} guild
|
* @param {{id: string}} guild
|
||||||
|
|
@ -56,7 +70,6 @@ function convertNameAndTopic(channel, guild, customName) {
|
||||||
let channelPrefix =
|
let channelPrefix =
|
||||||
( parentChannel?.type === DiscordTypes.ChannelType.GuildForum ? ""
|
( parentChannel?.type === DiscordTypes.ChannelType.GuildForum ? ""
|
||||||
: channel.type === DiscordTypes.ChannelType.PublicThread ? "[⛓️] "
|
: channel.type === DiscordTypes.ChannelType.PublicThread ? "[⛓️] "
|
||||||
: channel.type === DiscordTypes.ChannelType.AnnouncementThread ? "[⛓️] "
|
|
||||||
: channel.type === DiscordTypes.ChannelType.PrivateThread ? "[🔒⛓️] "
|
: channel.type === DiscordTypes.ChannelType.PrivateThread ? "[🔒⛓️] "
|
||||||
: channel.type === DiscordTypes.ChannelType.GuildVoice ? "[🔊] "
|
: channel.type === DiscordTypes.ChannelType.GuildVoice ? "[🔊] "
|
||||||
: "")
|
: "")
|
||||||
|
|
@ -77,25 +90,32 @@ function convertNameAndTopic(channel, guild, customName) {
|
||||||
* Async because it may create the guild and/or upload the guild icon to mxc.
|
* Async because it may create the guild and/or upload the guild icon to mxc.
|
||||||
* @param {DiscordTypes.APIGuildTextChannel | DiscordTypes.APIThreadChannel} channel
|
* @param {DiscordTypes.APIGuildTextChannel | DiscordTypes.APIThreadChannel} channel
|
||||||
* @param {DiscordTypes.APIGuild} guild
|
* @param {DiscordTypes.APIGuild} guild
|
||||||
* @param {{api: {getStateEvent: typeof api.getStateEvent, getStateEventOuter: typeof api.getStateEventOuter}}} di simple-as-nails dependency injection for the matrix API
|
* @param {{api: {getStateEvent: typeof api.getStateEvent}}} di simple-as-nails dependency injection for the matrix API
|
||||||
*/
|
*/
|
||||||
async function channelToKState(channel, guild, di) {
|
async function channelToKState(channel, guild, di) {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const parentChannel = discord.channels.get(channel.parent_id)
|
const parentChannel = discord.channels.get(channel.parent_id)
|
||||||
|
|
||||||
/** Used for membership/permission checks. */
|
/** Used for membership/permission checks. */
|
||||||
const guildSpaceID = await createSpace.ensureSpace(guild)
|
let guildSpaceID
|
||||||
/** Used as the literal parent on Matrix, for categorisation. Will be the same as `guildSpaceID` unless it's a forum channel's thread, in which case a different space is used to group those threads. */
|
/** Used as the literal parent on Matrix, for categorisation. Will be the same as `guildSpaceID` unless it's a forum channel's thread, in which case a different space is used to group those threads. */
|
||||||
let parentSpaceID = guildSpaceID
|
let parentSpaceID
|
||||||
if (parentChannel?.type === DiscordTypes.ChannelType.GuildForum) {
|
let privacyLevel
|
||||||
|
if (parentChannel?.type === DiscordTypes.ChannelType.GuildForum) { // it's a forum channel's thread, so use a different space to group those threads
|
||||||
|
guildSpaceID = await createSpace.ensureSpace(guild)
|
||||||
parentSpaceID = await ensureRoom(channel.parent_id)
|
parentSpaceID = await ensureRoom(channel.parent_id)
|
||||||
assert(typeof parentSpaceID === "string")
|
privacyLevel = select("guild_space", "privacy_level", {space_id: guildSpaceID}).pluck().get()
|
||||||
|
} else { // otherwise use the guild's space like usual
|
||||||
|
parentSpaceID = await createSpace.ensureSpace(guild)
|
||||||
|
guildSpaceID = parentSpaceID
|
||||||
|
privacyLevel = select("guild_space", "privacy_level", {space_id: parentSpaceID}).pluck().get()
|
||||||
}
|
}
|
||||||
|
assert(typeof parentSpaceID === "string")
|
||||||
|
assert(typeof guildSpaceID === "string")
|
||||||
|
assert(typeof privacyLevel === "number")
|
||||||
|
|
||||||
const channelRow = select("channel_room", ["nick", "custom_avatar", "custom_topic"], {channel_id: channel.id}).get()
|
const row = select("channel_room", ["nick", "custom_avatar"], {channel_id: channel.id}).get()
|
||||||
const customName = channelRow?.nick
|
const customName = row?.nick
|
||||||
const customAvatar = channelRow?.custom_avatar
|
const customAvatar = row?.custom_avatar
|
||||||
const hasCustomTopic = channelRow?.custom_topic
|
|
||||||
const [convertedName, convertedTopic] = convertNameAndTopic(channel, guild, customName)
|
const [convertedName, convertedTopic] = convertNameAndTopic(channel, guild, customName)
|
||||||
|
|
||||||
const avatarEventContent = {}
|
const avatarEventContent = {}
|
||||||
|
|
@ -105,8 +125,6 @@ async function channelToKState(channel, guild, di) {
|
||||||
avatarEventContent.url = {$url: file.guildIcon(guild)}
|
avatarEventContent.url = {$url: file.guildIcon(guild)}
|
||||||
}
|
}
|
||||||
|
|
||||||
const privacyLevel = select("guild_space", "privacy_level", {guild_id: guild.id}).pluck().get()
|
|
||||||
assert(privacyLevel != null) // already ensured the space exists
|
|
||||||
let history_visibility = PRIVACY_ENUMS.ROOM_HISTORY_VISIBILITY[privacyLevel]
|
let history_visibility = PRIVACY_ENUMS.ROOM_HISTORY_VISIBILITY[privacyLevel]
|
||||||
if (channel["thread_metadata"]) history_visibility = "world_readable"
|
if (channel["thread_metadata"]) history_visibility = "world_readable"
|
||||||
|
|
||||||
|
|
@ -122,31 +140,17 @@ async function channelToKState(channel, guild, di) {
|
||||||
join_rules = {join_rule: PRIVACY_ENUMS.ROOM_JOIN_RULES[privacyLevel]}
|
join_rules = {join_rule: PRIVACY_ENUMS.ROOM_JOIN_RULES[privacyLevel]}
|
||||||
}
|
}
|
||||||
|
|
||||||
const everyonePermissions = dUtils.getPermissions(guild.id, [], guild.roles, undefined, channel.permission_overwrites)
|
const everyonePermissions = utils.getPermissions([], guild.roles, undefined, channel.permission_overwrites)
|
||||||
const everyoneCanSend = dUtils.hasPermission(everyonePermissions, DiscordTypes.PermissionFlagsBits.SendMessages)
|
const everyoneCanMentionEveryone = utils.hasAllPermissions(everyonePermissions, ["MentionEveryone"])
|
||||||
const everyoneCanMentionEveryone = dUtils.hasPermission(everyonePermissions, DiscordTypes.PermissionFlagsBits.MentionEveryone)
|
|
||||||
|
|
||||||
const pollStartPowerLevel = {}
|
|
||||||
const everyoneCanCreatePolls = dUtils.hasPermission(everyonePermissions, DiscordTypes.PermissionFlagsBits.SendPolls)
|
|
||||||
if (everyoneCanSend && !everyoneCanCreatePolls) pollStartPowerLevel["org.matrix.msc3381.poll.start"] = 10
|
|
||||||
|
|
||||||
const spacePowerDetails = await mUtils.getEffectivePower(guildSpaceID, [], di.api)
|
|
||||||
spacePowerDetails.powerLevels.users ??= {}
|
|
||||||
const spaceCreatorsAndFounders = spacePowerDetails.allCreators
|
|
||||||
.concat(Object.entries(spacePowerDetails.powerLevels.users).filter(([, power]) => power >= spacePowerDetails.tombstone).map(([mxid]) => mxid))
|
|
||||||
|
|
||||||
const globalAdmins = select("member_power", ["mxid", "power_level"], {room_id: "*"}).all()
|
const globalAdmins = select("member_power", ["mxid", "power_level"], {room_id: "*"}).all()
|
||||||
const globalAdminPower = globalAdmins.reduce((a, c) => (a[c.mxid] = c.power_level, a), {})
|
const globalAdminPower = globalAdmins.reduce((a, c) => (a[c.mxid] = c.power_level, a), {})
|
||||||
|
|
||||||
const additionalCreators = select("member_power", "mxid", {room_id: "*"}, "AND power_level > 100").pluck().all().concat(spaceCreatorsAndFounders)
|
/** @type {Ty.Event.M_Power_Levels} */
|
||||||
const creationContent = {}
|
const spacePowerEvent = await di.api.getStateEvent(guildSpaceID, "m.room.power_levels", "")
|
||||||
creationContent.additional_creators = additionalCreators
|
const spacePower = spacePowerEvent.users
|
||||||
|
|
||||||
if (channel.type === DiscordTypes.ChannelType.GuildForum) creationContent.type = "m.space"
|
|
||||||
|
|
||||||
/** @type {any} */
|
|
||||||
const channelKState = {
|
const channelKState = {
|
||||||
"m.room.create/": creationContent,
|
|
||||||
"m.room.name/": {name: convertedName},
|
"m.room.name/": {name: convertedName},
|
||||||
"m.room.topic/": {topic: convertedTopic},
|
"m.room.topic/": {topic: convertedTopic},
|
||||||
"m.room.avatar/": avatarEventContent,
|
"m.room.avatar/": avatarEventContent,
|
||||||
|
|
@ -158,21 +162,17 @@ async function channelToKState(channel, guild, di) {
|
||||||
},
|
},
|
||||||
/** @type {{join_rule: string, [x: string]: any}} */
|
/** @type {{join_rule: string, [x: string]: any}} */
|
||||||
"m.room.join_rules/": join_rules,
|
"m.room.join_rules/": join_rules,
|
||||||
/** @type {Ty.Event.M_Power_Levels} */
|
|
||||||
"m.room.power_levels/": {
|
"m.room.power_levels/": {
|
||||||
events_default: everyoneCanSend ? 0 : READ_ONLY_ROOM_EVENTS_DEFAULT_POWER,
|
|
||||||
events: {
|
|
||||||
"m.reaction": 0,
|
|
||||||
"m.room.redaction": 0, // only affects redactions of own events, required to be able to un-react
|
|
||||||
...pollStartPowerLevel
|
|
||||||
},
|
|
||||||
notifications: {
|
notifications: {
|
||||||
room: everyoneCanMentionEveryone ? 0 : 20
|
room: everyoneCanMentionEveryone ? 0 : 20
|
||||||
},
|
},
|
||||||
users: {...spacePowerDetails.powerLevels.users, ...globalAdminPower}
|
users: {...spacePower, ...globalAdminPower}
|
||||||
|
},
|
||||||
|
"chat.schildi.hide_ui/read_receipts": {
|
||||||
|
hidden: true
|
||||||
},
|
},
|
||||||
[`uk.half-shot.bridge/moe.cadence.ooye://discord/${guild.id}/${channel.id}`]: {
|
[`uk.half-shot.bridge/moe.cadence.ooye://discord/${guild.id}/${channel.id}`]: {
|
||||||
bridgebot: mUtils.bot,
|
bridgebot: `@${reg.sender_localpart}:${reg.ooye.server_name}`,
|
||||||
protocol: {
|
protocol: {
|
||||||
id: "discord",
|
id: "discord",
|
||||||
displayname: "Discord"
|
displayname: "Discord"
|
||||||
|
|
@ -180,7 +180,7 @@ async function channelToKState(channel, guild, di) {
|
||||||
network: {
|
network: {
|
||||||
id: guild.id,
|
id: guild.id,
|
||||||
displayname: guild.name,
|
displayname: guild.name,
|
||||||
avatar_url: {$url: file.guildIcon(guild)}
|
avatar_url: await file.uploadDiscordFileToMxc(file.guildIcon(guild))
|
||||||
},
|
},
|
||||||
channel: {
|
channel: {
|
||||||
id: channel.id,
|
id: channel.id,
|
||||||
|
|
@ -190,23 +190,13 @@ async function channelToKState(channel, guild, di) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Don't overwrite room topic if the topic has been customised
|
|
||||||
if (hasCustomTopic) delete channelKState["m.room.topic/"]
|
|
||||||
|
|
||||||
// Don't add a space parent if it's self service
|
|
||||||
// (The person setting up self-service has already put it in their preferred space to be able to get this far.)
|
|
||||||
const autocreate = select("guild_active", "autocreate", {guild_id: guild.id}).pluck().get()
|
|
||||||
if (autocreate === 0 && ![DiscordTypes.ChannelType.PrivateThread, DiscordTypes.ChannelType.PublicThread, DiscordTypes.ChannelType.AnnouncementThread].includes(channel.type)) {
|
|
||||||
delete channelKState[`m.space.parent/${parentSpaceID}`]
|
|
||||||
}
|
|
||||||
|
|
||||||
return {spaceID: parentSpaceID, privacyLevel, channelKState}
|
return {spaceID: parentSpaceID, privacyLevel, channelKState}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a bridge room, store the relationship in the database, and add it to the guild's space.
|
* Create a bridge room, store the relationship in the database, and add it to the guild's space.
|
||||||
* @param {DiscordTypes.APIGuildTextChannel} channel
|
* @param {DiscordTypes.APIGuildTextChannel} channel
|
||||||
* @param {DiscordTypes.APIGuild} guild
|
* @param guild
|
||||||
* @param {string} spaceID
|
* @param {string} spaceID
|
||||||
* @param {any} kstate
|
* @param {any} kstate
|
||||||
* @param {number} privacyLevel
|
* @param {number} privacyLevel
|
||||||
|
|
@ -216,6 +206,9 @@ async function createRoom(channel, guild, spaceID, kstate, privacyLevel) {
|
||||||
let threadParent = null
|
let threadParent = null
|
||||||
if (channel.type === DiscordTypes.ChannelType.PublicThread) threadParent = channel.parent_id
|
if (channel.type === DiscordTypes.ChannelType.PublicThread) threadParent = channel.parent_id
|
||||||
|
|
||||||
|
let spaceCreationContent = {}
|
||||||
|
if (channel.type === DiscordTypes.ChannelType.GuildForum) spaceCreationContent = {creation_content: {type: "m.space"}}
|
||||||
|
|
||||||
// Name and topic can be done earlier in room creation rather than in initial_state
|
// Name and topic can be done earlier in room creation rather than in initial_state
|
||||||
// https://spec.matrix.org/latest/client-server-api/#creation
|
// https://spec.matrix.org/latest/client-server-api/#creation
|
||||||
const name = kstate["m.room.name/"].name
|
const name = kstate["m.room.name/"].name
|
||||||
|
|
@ -225,7 +218,7 @@ async function createRoom(channel, guild, spaceID, kstate, privacyLevel) {
|
||||||
delete kstate["m.room.topic/"]
|
delete kstate["m.room.topic/"]
|
||||||
assert(topic)
|
assert(topic)
|
||||||
|
|
||||||
const roomCreate = await postApplyPowerLevels(kstate, async kstate => {
|
const roomID = await postApplyPowerLevels(kstate, async kstate => {
|
||||||
const roomID = await api.createRoom({
|
const roomID = await api.createRoom({
|
||||||
name,
|
name,
|
||||||
topic,
|
topic,
|
||||||
|
|
@ -233,23 +226,16 @@ async function createRoom(channel, guild, spaceID, kstate, privacyLevel) {
|
||||||
visibility: PRIVACY_ENUMS.VISIBILITY[privacyLevel],
|
visibility: PRIVACY_ENUMS.VISIBILITY[privacyLevel],
|
||||||
invite: [],
|
invite: [],
|
||||||
initial_state: await ks.kstateToState(kstate),
|
initial_state: await ks.kstateToState(kstate),
|
||||||
creation_content: ks.kstateToCreationContent(kstate)
|
...spaceCreationContent
|
||||||
})
|
})
|
||||||
|
|
||||||
/** @type {Ty.Event.StateOuter<Ty.Event.M_Room_Create>} */
|
db.prepare("INSERT INTO channel_room (channel_id, room_id, name, nick, thread_parent) VALUES (?, ?, ?, NULL, ?)").run(channel.id, roomID, channel.name, threadParent)
|
||||||
const roomCreate = await api.getStateEventOuter(roomID, "m.room.create", "")
|
|
||||||
|
|
||||||
db.transaction(() => {
|
return roomID
|
||||||
db.prepare("INSERT INTO channel_room (channel_id, room_id, name, nick, thread_parent, guild_id) VALUES (?, ?, ?, NULL, ?, ?)").run(channel.id, roomID, channel.name, threadParent, guild.id)
|
|
||||||
db.prepare("INSERT INTO historical_channel_room (reference_channel_id, room_id, upgraded_timestamp) VALUES (?, ?, 0)").run(channel.id, roomID)
|
|
||||||
})()
|
|
||||||
|
|
||||||
return roomCreate
|
|
||||||
})
|
})
|
||||||
const roomID = roomCreate.room_id
|
|
||||||
|
|
||||||
// Put the newly created child into the space
|
// Put the newly created child into the space, no need to await this
|
||||||
await _syncSpaceMember(channel, spaceID, roomID, guild.id)
|
_syncSpaceMember(channel, spaceID, roomID)
|
||||||
|
|
||||||
return roomID
|
return roomID
|
||||||
}
|
}
|
||||||
|
|
@ -261,30 +247,25 @@ async function createRoom(channel, guild, spaceID, kstate, privacyLevel) {
|
||||||
* https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/room.py#L1170-L1210
|
* https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/room.py#L1170-L1210
|
||||||
* https://github.com/matrix-org/matrix-spec/issues/492
|
* https://github.com/matrix-org/matrix-spec/issues/492
|
||||||
* @param {any} kstate
|
* @param {any} kstate
|
||||||
* @param {(_: any) => Promise<Ty.Event.StateOuter<Ty.Event.M_Room_Create>>} callback must return room ID and room version
|
* @param {(_: any) => Promise<string>} callback must return room ID
|
||||||
* @returns {Promise<Ty.Event.StateOuter<Ty.Event.M_Room_Create>>} room ID
|
* @returns {Promise<string>} room ID
|
||||||
*/
|
*/
|
||||||
async function postApplyPowerLevels(kstate, callback) {
|
async function postApplyPowerLevels(kstate, callback) {
|
||||||
const powerLevelContent = kstate["m.room.power_levels/"]
|
const powerLevelContent = kstate["m.room.power_levels/"]
|
||||||
const kstateWithoutPowerLevels = {...kstate}
|
const kstateWithoutPowerLevels = {...kstate}
|
||||||
delete kstateWithoutPowerLevels["m.room.power_levels/"]
|
delete kstateWithoutPowerLevels["m.room.power_levels/"]
|
||||||
|
|
||||||
const roomCreate = await callback(kstateWithoutPowerLevels)
|
/** @type {string} */
|
||||||
const roomID = roomCreate.room_id
|
const roomID = await callback(kstateWithoutPowerLevels)
|
||||||
|
|
||||||
// Now *really* apply the power level overrides on top of what Synapse *really* set
|
// Now *really* apply the power level overrides on top of what Synapse *really* set
|
||||||
if (powerLevelContent) {
|
if (powerLevelContent) {
|
||||||
mUtils.removeCreatorsFromPowerLevels(roomCreate, powerLevelContent)
|
const newRoomKState = await roomToKState(roomID)
|
||||||
|
const newRoomPowerLevelsDiff = ks.diffKState(newRoomKState, {"m.room.power_levels/": powerLevelContent})
|
||||||
const originalPowerLevels = await api.getStateEvent(roomID, "m.room.power_levels", "")
|
await applyKStateDiffToRoom(roomID, newRoomPowerLevelsDiff)
|
||||||
const powerLevelsDiff = ks.diffKState(
|
|
||||||
{"m.room.power_levels/": originalPowerLevels, "m.room.create/": roomCreate.content, "m.room.create/outer": roomCreate},
|
|
||||||
{"m.room.power_levels/": powerLevelContent}
|
|
||||||
)
|
|
||||||
await ks.applyKStateDiffToRoom(roomID, powerLevelsDiff)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return roomCreate
|
return roomID
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -298,61 +279,6 @@ function channelToGuild(channel) {
|
||||||
return guild
|
return guild
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* This function handles whether it's allowed to bridge messages in this channel, and if so, where to.
|
|
||||||
* This has to account for whether self-service is enabled for the guild or not.
|
|
||||||
* This also has to account for different channel types, like forum channels (which need the
|
|
||||||
* parent forum to already exist, and ignore the self-service setting), or thread channels (which
|
|
||||||
* need the parent channel to already exist, and ignore the self-service setting).
|
|
||||||
* @param {DiscordTypes.APIGuildTextChannel | DiscordTypes.APIThreadChannel} channel text channel or thread
|
|
||||||
* @param {string} guildID
|
|
||||||
* @returns obj if bridged; 1 if autocreatable; null/undefined if guild is not bridged; 0 if self-service and not autocreatable thread
|
|
||||||
*/
|
|
||||||
function existsOrAutocreatable(channel, guildID) {
|
|
||||||
// 1. If the channel is already linked somewhere, it's always okay to bridge to that destination, no matter what. Yippee!
|
|
||||||
const existing = select("channel_room", ["room_id", "thread_parent"], {channel_id: channel.id}).get()
|
|
||||||
if (existing) return existing
|
|
||||||
|
|
||||||
// 2. If the guild is an autocreate guild, it's always okay to bridge to that destination, and
|
|
||||||
// we'll need to create any dependent resources recursively.
|
|
||||||
const autocreate = select("guild_active", "autocreate", {guild_id: guildID}).pluck().get()
|
|
||||||
if (autocreate === 1) return autocreate
|
|
||||||
|
|
||||||
// 3. If the guild is not approved for bridging yet, we can't bridge there.
|
|
||||||
// They need to decide one way or another whether it's self-service before we can continue.
|
|
||||||
if (autocreate == null) return autocreate
|
|
||||||
|
|
||||||
// 4. If we got here, the guild is in self-service mode.
|
|
||||||
// New channels won't be able to create new rooms. But forum threads or channel threads could be fine.
|
|
||||||
if ([DiscordTypes.ChannelType.PublicThread, DiscordTypes.ChannelType.PrivateThread, DiscordTypes.ChannelType.AnnouncementThread].includes(channel.type)) {
|
|
||||||
// In self-service mode, threads rely on the parent resource already existing.
|
|
||||||
/** @type {DiscordTypes.APIGuildTextChannel} */ // @ts-ignore
|
|
||||||
const parent = discord.channels.get(channel.parent_id)
|
|
||||||
assert(parent)
|
|
||||||
const parentExisting = existsOrAutocreatable(parent, guildID)
|
|
||||||
if (parentExisting) return 1 // Autocreatable
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. If we got here, the guild is in self-service mode and the channel is truly not bridged.
|
|
||||||
return autocreate
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {DiscordTypes.APIGuildTextChannel | DiscordTypes.APIThreadChannel} channel text channel or thread
|
|
||||||
* @param {string} guildID
|
|
||||||
* @returns obj if bridged; 1 if autocreatable. (throws if not autocreatable)
|
|
||||||
*/
|
|
||||||
function assertExistsOrAutocreatable(channel, guildID) {
|
|
||||||
const existing = existsOrAutocreatable(channel, guildID)
|
|
||||||
if (existing === 0) {
|
|
||||||
throw new Error(`Guild ${guildID} is self-service, so won't create a Matrix room for channel ${channel.id}`)
|
|
||||||
}
|
|
||||||
if (!existing) {
|
|
||||||
throw new Error(`Guild ${guildID} is not bridged, so won't create a Matrix room for channel ${channel.id}`)
|
|
||||||
}
|
|
||||||
return existing
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Ensure flow:
|
Ensure flow:
|
||||||
1. Get IDs
|
1. Get IDs
|
||||||
|
|
@ -371,13 +297,12 @@ function assertExistsOrAutocreatable(channel, guildID) {
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create room and/or sync room data. Please check that a channel_room entry exists or autocreate = 1 before calling this.
|
|
||||||
* @param {string} channelID
|
* @param {string} channelID
|
||||||
* @param {boolean} shouldActuallySync false if just need to ensure room exists (which is a quick database check), true if also want to sync room data when it does exist (slow)
|
* @param {boolean} shouldActuallySync false if just need to ensure room exists (which is a quick database check), true if also want to sync room data when it does exist (slow)
|
||||||
* @returns {Promise<string>} room ID
|
* @returns {Promise<string>} room ID
|
||||||
*/
|
*/
|
||||||
async function _syncRoom(channelID, shouldActuallySync) {
|
async function _syncRoom(channelID, shouldActuallySync) {
|
||||||
/** @ts-ignore @type {DiscordTypes.APIGuildTextChannel} */
|
/** @ts-ignore @type {DiscordTypes.APIGuildChannel} */
|
||||||
const channel = discord.channels.get(channelID)
|
const channel = discord.channels.get(channelID)
|
||||||
assert.ok(channel)
|
assert.ok(channel)
|
||||||
const guild = channelToGuild(channel)
|
const guild = channelToGuild(channel)
|
||||||
|
|
@ -386,9 +311,9 @@ async function _syncRoom(channelID, shouldActuallySync) {
|
||||||
await inflightRoomCreate.get(channelID) // just waiting, and then doing a new db query afterwards, is the simplest way of doing it
|
await inflightRoomCreate.get(channelID) // just waiting, and then doing a new db query afterwards, is the simplest way of doing it
|
||||||
}
|
}
|
||||||
|
|
||||||
const existing = assertExistsOrAutocreatable(channel, guild.id)
|
const existing = select("channel_room", ["room_id", "thread_parent"], {channel_id: channelID}).get()
|
||||||
|
|
||||||
if (existing === 1) {
|
if (!existing) {
|
||||||
const creation = (async () => {
|
const creation = (async () => {
|
||||||
const {spaceID, privacyLevel, channelKState} = await channelToKState(channel, guild, {api})
|
const {spaceID, privacyLevel, channelKState} = await channelToKState(channel, guild, {api})
|
||||||
const roomID = await createRoom(channel, guild, spaceID, channelKState, privacyLevel)
|
const roomID = await createRoom(channel, guild, spaceID, channelKState, privacyLevel)
|
||||||
|
|
@ -408,117 +333,76 @@ async function _syncRoom(channelID, shouldActuallySync) {
|
||||||
console.log(`[room sync] to matrix: ${channel.name}`)
|
console.log(`[room sync] to matrix: ${channel.name}`)
|
||||||
|
|
||||||
const {spaceID, channelKState} = await channelToKState(channel, guild, {api}) // calling this in both branches because we don't want to calculate this if not syncing
|
const {spaceID, channelKState} = await channelToKState(channel, guild, {api}) // calling this in both branches because we don't want to calculate this if not syncing
|
||||||
await ks.kstateUploadMxc(channelKState) // pre-upload icons before diffing
|
|
||||||
|
|
||||||
// sync channel state to room
|
// sync channel state to room
|
||||||
const roomKState = await ks.roomToKState(roomID)
|
const roomKState = await roomToKState(roomID)
|
||||||
if (!mUtils.roomHasAtLeastVersion(roomKState["m.room.create/"].room_version, 9)) {
|
if (+roomKState["m.room.create/"].room_version <= 8) {
|
||||||
// join_rule `restricted` is not available in room version < 8 and not working properly in version == 8, so require version 9
|
// join_rule `restricted` is not available in room version < 8 and not working properly in version == 8
|
||||||
// read more: https://spec.matrix.org/v1.8/rooms/v9/
|
// read more: https://spec.matrix.org/v1.8/rooms/v9/
|
||||||
// we have to use `public` instead, otherwise the room will be unjoinable.
|
// we have to use `public` instead, otherwise the room will be unjoinable.
|
||||||
channelKState["m.room.join_rules/"] = {join_rule: "public"}
|
channelKState["m.room.join_rules/"] = {join_rule: "public"}
|
||||||
}
|
}
|
||||||
const roomDiff = ks.diffKState(roomKState, channelKState)
|
const roomDiff = ks.diffKState(roomKState, channelKState)
|
||||||
const roomApply = ks.applyKStateDiffToRoom(roomID, roomDiff)
|
const roomApply = applyKStateDiffToRoom(roomID, roomDiff)
|
||||||
db.prepare("UPDATE channel_room SET name = ? WHERE channel_id = ?").run(channel.name, channel.id)
|
db.prepare("UPDATE channel_room SET name = ? WHERE room_id = ?").run(channel.name, roomID)
|
||||||
|
|
||||||
// sync room as space member
|
// sync room as space member
|
||||||
const spaceApply = _syncSpaceMember(channel, spaceID, roomID, guild.id)
|
const spaceApply = _syncSpaceMember(channel, spaceID, roomID)
|
||||||
await Promise.all([roomApply, spaceApply])
|
await Promise.all([roomApply, spaceApply])
|
||||||
|
|
||||||
return roomID
|
return roomID
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Ensures the room exists. If it doesn't, creates the room with an accurate initial state. Please check that a channel_room entry exists or guild autocreate = 1 before calling this. */
|
/** Ensures the room exists. If it doesn't, creates the room with an accurate initial state. */
|
||||||
function ensureRoom(channelID) {
|
function ensureRoom(channelID) {
|
||||||
return _syncRoom(channelID, false)
|
return _syncRoom(channelID, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Actually syncs. Gets all room state from the homeserver in order to diff, and uploads the icon to mxc if it has changed. Please check that a channel_room entry exists or guild autocreate = 1 before calling this. */
|
/** Actually syncs. Gets all room state from the homeserver in order to diff, and uploads the icon to mxc if it has changed. */
|
||||||
function syncRoom(channelID) {
|
function syncRoom(channelID) {
|
||||||
return _syncRoom(channelID, true)
|
return _syncRoom(channelID, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function _unbridgeRoom(channelID) {
|
||||||
|
/** @ts-ignore @type {DiscordTypes.APIGuildChannel} */
|
||||||
|
const channel = discord.channels.get(channelID)
|
||||||
|
assert.ok(channel)
|
||||||
|
assert.ok(channel.guild_id)
|
||||||
|
return unbridgeDeletedChannel(channel, channel.guild_id)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {{id: string, topic?: string?}} channel channel-ish (just needs an id, topic is optional)
|
* @param {{id: string, topic?: string?}} channel
|
||||||
* @param {string} guildID
|
* @param {string} guildID
|
||||||
*/
|
*/
|
||||||
async function unbridgeChannel(channel, guildID) {
|
async function unbridgeDeletedChannel(channel, guildID) {
|
||||||
const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get()
|
const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get()
|
||||||
assert.ok(roomID)
|
assert.ok(roomID)
|
||||||
const row = from("guild_space").join("guild_active", "guild_id").select("space_id", "autocreate").where({guild_id: guildID}).get()
|
const spaceID = select("guild_space", "space_id", {guild_id: guildID}).pluck().get()
|
||||||
assert.ok(row)
|
assert.ok(spaceID)
|
||||||
|
|
||||||
let botInRoom = true
|
// remove room from being a space member
|
||||||
|
await api.sendState(roomID, "m.space.parent", spaceID, {})
|
||||||
|
await api.sendState(spaceID, "m.space.child", roomID, {})
|
||||||
|
|
||||||
// remove declaration that the room is bridged
|
// remove declaration that the room is bridged
|
||||||
try {
|
|
||||||
await api.sendState(roomID, "uk.half-shot.bridge", `moe.cadence.ooye://discord/${guildID}/${channel.id}`, {})
|
await api.sendState(roomID, "uk.half-shot.bridge", `moe.cadence.ooye://discord/${guildID}/${channel.id}`, {})
|
||||||
} catch (e) {
|
if ("topic" in channel) {
|
||||||
if (String(e).includes("not in room")) {
|
|
||||||
botInRoom = false
|
|
||||||
} else {
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (botInRoom && "topic" in channel) {
|
|
||||||
// previously the Matrix topic would say the channel ID. we should remove that
|
// previously the Matrix topic would say the channel ID. we should remove that
|
||||||
await api.sendState(roomID, "m.room.topic", "", {topic: channel.topic || ""})
|
await api.sendState(roomID, "m.room.topic", "", {topic: channel.topic || ""})
|
||||||
}
|
}
|
||||||
|
|
||||||
// delete webhook on discord
|
|
||||||
const webhook = select("webhook", ["webhook_id", "webhook_token"], {channel_id: channel.id}).get()
|
|
||||||
if (webhook) {
|
|
||||||
await discord.snow.webhook.deleteWebhook(webhook.webhook_id, webhook.webhook_token).catch(() => {})
|
|
||||||
db.prepare("DELETE FROM webhook WHERE channel_id = ?").run(channel.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// delete room from database
|
|
||||||
db.prepare("DELETE FROM member_cache WHERE room_id = ?").run(roomID)
|
|
||||||
db.prepare("DELETE FROM channel_room WHERE room_id = ? AND channel_id = ?").run(roomID, channel.id) // cascades to most other tables, like messages and historical rooms
|
|
||||||
|
|
||||||
if (!botInRoom) return
|
|
||||||
|
|
||||||
// demote discord sim admins in room
|
|
||||||
const {powerLevels, allCreators} = await mUtils.getEffectivePower(roomID, [], api)
|
|
||||||
const powerLevelsUsers = (powerLevels.users ||= {})
|
|
||||||
for (const mxid of Object.keys(powerLevelsUsers)) {
|
|
||||||
if (powerLevelsUsers[mxid] >= (powerLevels.state_default ?? 50) && !allCreators.includes(mxid) && mUtils.eventSenderIsFromDiscord(mxid) && mxid !== mUtils.bot) {
|
|
||||||
delete powerLevelsUsers[mxid]
|
|
||||||
await api.sendState(roomID, "m.room.power_levels", "", powerLevels, mxid) // done individually because each user must demote themselves
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// send a notification in the room
|
// send a notification in the room
|
||||||
await api.sendEvent(roomID, "m.room.message", {
|
await api.sendEvent(roomID, "m.room.message", {
|
||||||
msgtype: "m.notice",
|
msgtype: "m.notice",
|
||||||
body: "⚠️ This room was removed from the bridge."
|
body: "⚠️ This room was removed from the bridge."
|
||||||
})
|
})
|
||||||
|
|
||||||
// if it is an easy mode room, clean up the room from the managed space and make it clear it's not being bridged
|
|
||||||
// (don't do this for self-service rooms, because they might continue to be used on Matrix or linked somewhere else later)
|
|
||||||
if (row.autocreate === 1) {
|
|
||||||
// remove room from being a space member
|
|
||||||
await api.sendState(roomID, "m.space.parent", row.space_id, {})
|
|
||||||
await api.sendState(row.space_id, "m.space.child", roomID, {})
|
|
||||||
}
|
|
||||||
|
|
||||||
// if it is a self-service room, remove sim members
|
|
||||||
// (the room can be used with less clutter and the member list makes sense if it's bridged somewhere else)
|
|
||||||
if (row.autocreate === 0) {
|
|
||||||
// remove sim members
|
|
||||||
const members = db.prepare("SELECT mxid FROM sim_member WHERE room_id = ? AND mxid <> ?").pluck().all(roomID, mUtils.bot)
|
|
||||||
const preparedDelete = db.prepare("DELETE FROM sim_member WHERE room_id = ? AND mxid = ?")
|
|
||||||
for (const mxid of members) {
|
|
||||||
await api.leaveRoom(roomID, mxid)
|
|
||||||
preparedDelete.run(roomID, mxid)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// leave room
|
// leave room
|
||||||
await mUtils.setUserPower(roomID, mUtils.bot, 0, api)
|
|
||||||
await api.leaveRoom(roomID)
|
await api.leaveRoom(roomID)
|
||||||
|
|
||||||
|
// delete room from database
|
||||||
|
db.prepare("DELETE FROM channel_room WHERE room_id = ? AND channel_id = ?").run(roomID, channel.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -526,25 +410,14 @@ async function unbridgeChannel(channel, guildID) {
|
||||||
* @param {DiscordTypes.APIGuildTextChannel} channel
|
* @param {DiscordTypes.APIGuildTextChannel} channel
|
||||||
* @param {string} spaceID
|
* @param {string} spaceID
|
||||||
* @param {string} roomID
|
* @param {string} roomID
|
||||||
* @param {string} guild_id
|
|
||||||
* @returns {Promise<string[]>}
|
* @returns {Promise<string[]>}
|
||||||
*/
|
*/
|
||||||
async function _syncSpaceMember(channel, spaceID, roomID, guild_id) {
|
async function _syncSpaceMember(channel, spaceID, roomID) {
|
||||||
// If space is self-service then only permit changes to space parenting for threads
|
const spaceKState = await roomToKState(spaceID)
|
||||||
// (The person setting up self-service has already put it in their preferred space to be able to get this far.)
|
|
||||||
const autocreate = select("guild_active", "autocreate", {guild_id}).pluck().get()
|
|
||||||
if (autocreate === 0 && ![DiscordTypes.ChannelType.PrivateThread, DiscordTypes.ChannelType.PublicThread, DiscordTypes.ChannelType.AnnouncementThread].includes(channel.type)) {
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
|
|
||||||
const spaceKState = await ks.roomToKState(spaceID)
|
|
||||||
let spaceEventContent = {}
|
let spaceEventContent = {}
|
||||||
if (
|
if (
|
||||||
channel.type !== DiscordTypes.ChannelType.PrivateThread // private threads do not belong in the space (don't offer people something they can't join)
|
channel.type !== DiscordTypes.ChannelType.PrivateThread // private threads do not belong in the space (don't offer people something they can't join)
|
||||||
&& (
|
&& !channel["thread_metadata"]?.archived // archived threads do not belong in the space (don't offer people conversations that are no longer relevant)
|
||||||
!channel["thread_metadata"]?.archived // archived threads do not belong in the space (don't offer people conversations that are no longer relevant)
|
|
||||||
|| discord.channels.get(channel.parent_id || "")?.type === DiscordTypes.ChannelType.GuildForum
|
|
||||||
)
|
|
||||||
) {
|
) {
|
||||||
spaceEventContent = {
|
spaceEventContent = {
|
||||||
via: [reg.ooye.server_name]
|
via: [reg.ooye.server_name]
|
||||||
|
|
@ -553,7 +426,7 @@ async function _syncSpaceMember(channel, spaceID, roomID, guild_id) {
|
||||||
const spaceDiff = ks.diffKState(spaceKState, {
|
const spaceDiff = ks.diffKState(spaceKState, {
|
||||||
[`m.space.child/${roomID}`]: spaceEventContent
|
[`m.space.child/${roomID}`]: spaceEventContent
|
||||||
})
|
})
|
||||||
return ks.applyKStateDiffToRoom(spaceID, spaceDiff)
|
return applyKStateDiffToRoom(spaceID, spaceDiff)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createAllForGuild(guildID) {
|
async function createAllForGuild(guildID) {
|
||||||
|
|
@ -570,16 +443,15 @@ async function createAllForGuild(guildID) {
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.DEFAULT_PRIVACY_LEVEL = DEFAULT_PRIVACY_LEVEL
|
module.exports.DEFAULT_PRIVACY_LEVEL = DEFAULT_PRIVACY_LEVEL
|
||||||
module.exports.READ_ONLY_ROOM_EVENTS_DEFAULT_POWER = READ_ONLY_ROOM_EVENTS_DEFAULT_POWER
|
|
||||||
module.exports.PRIVACY_ENUMS = PRIVACY_ENUMS
|
module.exports.PRIVACY_ENUMS = PRIVACY_ENUMS
|
||||||
module.exports.createRoom = createRoom
|
module.exports.createRoom = createRoom
|
||||||
module.exports.ensureRoom = ensureRoom
|
module.exports.ensureRoom = ensureRoom
|
||||||
module.exports.syncRoom = syncRoom
|
module.exports.syncRoom = syncRoom
|
||||||
module.exports.createAllForGuild = createAllForGuild
|
module.exports.createAllForGuild = createAllForGuild
|
||||||
module.exports.channelToKState = channelToKState
|
module.exports.channelToKState = channelToKState
|
||||||
|
module.exports.roomToKState = roomToKState
|
||||||
|
module.exports.applyKStateDiffToRoom = applyKStateDiffToRoom
|
||||||
module.exports.postApplyPowerLevels = postApplyPowerLevels
|
module.exports.postApplyPowerLevels = postApplyPowerLevels
|
||||||
module.exports._convertNameAndTopic = convertNameAndTopic
|
module.exports._convertNameAndTopic = convertNameAndTopic
|
||||||
module.exports._syncSpaceMember = _syncSpaceMember
|
module.exports._unbridgeRoom = _unbridgeRoom
|
||||||
module.exports.unbridgeChannel = unbridgeChannel
|
module.exports.unbridgeDeletedChannel = unbridgeDeletedChannel
|
||||||
module.exports.existsOrAutocreatable = existsOrAutocreatable
|
|
||||||
module.exports.assertExistsOrAutocreatable = assertExistsOrAutocreatable
|
|
||||||
|
|
|
||||||
|
|
@ -9,44 +9,19 @@ const testData = require("../../../test/data")
|
||||||
const passthrough = require("../../passthrough")
|
const passthrough = require("../../passthrough")
|
||||||
const {db} = passthrough
|
const {db} = passthrough
|
||||||
|
|
||||||
function mockAPI(t) {
|
|
||||||
let called = 0
|
|
||||||
return {
|
|
||||||
getCalled() {
|
|
||||||
return called
|
|
||||||
},
|
|
||||||
async getStateEvent(roomID, type, key) { // getting power levels from space to apply to room
|
|
||||||
called++
|
|
||||||
t.equal(roomID, "!jjmvBegULiLucuWEHU:cadence.moe")
|
|
||||||
t.equal(type, "m.room.power_levels")
|
|
||||||
t.equal(key, "")
|
|
||||||
return {users: {"@example:matrix.org": 50}, events: {"m.room.tombstone": 100}}
|
|
||||||
},
|
|
||||||
async getStateEventOuter(roomID, type, key) {
|
|
||||||
called++
|
|
||||||
t.equal(roomID, "!jjmvBegULiLucuWEHU:cadence.moe")
|
|
||||||
t.equal(type, "m.room.create")
|
|
||||||
t.equal(key, "")
|
|
||||||
return {
|
|
||||||
type: "m.room.create",
|
|
||||||
state_key: "",
|
|
||||||
content: {
|
|
||||||
room_version: "11"
|
|
||||||
},
|
|
||||||
event_id: "$create",
|
|
||||||
origin_server_ts: 0,
|
|
||||||
room_id: "!jjmvBegULiLucuWEHU:cadence.moe",
|
|
||||||
sender: "@_ooye_bot:cadence.moe"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
test("channel2room: discoverable privacy room", async t => {
|
test("channel2room: discoverable privacy room", async t => {
|
||||||
const api = mockAPI(t)
|
let called = 0
|
||||||
|
async function getStateEvent(roomID, type, key) { // getting power levels from space to apply to room
|
||||||
|
called++
|
||||||
|
t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe")
|
||||||
|
t.equal(type, "m.room.power_levels")
|
||||||
|
t.equal(key, "")
|
||||||
|
return {users: {"@example:matrix.org": 50}}
|
||||||
|
}
|
||||||
db.prepare("UPDATE guild_space SET privacy_level = 2").run()
|
db.prepare("UPDATE guild_space SET privacy_level = 2").run()
|
||||||
t.deepEqual(
|
t.deepEqual(
|
||||||
kstateStripConditionals(await channelToKState(testData.channel.general, testData.guild.general, {api}).then(x => x.channelKState)),
|
kstateStripConditionals(await channelToKState(testData.channel.general, testData.guild.general, {api: {getStateEvent}}).then(x => x.channelKState)),
|
||||||
Object.assign({}, testData.room.general, {
|
Object.assign({}, testData.room.general, {
|
||||||
"m.room.guest_access/": {guest_access: "forbidden"},
|
"m.room.guest_access/": {guest_access: "forbidden"},
|
||||||
"m.room.join_rules/": {join_rule: "public"},
|
"m.room.join_rules/": {join_rule: "public"},
|
||||||
|
|
@ -54,37 +29,58 @@ test("channel2room: discoverable privacy room", async t => {
|
||||||
"m.room.power_levels/": mixin({users: {"@example:matrix.org": 50}}, testData.room.general["m.room.power_levels/"])
|
"m.room.power_levels/": mixin({users: {"@example:matrix.org": 50}}, testData.room.general["m.room.power_levels/"])
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
t.equal(api.getCalled(), 2)
|
t.equal(called, 1)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("channel2room: linkable privacy room", async t => {
|
test("channel2room: linkable privacy room", async t => {
|
||||||
const api = mockAPI(t)
|
let called = 0
|
||||||
|
async function getStateEvent(roomID, type, key) { // getting power levels from space to apply to room
|
||||||
|
called++
|
||||||
|
t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe")
|
||||||
|
t.equal(type, "m.room.power_levels")
|
||||||
|
t.equal(key, "")
|
||||||
|
return {users: {"@example:matrix.org": 50}}
|
||||||
|
}
|
||||||
db.prepare("UPDATE guild_space SET privacy_level = 1").run()
|
db.prepare("UPDATE guild_space SET privacy_level = 1").run()
|
||||||
t.deepEqual(
|
t.deepEqual(
|
||||||
kstateStripConditionals(await channelToKState(testData.channel.general, testData.guild.general, {api}).then(x => x.channelKState)),
|
kstateStripConditionals(await channelToKState(testData.channel.general, testData.guild.general, {api: {getStateEvent}}).then(x => x.channelKState)),
|
||||||
Object.assign({}, testData.room.general, {
|
Object.assign({}, testData.room.general, {
|
||||||
"m.room.guest_access/": {guest_access: "forbidden"},
|
"m.room.guest_access/": {guest_access: "forbidden"},
|
||||||
"m.room.join_rules/": {join_rule: "public"},
|
"m.room.join_rules/": {join_rule: "public"},
|
||||||
"m.room.power_levels/": mixin({users: {"@example:matrix.org": 50}}, testData.room.general["m.room.power_levels/"])
|
"m.room.power_levels/": mixin({users: {"@example:matrix.org": 50}}, testData.room.general["m.room.power_levels/"])
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
t.equal(api.getCalled(), 2)
|
t.equal(called, 1)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("channel2room: invite-only privacy room", async t => {
|
test("channel2room: invite-only privacy room", async t => {
|
||||||
const api = mockAPI(t)
|
let called = 0
|
||||||
|
async function getStateEvent(roomID, type, key) { // getting power levels from space to apply to room
|
||||||
|
called++
|
||||||
|
t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe")
|
||||||
|
t.equal(type, "m.room.power_levels")
|
||||||
|
t.equal(key, "")
|
||||||
|
return {users: {"@example:matrix.org": 50}}
|
||||||
|
}
|
||||||
db.prepare("UPDATE guild_space SET privacy_level = 0").run()
|
db.prepare("UPDATE guild_space SET privacy_level = 0").run()
|
||||||
t.deepEqual(
|
t.deepEqual(
|
||||||
kstateStripConditionals(await channelToKState(testData.channel.general, testData.guild.general, {api}).then(x => x.channelKState)),
|
kstateStripConditionals(await channelToKState(testData.channel.general, testData.guild.general, {api: {getStateEvent}}).then(x => x.channelKState)),
|
||||||
Object.assign({}, testData.room.general, {
|
Object.assign({}, testData.room.general, {
|
||||||
"m.room.power_levels/": mixin({users: {"@example:matrix.org": 50}}, testData.room.general["m.room.power_levels/"])
|
"m.room.power_levels/": mixin({users: {"@example:matrix.org": 50}}, testData.room.general["m.room.power_levels/"])
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
t.equal(api.getCalled(), 2)
|
t.equal(called, 1)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("channel2room: room where limited people can mention everyone", async t => {
|
test("channel2room: room where limited people can mention everyone", async t => {
|
||||||
const api = mockAPI(t)
|
let called = 0
|
||||||
|
async function getStateEvent(roomID, type, key) { // getting power levels from space to apply to room
|
||||||
|
called++
|
||||||
|
t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe")
|
||||||
|
t.equal(type, "m.room.power_levels")
|
||||||
|
t.equal(key, "")
|
||||||
|
return {users: {"@example:matrix.org": 50}}
|
||||||
|
}
|
||||||
const limitedGuild = mixin({}, testData.guild.general)
|
const limitedGuild = mixin({}, testData.guild.general)
|
||||||
limitedGuild.roles[0].permissions = (BigInt(limitedGuild.roles[0].permissions) - 131072n).toString()
|
limitedGuild.roles[0].permissions = (BigInt(limitedGuild.roles[0].permissions) - 131072n).toString()
|
||||||
const limitedRoom = mixin({}, testData.room.general, {"m.room.power_levels/": {
|
const limitedRoom = mixin({}, testData.room.general, {"m.room.power_levels/": {
|
||||||
|
|
@ -92,102 +88,10 @@ test("channel2room: room where limited people can mention everyone", async t =>
|
||||||
users: {"@example:matrix.org": 50}
|
users: {"@example:matrix.org": 50}
|
||||||
}})
|
}})
|
||||||
t.deepEqual(
|
t.deepEqual(
|
||||||
kstateStripConditionals(await channelToKState(testData.channel.general, limitedGuild, {api}).then(x => x.channelKState)),
|
kstateStripConditionals(await channelToKState(testData.channel.general, limitedGuild, {api: {getStateEvent}}).then(x => x.channelKState)),
|
||||||
limitedRoom
|
limitedRoom
|
||||||
)
|
)
|
||||||
t.equal(api.getCalled(), 2)
|
t.equal(called, 1)
|
||||||
})
|
|
||||||
|
|
||||||
test("channel2room: matrix room that already has a custom topic set", async t => {
|
|
||||||
const api = mockAPI(t)
|
|
||||||
db.prepare("UPDATE channel_room SET custom_topic = 1 WHERE channel_id = ?").run(testData.channel.general.id)
|
|
||||||
const expected = mixin({}, testData.room.general, {"m.room.power_levels/": {notifications: {room: 20}, users: {"@example:matrix.org": 50}}})
|
|
||||||
// @ts-ignore
|
|
||||||
delete expected["m.room.topic/"]
|
|
||||||
t.deepEqual(
|
|
||||||
kstateStripConditionals(await channelToKState(testData.channel.general, testData.guild.general, {api}).then(x => x.channelKState)),
|
|
||||||
expected
|
|
||||||
)
|
|
||||||
t.equal(api.getCalled(), 2)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("channel2room: read-only discord channel", async t => {
|
|
||||||
const api = mockAPI(t)
|
|
||||||
const expected = {
|
|
||||||
"m.room.create/": {
|
|
||||||
additional_creators: ["@test_auto_invite:example.org"],
|
|
||||||
},
|
|
||||||
"m.room.avatar/": {
|
|
||||||
url: {
|
|
||||||
$url: "/icons/112760669178241024/a_f83622e09ead74f0c5c527fe241f8f8c.png?size=1024",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"m.room.guest_access/": {
|
|
||||||
guest_access: "can_join",
|
|
||||||
},
|
|
||||||
"m.room.history_visibility/": {
|
|
||||||
history_visibility: "shared",
|
|
||||||
},
|
|
||||||
"m.room.join_rules/": {
|
|
||||||
allow: [
|
|
||||||
{
|
|
||||||
room_id: "!jjmvBegULiLucuWEHU:cadence.moe",
|
|
||||||
type: "m.room_membership",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
join_rule: "restricted",
|
|
||||||
},
|
|
||||||
"m.room.name/": {
|
|
||||||
name: "updates",
|
|
||||||
},
|
|
||||||
"m.room.topic/": {
|
|
||||||
topic: "Updates and release announcements for Out Of Your Element.\n\nChannel ID: 1161864271370666075\nGuild ID: 112760669178241024"
|
|
||||||
},
|
|
||||||
"m.room.power_levels/": {
|
|
||||||
events_default: 50, // <-- it should be read-only!
|
|
||||||
events: {
|
|
||||||
"m.reaction": 0,
|
|
||||||
"m.room.redaction": 0
|
|
||||||
},
|
|
||||||
notifications: {
|
|
||||||
room: 20,
|
|
||||||
},
|
|
||||||
users: {
|
|
||||||
"@test_auto_invite:example.org": 150,
|
|
||||||
"@example:matrix.org": 50
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"m.space.parent/!jjmvBegULiLucuWEHU:cadence.moe": {
|
|
||||||
canonical: true,
|
|
||||||
via: [
|
|
||||||
"cadence.moe",
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"uk.half-shot.bridge/moe.cadence.ooye://discord/112760669178241024/1161864271370666075": {
|
|
||||||
bridgebot: "@_ooye_bot:cadence.moe",
|
|
||||||
channel: {
|
|
||||||
displayname: "updates",
|
|
||||||
external_url: "https://discord.com/channels/112760669178241024/1161864271370666075",
|
|
||||||
id: "1161864271370666075",
|
|
||||||
},
|
|
||||||
network: {
|
|
||||||
avatar_url: {
|
|
||||||
"$url": "/icons/112760669178241024/a_f83622e09ead74f0c5c527fe241f8f8c.png?size=1024",
|
|
||||||
},
|
|
||||||
displayname: "Psychonauts 3",
|
|
||||||
id: "112760669178241024",
|
|
||||||
},
|
|
||||||
protocol: {
|
|
||||||
displayname: "Discord",
|
|
||||||
id: "discord",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
t.deepEqual(
|
|
||||||
kstateStripConditionals(await channelToKState(testData.channel.updates, testData.guild.general, {api}).then(x => x.channelKState)),
|
|
||||||
expected
|
|
||||||
)
|
|
||||||
t.equal(api.getCalled(), 2)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test("convertNameAndTopic: custom name and topic", t => {
|
test("convertNameAndTopic: custom name and topic", t => {
|
||||||
|
|
|
||||||
|
|
@ -31,12 +31,10 @@ async function createSpace(guild, kstate) {
|
||||||
const topic = kstate["m.room.topic/"]?.topic || undefined
|
const topic = kstate["m.room.topic/"]?.topic || undefined
|
||||||
assert(name)
|
assert(name)
|
||||||
|
|
||||||
const memberCount = guild["member_count"] ?? guild.approximate_member_count ?? 0
|
|
||||||
const enablePresenceByDefault = +(memberCount < 50) // scary! all active users in a presence-enabled guild will be pinging the server every <30 seconds to stay online
|
|
||||||
const globalAdmins = select("member_power", "mxid", {room_id: "*"}).pluck().all()
|
const globalAdmins = select("member_power", "mxid", {room_id: "*"}).pluck().all()
|
||||||
|
|
||||||
const roomCreate = await createRoom.postApplyPowerLevels(kstate, async kstate => {
|
const roomID = await createRoom.postApplyPowerLevels(kstate, async kstate => {
|
||||||
const roomID = await api.createRoom({
|
return api.createRoom({
|
||||||
name,
|
name,
|
||||||
preset: createRoom.PRIVACY_ENUMS.PRESET[createRoom.DEFAULT_PRIVACY_LEVEL], // New spaces will have to use the default privacy level; we obviously can't look up the existing entry
|
preset: createRoom.PRIVACY_ENUMS.PRESET[createRoom.DEFAULT_PRIVACY_LEVEL], // New spaces will have to use the default privacy level; we obviously can't look up the existing entry
|
||||||
visibility: createRoom.PRIVACY_ENUMS.VISIBILITY[createRoom.DEFAULT_PRIVACY_LEVEL],
|
visibility: createRoom.PRIVACY_ENUMS.VISIBILITY[createRoom.DEFAULT_PRIVACY_LEVEL],
|
||||||
|
|
@ -46,15 +44,13 @@ async function createSpace(guild, kstate) {
|
||||||
},
|
},
|
||||||
invite: globalAdmins,
|
invite: globalAdmins,
|
||||||
topic,
|
topic,
|
||||||
initial_state: await ks.kstateToState(kstate),
|
creation_content: {
|
||||||
creation_content: ks.kstateToCreationContent(kstate)
|
type: "m.space"
|
||||||
|
},
|
||||||
|
initial_state: await ks.kstateToState(kstate)
|
||||||
})
|
})
|
||||||
const roomCreate = await api.getStateEventOuter(roomID, "m.room.create", "")
|
|
||||||
return roomCreate
|
|
||||||
})
|
})
|
||||||
const roomID = roomCreate.room_id
|
db.prepare("INSERT INTO guild_space (guild_id, space_id) VALUES (?, ?)").run(guild.id, roomID)
|
||||||
|
|
||||||
db.prepare("INSERT INTO guild_space (guild_id, space_id, presence) VALUES (?, ?, ?)").run(guild.id, roomID, enablePresenceByDefault)
|
|
||||||
return roomID
|
return roomID
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -65,13 +61,7 @@ async function createSpace(guild, kstate) {
|
||||||
async function guildToKState(guild, privacyLevel) {
|
async function guildToKState(guild, privacyLevel) {
|
||||||
assert.equal(typeof privacyLevel, "number")
|
assert.equal(typeof privacyLevel, "number")
|
||||||
const globalAdmins = select("member_power", ["mxid", "power_level"], {room_id: "*"}).all()
|
const globalAdmins = select("member_power", ["mxid", "power_level"], {room_id: "*"}).all()
|
||||||
const additionalCreators = select("member_power", "mxid", {room_id: "*"}, "AND power_level > 100").pluck().all()
|
|
||||||
|
|
||||||
const guildKState = {
|
const guildKState = {
|
||||||
"m.room.create/": {
|
|
||||||
type: "m.space",
|
|
||||||
additional_creators: additionalCreators
|
|
||||||
},
|
|
||||||
"m.room.name/": {name: guild.name},
|
"m.room.name/": {name: guild.name},
|
||||||
"m.room.avatar/": {
|
"m.room.avatar/": {
|
||||||
$if: guild.icon,
|
$if: guild.icon,
|
||||||
|
|
@ -102,9 +92,6 @@ async function _syncSpace(guild, shouldActuallySync) {
|
||||||
const row = select("guild_space", ["space_id", "privacy_level"], {guild_id: guild.id}).get()
|
const row = select("guild_space", ["space_id", "privacy_level"], {guild_id: guild.id}).get()
|
||||||
|
|
||||||
if (!row) {
|
if (!row) {
|
||||||
const autocreate = select("guild_active", "autocreate", {guild_id: guild.id}).pluck().get()
|
|
||||||
assert.equal(autocreate, 1, `refusing to implicitly create a space for guild ${guild.id}. set the guild_active data first before calling ensureSpace/syncSpace.`)
|
|
||||||
|
|
||||||
const creation = (async () => {
|
const creation = (async () => {
|
||||||
const guildKState = await guildToKState(guild, createRoom.DEFAULT_PRIVACY_LEVEL) // New spaces will have to use the default privacy level; we obviously can't look up the existing entry
|
const guildKState = await guildToKState(guild, createRoom.DEFAULT_PRIVACY_LEVEL) // New spaces will have to use the default privacy level; we obviously can't look up the existing entry
|
||||||
const spaceID = await createSpace(guild, guildKState)
|
const spaceID = await createSpace(guild, guildKState)
|
||||||
|
|
@ -124,13 +111,11 @@ async function _syncSpace(guild, shouldActuallySync) {
|
||||||
console.log(`[space sync] to matrix: ${guild.name}`)
|
console.log(`[space sync] to matrix: ${guild.name}`)
|
||||||
|
|
||||||
const guildKState = await guildToKState(guild, privacy_level) // calling this in both branches because we don't want to calculate this if not syncing
|
const guildKState = await guildToKState(guild, privacy_level) // calling this in both branches because we don't want to calculate this if not syncing
|
||||||
ks.kstateStripConditionals(guildKState) // pre-upload icons before diffing
|
|
||||||
await ks.kstateUploadMxc(guildKState)
|
|
||||||
|
|
||||||
// sync guild state to space
|
// sync guild state to space
|
||||||
const spaceKState = await ks.roomToKState(spaceID)
|
const spaceKState = await createRoom.roomToKState(spaceID)
|
||||||
const spaceDiff = ks.diffKState(spaceKState, guildKState)
|
const spaceDiff = ks.diffKState(spaceKState, guildKState)
|
||||||
await ks.applyKStateDiffToRoom(spaceID, spaceDiff)
|
await createRoom.applyKStateDiffToRoom(spaceID, spaceDiff)
|
||||||
|
|
||||||
// guild icon was changed, so room avatars need to be updated as well as the space ones
|
// guild icon was changed, so room avatars need to be updated as well as the space ones
|
||||||
// doing it this way rather than calling syncRoom for great efficiency gains
|
// doing it this way rather than calling syncRoom for great efficiency gains
|
||||||
|
|
@ -139,10 +124,16 @@ async function _syncSpace(guild, shouldActuallySync) {
|
||||||
// don't try to update rooms with custom avatars though
|
// don't try to update rooms with custom avatars though
|
||||||
const roomsWithCustomAvatars = select("channel_room", "room_id", {}, "WHERE custom_avatar IS NOT NULL").pluck().all()
|
const roomsWithCustomAvatars = select("channel_room", "room_id", {}, "WHERE custom_avatar IS NOT NULL").pluck().all()
|
||||||
|
|
||||||
for await (const room of api.generateFullHierarchy(spaceID)) {
|
const state = await ks.kstateToState(spaceKState)
|
||||||
if (room.avatar_url === newAvatarState.url) continue
|
const childRooms = state.filter(({type, state_key, content}) => {
|
||||||
if (roomsWithCustomAvatars.includes(room.room_id)) continue
|
return type === "m.space.child" && "via" in content && !roomsWithCustomAvatars.includes(state_key)
|
||||||
await api.sendState(room.room_id, "m.room.avatar", "", newAvatarState)
|
}).map(({state_key}) => state_key)
|
||||||
|
|
||||||
|
for (const roomID of childRooms) {
|
||||||
|
const avatarEventContent = await api.getStateEvent(roomID, "m.room.avatar", "")
|
||||||
|
if (avatarEventContent.url !== newAvatarState.url) {
|
||||||
|
await api.sendState(roomID, "m.room.avatar", "", newAvatarState)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -187,13 +178,11 @@ async function syncSpaceFully(guildID) {
|
||||||
console.log(`[space sync] to matrix: ${guild.name}`)
|
console.log(`[space sync] to matrix: ${guild.name}`)
|
||||||
|
|
||||||
const guildKState = await guildToKState(guild, privacy_level)
|
const guildKState = await guildToKState(guild, privacy_level)
|
||||||
ks.kstateStripConditionals(guildKState) // pre-upload icons before diffing
|
|
||||||
await ks.kstateUploadMxc(guildKState)
|
|
||||||
|
|
||||||
// sync guild state to space
|
// sync guild state to space
|
||||||
const spaceKState = await ks.roomToKState(spaceID)
|
const spaceKState = await createRoom.roomToKState(spaceID)
|
||||||
const spaceDiff = ks.diffKState(spaceKState, guildKState)
|
const spaceDiff = ks.diffKState(spaceKState, guildKState)
|
||||||
await ks.applyKStateDiffToRoom(spaceID, spaceDiff)
|
await createRoom.applyKStateDiffToRoom(spaceID, spaceDiff)
|
||||||
|
|
||||||
const childRooms = await api.getFullHierarchy(spaceID)
|
const childRooms = await api.getFullHierarchy(spaceID)
|
||||||
|
|
||||||
|
|
@ -203,7 +192,7 @@ async function syncSpaceFully(guildID) {
|
||||||
if (discord.channels.has(channelID)) {
|
if (discord.channels.has(channelID)) {
|
||||||
await createRoom.syncRoom(channelID)
|
await createRoom.syncRoom(channelID)
|
||||||
} else {
|
} else {
|
||||||
await createRoom.unbridgeChannel({id: channelID}, guildID)
|
await createRoom.unbridgeDeletedChannel({id: channelID}, guildID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -229,24 +218,22 @@ async function syncSpaceExpressions(data, checkBeforeSync) {
|
||||||
*/
|
*/
|
||||||
async function update(spaceID, key, eventKey, fn) {
|
async function update(spaceID, key, eventKey, fn) {
|
||||||
if (!(key in data) || !data[key].length) return
|
if (!(key in data) || !data[key].length) return
|
||||||
const guild = discord.guilds.get(data.guild_id)
|
const content = await fn(data[key])
|
||||||
assert(guild)
|
|
||||||
const content = await fn(data[key], guild)
|
|
||||||
if (checkBeforeSync) {
|
if (checkBeforeSync) {
|
||||||
let existing
|
let existing
|
||||||
try {
|
try {
|
||||||
existing = await api.getStateEvent(spaceID, "im.ponies.room_emotes", eventKey)
|
existing = await api.getStateEvent(spaceID, "im.ponies.room_emotes", eventKey)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// State event not found. This space doesn't have any existing emojis. We create a dummy empty event for comparison's sake.
|
// State event not found. This space doesn't have any existing emojis. We create a dummy empty event for comparison's sake.
|
||||||
existing = fn([], guild)
|
existing = fn([])
|
||||||
}
|
}
|
||||||
if (isDeepStrictEqual(existing, content)) return
|
if (isDeepStrictEqual(existing, content)) return
|
||||||
}
|
}
|
||||||
await api.sendState(spaceID, "im.ponies.room_emotes", eventKey, content)
|
api.sendState(spaceID, "im.ponies.room_emotes", eventKey, content)
|
||||||
}
|
}
|
||||||
|
|
||||||
await update(spaceID, "emojis", "moe.cadence.ooye.pack.emojis", expression.emojisToState)
|
update(spaceID, "emojis", "moe.cadence.ooye.pack.emojis", expression.emojisToState)
|
||||||
await update(spaceID, "stickers", "moe.cadence.ooye.pack.stickers", expression.stickersToState)
|
update(spaceID, "stickers", "moe.cadence.ooye.pack.stickers", expression.stickersToState)
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.createSpace = createSpace
|
module.exports.createSpace = createSpace
|
||||||
|
|
|
||||||
|
|
@ -13,10 +13,6 @@ test("guild2space: can generate kstate for a guild, passing privacy level 0", as
|
||||||
t.deepEqual(
|
t.deepEqual(
|
||||||
await kstateUploadMxc(kstateStripConditionals(await guildToKState(testData.guild.general, 0))),
|
await kstateUploadMxc(kstateStripConditionals(await guildToKState(testData.guild.general, 0))),
|
||||||
{
|
{
|
||||||
"m.room.create/": {
|
|
||||||
additional_creators: ["@test_auto_invite:example.org"],
|
|
||||||
type: "m.space"
|
|
||||||
},
|
|
||||||
"m.room.avatar/": {
|
"m.room.avatar/": {
|
||||||
url: "mxc://cadence.moe/zKXGZhmImMHuGQZWJEFKJbsF"
|
url: "mxc://cadence.moe/zKXGZhmImMHuGQZWJEFKJbsF"
|
||||||
},
|
},
|
||||||
|
|
@ -34,7 +30,7 @@ test("guild2space: can generate kstate for a guild, passing privacy level 0", as
|
||||||
},
|
},
|
||||||
"m.room.power_levels/": {
|
"m.room.power_levels/": {
|
||||||
users: {
|
users: {
|
||||||
"@test_auto_invite:example.org": 150
|
"@test_auto_invite:example.org": 100
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,13 +14,12 @@ async function deleteMessage(data) {
|
||||||
const row = select("channel_room", ["room_id", "speedbump_checked", "thread_parent"], {channel_id: data.channel_id}).get()
|
const row = select("channel_room", ["room_id", "speedbump_checked", "thread_parent"], {channel_id: data.channel_id}).get()
|
||||||
if (!row) return
|
if (!row) return
|
||||||
|
|
||||||
// Assume we can redact from tombstoned rooms.
|
const eventsToRedact = select("event_message", "event_id", {message_id: data.id}).pluck().all()
|
||||||
const eventsToRedact = from("event_message").join("message_room", "message_id").join("historical_channel_room", "historical_room_index")
|
db.prepare("DELETE FROM message_channel WHERE message_id = ?").run(data.id)
|
||||||
.select("event_id", "room_id").where({message_id: data.id}).all()
|
db.prepare("DELETE FROM event_message WHERE message_id = ?").run(data.id)
|
||||||
db.prepare("DELETE FROM message_room WHERE message_id = ?").run(data.id)
|
for (const eventID of eventsToRedact) {
|
||||||
for (const {event_id, room_id} of eventsToRedact) {
|
|
||||||
// Unfortunately, we can't specify a sender to do the redaction as, unless we find out that info via the audit logs
|
// Unfortunately, we can't specify a sender to do the redaction as, unless we find out that info via the audit logs
|
||||||
await api.redactEvent(room_id, event_id)
|
await api.redactEvent(row.room_id, eventID)
|
||||||
}
|
}
|
||||||
|
|
||||||
await speedbump.updateCache(row.thread_parent || data.channel_id, row.speedbump_checked)
|
await speedbump.updateCache(row.thread_parent || data.channel_id, row.speedbump_checked)
|
||||||
|
|
@ -30,17 +29,16 @@ async function deleteMessage(data) {
|
||||||
* @param {import("discord-api-types/v10").GatewayMessageDeleteBulkDispatchData} data
|
* @param {import("discord-api-types/v10").GatewayMessageDeleteBulkDispatchData} data
|
||||||
*/
|
*/
|
||||||
async function deleteMessageBulk(data) {
|
async function deleteMessageBulk(data) {
|
||||||
const row = select("channel_room", "room_id", {channel_id: data.channel_id}).get()
|
const roomID = select("channel_room", "room_id", {channel_id: data.channel_id}).pluck().get()
|
||||||
if (!row) return
|
if (!roomID) return
|
||||||
|
|
||||||
const sids = JSON.stringify(data.ids)
|
const sids = JSON.stringify(data.ids)
|
||||||
// Assume we can redact from tombstoned rooms.
|
const eventsToRedact = from("event_message").pluck("event_id").and("WHERE message_id IN (SELECT value FROM json_each(?))").all(sids)
|
||||||
const eventsToRedact = from("event_message").join("message_room", "message_id").join("historical_channel_room", "historical_room_index")
|
db.prepare("DELETE FROM message_channel WHERE message_id IN (SELECT value FROM json_each(?))").run(sids)
|
||||||
.select("event_id", "room_id").and("WHERE message_id IN (SELECT value FROM json_each(?))").all(sids)
|
db.prepare("DELETE FROM event_message WHERE message_id IN (SELECT value FROM json_each(?))").run(sids)
|
||||||
db.prepare("DELETE FROM message_room WHERE message_id IN (SELECT value FROM json_each(?))").run(sids)
|
for (const eventID of eventsToRedact) {
|
||||||
for (const {event_id, room_id} of eventsToRedact) {
|
|
||||||
// Awaiting will make it go slower, but since this could be a long-running operation either way, we want to leave rate limit capacity for other operations
|
// Awaiting will make it go slower, but since this could be a long-running operation either way, we want to leave rate limit capacity for other operations
|
||||||
await api.redactEvent(room_id, event_id)
|
await api.redactEvent(roomID, eventID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,15 +3,13 @@
|
||||||
const assert = require("assert").strict
|
const assert = require("assert").strict
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
const passthrough = require("../../passthrough")
|
||||||
const {sync, db, select, from} = passthrough
|
const {sync, db, select} = passthrough
|
||||||
/** @type {import("../converters/edit-to-changes")} */
|
/** @type {import("../converters/edit-to-changes")} */
|
||||||
const editToChanges = sync.require("../converters/edit-to-changes")
|
const editToChanges = sync.require("../converters/edit-to-changes")
|
||||||
/** @type {import("./register-pk-user")} */
|
/** @type {import("./register-pk-user")} */
|
||||||
const registerPkUser = sync.require("./register-pk-user")
|
const registerPkUser = sync.require("./register-pk-user")
|
||||||
/** @type {import("../../matrix/api")} */
|
/** @type {import("../../matrix/api")} */
|
||||||
const api = sync.require("../../matrix/api")
|
const api = sync.require("../../matrix/api")
|
||||||
/** @type {import("../../matrix/mreq")} */
|
|
||||||
const mreq = sync.require("../../matrix/mreq")
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {import("discord-api-types/v10").GatewayMessageCreateDispatchData} message
|
* @param {import("discord-api-types/v10").GatewayMessageCreateDispatchData} message
|
||||||
|
|
@ -19,18 +17,14 @@ const mreq = sync.require("../../matrix/mreq")
|
||||||
* @param {{speedbump_id: string, speedbump_webhook_id: string} | null} row data about the webhook which is proxying messages in this channel
|
* @param {{speedbump_id: string, speedbump_webhook_id: string} | null} row data about the webhook which is proxying messages in this channel
|
||||||
*/
|
*/
|
||||||
async function editMessage(message, guild, row) {
|
async function editMessage(message, guild, row) {
|
||||||
const historicalRoomOfMessage = from("message_room").join("historical_channel_room", "historical_room_index").where({message_id: message.id}).select("room_id").get()
|
|
||||||
const currentRoom = from("channel_room").join("historical_channel_room", "room_id").where({channel_id: message.channel_id}).select("room_id", "historical_room_index").get()
|
|
||||||
if (!currentRoom) return
|
|
||||||
|
|
||||||
if (historicalRoomOfMessage && historicalRoomOfMessage.room_id !== currentRoom.room_id) return // tombstoned rooms should not have new events (including edits) sent to them
|
|
||||||
|
|
||||||
let {roomID, eventsToRedact, eventsToReplace, eventsToSend, senderMxid, promotions} = await editToChanges.editToChanges(message, guild, api)
|
let {roomID, eventsToRedact, eventsToReplace, eventsToSend, senderMxid, promotions} = await editToChanges.editToChanges(message, guild, api)
|
||||||
|
|
||||||
if (row && row.speedbump_webhook_id === message.webhook_id) {
|
if (row && row.speedbump_webhook_id === message.webhook_id) {
|
||||||
// Handle the PluralKit public instance
|
// Handle the PluralKit public instance
|
||||||
if (row.speedbump_id === "466378653216014359") {
|
if (row.speedbump_id === "466378653216014359") {
|
||||||
senderMxid = await registerPkUser.syncUser(message.id, message.author, roomID, true)
|
const root = await registerPkUser.fetchMessage(message.id)
|
||||||
|
assert(root.member)
|
||||||
|
senderMxid = await registerPkUser.ensureSimJoined(root, roomID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -67,7 +61,7 @@ async function editMessage(message, guild, row) {
|
||||||
|
|
||||||
// 4. Send all the things.
|
// 4. Send all the things.
|
||||||
if (eventsToSend.length) {
|
if (eventsToSend.length) {
|
||||||
db.prepare("INSERT OR IGNORE INTO message_room (message_id, historical_room_index) VALUES (?, ?)").run(message.id, currentRoom.historical_room_index)
|
db.prepare("REPLACE INTO message_channel (message_id, channel_id) VALUES (?, ?)").run(message.id, message.channel_id)
|
||||||
}
|
}
|
||||||
for (const content of eventsToSend) {
|
for (const content of eventsToSend) {
|
||||||
const eventType = content.$type
|
const eventType = content.$type
|
||||||
|
|
@ -78,17 +72,8 @@ async function editMessage(message, guild, row) {
|
||||||
|
|
||||||
const part = sendNewEventParts.has("part") && eventsToSend[0] === content ? 0 : 1
|
const part = sendNewEventParts.has("part") && eventsToSend[0] === content ? 0 : 1
|
||||||
const reactionPart = sendNewEventParts.has("reaction_part") && eventsToSend[eventsToSend.length - 1] === content ? 0 : 1
|
const reactionPart = sendNewEventParts.has("reaction_part") && eventsToSend[eventsToSend.length - 1] === content ? 0 : 1
|
||||||
|
|
||||||
try {
|
|
||||||
const eventID = await api.sendEvent(roomID, eventType, contentWithoutType, senderMxid)
|
const eventID = await api.sendEvent(roomID, eventType, contentWithoutType, senderMxid)
|
||||||
db.prepare("INSERT INTO event_message (event_id, event_type, event_subtype, message_id, part, reaction_part, source) VALUES (?, ?, ?, ?, ?, ?, 1)").run(eventID, eventType, content.msgtype || null, message.id, part, reactionPart) // source 1 = discord
|
db.prepare("INSERT INTO event_message (event_id, event_type, event_subtype, message_id, part, reaction_part, source) VALUES (?, ?, ?, ?, ?, ?, 1)").run(eventID, eventType, content.msgtype || null, message.id, part, reactionPart) // source 1 = discord
|
||||||
} catch (e) {
|
|
||||||
if (e instanceof mreq.MatrixServerError && e.errcode === "M_FORBIDDEN") {
|
|
||||||
// sending user doesn't have permission to update message, e.g. because Discord generated an embed in a read-only room
|
|
||||||
} else {
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,12 +9,11 @@ const file = sync.require("../../matrix/file")
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {DiscordTypes.APIEmoji[]} emojis
|
* @param {DiscordTypes.APIEmoji[]} emojis
|
||||||
* @param {DiscordTypes.APIGuild} guild
|
|
||||||
*/
|
*/
|
||||||
async function emojisToState(emojis, guild) {
|
async function emojisToState(emojis) {
|
||||||
const result = {
|
const result = {
|
||||||
pack: {
|
pack: {
|
||||||
display_name: `${guild.name} (Discord Emojis)`,
|
display_name: "Discord Emojis",
|
||||||
usage: ["emoticon"] // we'll see...
|
usage: ["emoticon"] // we'll see...
|
||||||
},
|
},
|
||||||
images: {
|
images: {
|
||||||
|
|
@ -25,7 +24,7 @@ async function emojisToState(emojis, guild) {
|
||||||
file.uploadDiscordFileToMxc(file.emoji(emoji.id, emoji.animated)).then(url => {
|
file.uploadDiscordFileToMxc(file.emoji(emoji.id, emoji.animated)).then(url => {
|
||||||
result.images[emoji.name] = {
|
result.images[emoji.name] = {
|
||||||
info: {
|
info: {
|
||||||
mimetype: "image/webp"
|
mimetype: emoji.animated ? "image/gif" : "image/png"
|
||||||
},
|
},
|
||||||
url
|
url
|
||||||
}
|
}
|
||||||
|
|
@ -43,12 +42,11 @@ async function emojisToState(emojis, guild) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {DiscordTypes.APISticker[]} stickers
|
* @param {DiscordTypes.APISticker[]} stickers
|
||||||
* @param {DiscordTypes.APIGuild} guild
|
|
||||||
*/
|
*/
|
||||||
async function stickersToState(stickers, guild) {
|
async function stickersToState(stickers) {
|
||||||
const result = {
|
const result = {
|
||||||
pack: {
|
pack: {
|
||||||
display_name: `${guild.name} (Discord Stickers)`,
|
display_name: "Discord Stickers",
|
||||||
usage: ["sticker"] // we'll see...
|
usage: ["sticker"] // we'll see...
|
||||||
},
|
},
|
||||||
images: {
|
images: {
|
||||||
|
|
|
||||||
|
|
@ -33,7 +33,7 @@ async function convert(stickerItem) {
|
||||||
if (res.status !== 200) throw new Error("Sticker data file not found.")
|
if (res.status !== 200) throw new Error("Sticker data file not found.")
|
||||||
const text = await res.text()
|
const text = await res.text()
|
||||||
|
|
||||||
// Convert to PNG (stream.Readable)
|
// Convert to PNG (readable stream)
|
||||||
const readablePng = await convertLottie.convert(text)
|
const readablePng = await convertLottie.convert(text)
|
||||||
|
|
||||||
// Upload to MXC
|
// Upload to MXC
|
||||||
|
|
|
||||||
|
|
@ -1,122 +0,0 @@
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const assert = require("assert").strict
|
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
|
||||||
const {isDeepStrictEqual} = require("util")
|
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
|
||||||
const {discord, sync, db, select, from} = passthrough
|
|
||||||
const {reg} = require("../../matrix/read-registration")
|
|
||||||
/** @type {import("./poll-vote")} */
|
|
||||||
const vote = sync.require("../actions/poll-vote")
|
|
||||||
/** @type {import("../../discord/interactions/poll-responses")} */
|
|
||||||
const pollResponses = sync.require("../../discord/interactions/poll-responses")
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @file This handles, in the following order:
|
|
||||||
* * verifying Matrix-side votes are accurate for a poll originating on Discord, sending missed votes to Matrix if necessary
|
|
||||||
* * sending a message to Discord if a vote in that poll has been cast on Matrix
|
|
||||||
* This does *not* handle bridging of poll closures on Discord to Matrix; that takes place in converters/message-to-event.js.
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {string} channelID
|
|
||||||
* @param {string} messageID
|
|
||||||
* @param {string} answerID
|
|
||||||
* @returns {Promise<DiscordTypes.RESTGetAPIPollAnswerVotersResult["users"]>}
|
|
||||||
*/
|
|
||||||
async function getAllVotesOnAnswer(channelID, messageID, answerID) {
|
|
||||||
const limit = 100
|
|
||||||
/** @type {DiscordTypes.RESTGetAPIPollAnswerVotersResult["users"]} */
|
|
||||||
let voteUsers = []
|
|
||||||
let after = undefined
|
|
||||||
while (true) {
|
|
||||||
const curVotes = await discord.snow.channel.getPollAnswerVoters(channelID, messageID, answerID, {after: after, limit})
|
|
||||||
voteUsers = voteUsers.concat(curVotes.users)
|
|
||||||
if (curVotes.users.length >= limit) { // Loop again for the next page.
|
|
||||||
// @ts-ignore - stupid
|
|
||||||
after = curVotes.users.at(-1).id
|
|
||||||
} else { // Reached the end.
|
|
||||||
return voteUsers
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {typeof import("../../../test/data.js")["poll_close"]} closeMessage
|
|
||||||
*/
|
|
||||||
async function endPoll(closeMessage) {
|
|
||||||
const pollCloseObject = closeMessage.embeds[0]
|
|
||||||
|
|
||||||
const pollMessageID = closeMessage.message_reference.message_id
|
|
||||||
const pollEventID = select("event_message", "event_id", {message_id: pollMessageID, event_type: "org.matrix.msc3381.poll.start"}).pluck().get()
|
|
||||||
if (!pollEventID) return // Nothing we can send Discord-side if we don't have the original poll. We will still send a results message Matrix-side.
|
|
||||||
|
|
||||||
const discordPollOptions = select("poll_option", "discord_option", {message_id: pollMessageID}).pluck().all()
|
|
||||||
assert(discordPollOptions.every(x => typeof x === "string")) // This poll originated on Discord so it will have Discord option IDs
|
|
||||||
|
|
||||||
// If the closure came from Discord, we want to fetch all the votes there again and bridge over any that got lost to Matrix before posting the results.
|
|
||||||
// Database reads are cheap, and API calls are expensive, so we will only query Discord when the totals don't match.
|
|
||||||
|
|
||||||
const totalVotes = +pollCloseObject.fields.find(element => element.name === "total_votes").value // We could do [2], but best not to rely on the ordering staying consistent.
|
|
||||||
|
|
||||||
const databaseVotes = select("poll_vote", ["discord_or_matrix_user_id", "matrix_option"], {message_id: pollMessageID}, " AND discord_or_matrix_user_id NOT LIKE '@%'").all()
|
|
||||||
|
|
||||||
if (databaseVotes.length !== totalVotes) { // Matching length should be sufficient for most cases.
|
|
||||||
let voteUsers = [...new Set(databaseVotes.map(vote => vote.discord_or_matrix_user_id))] // Unique array of all users we have votes for in the database.
|
|
||||||
|
|
||||||
// Main design challenge here: we get the data by *answer*, but we need to send it to Matrix by *user*.
|
|
||||||
|
|
||||||
/** @type {{user: DiscordTypes.APIUser, matrixOptionVotes: string[]}[]} This will be our new array of answers */
|
|
||||||
const updatedAnswers = []
|
|
||||||
|
|
||||||
for (const discordPollOption of discordPollOptions) {
|
|
||||||
const optionUsers = await getAllVotesOnAnswer(closeMessage.channel_id, pollMessageID, discordPollOption) // Array of user IDs who voted for the option we're testing.
|
|
||||||
for (const user of optionUsers) {
|
|
||||||
const userLocation = updatedAnswers.findIndex(answer => answer.user.id === user.id)
|
|
||||||
const matrixOption = select("poll_option", "matrix_option", {message_id: pollMessageID, discord_option: discordPollOption}).pluck().get()
|
|
||||||
assert(matrixOption)
|
|
||||||
if (userLocation === -1) { // We haven't seen this user yet, so we need to add them.
|
|
||||||
updatedAnswers.push({user, matrixOptionVotes: [matrixOption]}) // toString as this is what we store and get from the database and send to Matrix.
|
|
||||||
} else { // This user already voted for another option on the poll.
|
|
||||||
updatedAnswers[userLocation].matrixOptionVotes.push(matrixOption)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for inconsistencies in what was cached in database vs final confirmed poll answers
|
|
||||||
// If different, sync the final confirmed answers to Matrix-side to make it accurate there too
|
|
||||||
|
|
||||||
await Promise.all(updatedAnswers.map(async answer => {
|
|
||||||
voteUsers = voteUsers.filter(item => item !== answer.user.id) // Remove any users we have updated answers for from voteUsers. The only remaining entries in this array will be users who voted, but then removed their votes before the poll ended.
|
|
||||||
const cachedAnswers = select("poll_vote", "matrix_option", {discord_or_matrix_user_id: answer.user.id, message_id: pollMessageID}).pluck().all()
|
|
||||||
if (!isDeepStrictEqual(new Set(cachedAnswers), new Set(answer.matrixOptionVotes))) {
|
|
||||||
db.transaction(() => {
|
|
||||||
db.prepare("DELETE FROM poll_vote WHERE discord_or_matrix_user_id = ? AND message_id = ?").run(answer.user.id, pollMessageID) // Delete existing stored votes.
|
|
||||||
for (const matrixOption of answer.matrixOptionVotes) {
|
|
||||||
db.prepare("INSERT INTO poll_vote (discord_or_matrix_user_id, message_id, matrix_option) VALUES (?, ?, ?)").run(answer.user.id, pollMessageID, matrixOption)
|
|
||||||
}
|
|
||||||
})()
|
|
||||||
await vote.sendVotes(answer.user, closeMessage.channel_id, pollMessageID, pollEventID)
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
|
|
||||||
await Promise.all(voteUsers.map(async user_id => { // Remove these votes.
|
|
||||||
db.prepare("DELETE FROM poll_vote WHERE discord_or_matrix_user_id = ? AND message_id = ?").run(user_id, pollMessageID)
|
|
||||||
await vote.sendVotes(user_id, closeMessage.channel_id, pollMessageID, pollEventID)
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
const {combinedVotes, messageString} = pollResponses.getCombinedResults(pollMessageID, true)
|
|
||||||
|
|
||||||
if (combinedVotes !== totalVotes) { // This means some votes were cast on Matrix. Now that we've corrected the vote totals, we can get the results again and post them to Discord.
|
|
||||||
return {
|
|
||||||
username: "Total results including Matrix votes",
|
|
||||||
avatar_url: `${reg.ooye.bridge_origin}/download/file/poll-star-avatar.png`,
|
|
||||||
content: messageString,
|
|
||||||
flags: DiscordTypes.MessageFlags.SuppressEmbeds
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports.endPoll = endPoll
|
|
||||||
|
|
@ -1,100 +0,0 @@
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const assert = require("assert").strict
|
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
|
||||||
const {Semaphore} = require("@chriscdn/promise-semaphore")
|
|
||||||
const {scheduler} = require("timers/promises")
|
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
|
||||||
const {discord, sync, db, select, from} = passthrough
|
|
||||||
/** @type {import("../../matrix/api")} */
|
|
||||||
const api = sync.require("../../matrix/api")
|
|
||||||
/** @type {import("./register-user")} */
|
|
||||||
const registerUser = sync.require("./register-user")
|
|
||||||
|
|
||||||
const inFlightPollSema = new Semaphore()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {import("discord-api-types/v10").GatewayMessagePollVoteAddDispatch["d"]} data
|
|
||||||
*/
|
|
||||||
async function addVote(data) {
|
|
||||||
const pollEventID = from("event_message").join("poll_option", "message_id").pluck("event_id").where({message_id: data.message_id, event_type: "org.matrix.msc3381.poll.start"}).get() // Currently Discord doesn't allow sending a poll with anything else, but we bridge it after all other content so reaction_part: 0 is the part that will have the poll.
|
|
||||||
if (!pollEventID) return // Nothing can be done if the parent message was never bridged.
|
|
||||||
|
|
||||||
let realAnswer = select("poll_option", "matrix_option", {message_id: data.message_id, discord_option: data.answer_id.toString()}).pluck().get() // Discord answer IDs don't match those on Matrix-created polls.
|
|
||||||
assert(realAnswer)
|
|
||||||
db.prepare("INSERT OR IGNORE INTO poll_vote (discord_or_matrix_user_id, message_id, matrix_option) VALUES (?, ?, ?)").run(data.user_id, data.message_id, realAnswer)
|
|
||||||
return debounceSendVotes(data, pollEventID)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {import("discord-api-types/v10").GatewayMessagePollVoteRemoveDispatch["d"]} data
|
|
||||||
*/
|
|
||||||
async function removeVote(data) {
|
|
||||||
const pollEventID = from("event_message").join("poll_option", "message_id").pluck("event_id").where({message_id: data.message_id, event_type: "org.matrix.msc3381.poll.start"}).get()
|
|
||||||
if (!pollEventID) return
|
|
||||||
|
|
||||||
let realAnswer = select("poll_option", "matrix_option", {message_id: data.message_id, discord_option: data.answer_id.toString()}).pluck().get() // Discord answer IDs don't match those on Matrix-created polls.
|
|
||||||
assert(realAnswer)
|
|
||||||
db.prepare("DELETE FROM poll_vote WHERE discord_or_matrix_user_id = ? AND message_id = ? AND matrix_option = ?").run(data.user_id, data.message_id, realAnswer)
|
|
||||||
return debounceSendVotes(data, pollEventID)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Multiple-choice polls send all the votes at the same time. This debounces and sends the combined votes.
|
|
||||||
* In the meantime, the combined votes are assembled in the `poll_vote` database table by the above functions.
|
|
||||||
* @param {import("discord-api-types/v10").GatewayMessagePollVoteAddDispatch["d"]} data
|
|
||||||
* @param {string} pollEventID
|
|
||||||
* @return {Promise<string>} event ID of Matrix vote
|
|
||||||
*/
|
|
||||||
async function debounceSendVotes(data, pollEventID) {
|
|
||||||
return await inFlightPollSema.request(async () => {
|
|
||||||
await scheduler.wait(1000) // Wait for votes to be collected
|
|
||||||
|
|
||||||
const user = await discord.snow.user.getUser(data.user_id) // Gateway event doesn't give us the object, only the ID.
|
|
||||||
return await sendVotes(user, data.channel_id, data.message_id, pollEventID)
|
|
||||||
}, `${data.user_id}/${data.message_id}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {DiscordTypes.APIUser | string} userOrID
|
|
||||||
* @param {string} channelID
|
|
||||||
* @param {string} pollMessageID
|
|
||||||
* @param {string} pollEventID
|
|
||||||
*/
|
|
||||||
async function sendVotes(userOrID, channelID, pollMessageID, pollEventID) {
|
|
||||||
const latestRoomID = select("channel_room", "room_id", {channel_id: channelID}).pluck().get()
|
|
||||||
const matchingRoomID = from("message_room").join("historical_channel_room", "historical_room_index").where({message_id: pollMessageID}).pluck("room_id").get()
|
|
||||||
if (!latestRoomID || latestRoomID !== matchingRoomID) { // room upgrade mid-poll??
|
|
||||||
db.prepare("UPDATE poll SET is_closed = 1 WHERE message_id = ?").run(pollMessageID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let userID, senderMxid
|
|
||||||
if (typeof userOrID === "string") { // just a string when double-checking a vote removal - good thing the unvoter is already here from having voted
|
|
||||||
userID = userOrID
|
|
||||||
senderMxid = from("sim").join("sim_member", "mxid").where({user_id: userOrID, room_id: matchingRoomID}).pluck("mxid").get()
|
|
||||||
if (!senderMxid) return
|
|
||||||
} else { // sent in full when double-checking adding a vote, so we can properly ensure joined
|
|
||||||
userID = userOrID.id
|
|
||||||
senderMxid = await registerUser.ensureSimJoined(userOrID, matchingRoomID)
|
|
||||||
}
|
|
||||||
|
|
||||||
const answersArray = select("poll_vote", "matrix_option", {discord_or_matrix_user_id: userID, message_id: pollMessageID}).pluck().all()
|
|
||||||
const eventID = await api.sendEvent(matchingRoomID, "org.matrix.msc3381.poll.response", {
|
|
||||||
"m.relates_to": {
|
|
||||||
rel_type: "m.reference",
|
|
||||||
event_id: pollEventID,
|
|
||||||
},
|
|
||||||
"org.matrix.msc3381.poll.response": {
|
|
||||||
answers: answersArray
|
|
||||||
}
|
|
||||||
}, senderMxid)
|
|
||||||
|
|
||||||
return eventID
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports.addVote = addVote
|
|
||||||
module.exports.removeVote = removeVote
|
|
||||||
module.exports.debounceSendVotes = debounceSendVotes
|
|
||||||
module.exports.sendVotes = sendVotes
|
|
||||||
|
|
@ -3,9 +3,10 @@
|
||||||
const assert = require("assert")
|
const assert = require("assert")
|
||||||
const {reg} = require("../../matrix/read-registration")
|
const {reg} = require("../../matrix/read-registration")
|
||||||
const Ty = require("../../types")
|
const Ty = require("../../types")
|
||||||
|
const fetch = require("node-fetch").default
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
const passthrough = require("../../passthrough")
|
||||||
const {sync, db, select, from} = passthrough
|
const {discord, sync, db, select} = passthrough
|
||||||
/** @type {import("../../matrix/api")} */
|
/** @type {import("../../matrix/api")} */
|
||||||
const api = sync.require("../../matrix/api")
|
const api = sync.require("../../matrix/api")
|
||||||
/** @type {import("../../matrix/file")} */
|
/** @type {import("../../matrix/file")} */
|
||||||
|
|
@ -13,20 +14,12 @@ const file = sync.require("../../matrix/file")
|
||||||
/** @type {import("./register-user")} */
|
/** @type {import("./register-user")} */
|
||||||
const registerUser = sync.require("./register-user")
|
const registerUser = sync.require("./register-user")
|
||||||
|
|
||||||
/** @returns {Promise<Ty.PkMessage>} */
|
/**
|
||||||
async function fetchMessage(messageID) {
|
* @typedef WebhookAuthor Discord API message->author. A webhook as an author.
|
||||||
try {
|
* @prop {string} username
|
||||||
var res = await fetch(`https://api.pluralkit.me/v2/messages/${messageID}`)
|
* @prop {string?} avatar
|
||||||
} catch (networkError) {
|
* @prop {string} id
|
||||||
// Network issue, raise a more readable message
|
*/
|
||||||
throw new Error(`Failed to connect to PK API: ${networkError.toString()}`)
|
|
||||||
}
|
|
||||||
if (!res.ok) throw new Error(`PK API returned an error: ${await res.text()}`)
|
|
||||||
/** @type {any} */
|
|
||||||
const root = await res.json()
|
|
||||||
if (!root.member) throw new Error(`PK API didn't return member data: ${JSON.stringify(root)}`)
|
|
||||||
return root
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A sim is an account that is being simulated by the bridge to copy events from the other side.
|
* A sim is an account that is being simulated by the bridge to copy events from the other side.
|
||||||
|
|
@ -40,7 +33,7 @@ async function createSim(pkMessage) {
|
||||||
const mxid = `@${localpart}:${reg.ooye.server_name}`
|
const mxid = `@${localpart}:${reg.ooye.server_name}`
|
||||||
|
|
||||||
// Save chosen name in the database forever
|
// Save chosen name in the database forever
|
||||||
db.prepare("INSERT INTO sim (user_id, username, sim_name, mxid) VALUES (?, ?, ?, ?)").run(pkMessage.member.uuid, simName, simName, mxid)
|
db.prepare("INSERT INTO sim (user_id, sim_name, localpart, mxid) VALUES (?, ?, ?, ?)").run(pkMessage.member.uuid, simName, localpart, mxid)
|
||||||
|
|
||||||
// Register matrix user with that name
|
// Register matrix user with that name
|
||||||
try {
|
try {
|
||||||
|
|
@ -87,17 +80,24 @@ async function ensureSimJoined(pkMessage, roomID) {
|
||||||
// Ensure joined
|
// Ensure joined
|
||||||
const existing = select("sim_member", "mxid", {room_id: roomID, mxid}).pluck().get()
|
const existing = select("sim_member", "mxid", {room_id: roomID, mxid}).pluck().get()
|
||||||
if (!existing) {
|
if (!existing) {
|
||||||
|
try {
|
||||||
await api.inviteToRoom(roomID, mxid)
|
await api.inviteToRoom(roomID, mxid)
|
||||||
await api.joinRoom(roomID, mxid)
|
await api.joinRoom(roomID, mxid)
|
||||||
|
} catch (e) {
|
||||||
|
if (e.message.includes("is already in the room.")) {
|
||||||
|
// Sweet!
|
||||||
|
} else {
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
db.prepare("INSERT OR IGNORE INTO sim_member (room_id, mxid) VALUES (?, ?)").run(roomID, mxid)
|
db.prepare("INSERT OR IGNORE INTO sim_member (room_id, mxid) VALUES (?, ?)").run(roomID, mxid)
|
||||||
}
|
}
|
||||||
return mxid
|
return mxid
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate profile data based on webhook displayname and configured avatar.
|
|
||||||
* @param {Ty.PkMessage} pkMessage
|
* @param {Ty.PkMessage} pkMessage
|
||||||
* @param {Ty.WebhookAuthor} author
|
* @param {WebhookAuthor} author
|
||||||
*/
|
*/
|
||||||
async function memberToStateContent(pkMessage, author) {
|
async function memberToStateContent(pkMessage, author) {
|
||||||
// We prefer to use the member's avatar URL data since the image upload can be cached across channels,
|
// We prefer to use the member's avatar URL data since the image upload can be cached across channels,
|
||||||
|
|
@ -116,40 +116,49 @@ async function memberToStateContent(pkMessage, author) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sync profile data for a sim user. This function follows the following process:
|
* Sync profile data for a sim user. This function follows the following process:
|
||||||
* 1. Look up data about proxy user from API
|
* 1. Join the sim to the room if needed
|
||||||
* 2. If this fails, try to use previously cached data (won't sync)
|
* 2. Make an object of what the new room member state content would be, including uploading the profile picture if it hasn't been done before
|
||||||
* 3. Create and join the sim to the room if needed
|
* 3. Compare against the previously known state content, which is helpfully stored in the database
|
||||||
* 4. Make an object of what the new room member state content would be, including uploading the profile picture if it hasn't been done before
|
* 4. If the state content has changed, send it to Matrix and update it in the database for next time
|
||||||
* 5. Compare against the previously known state content, which is helpfully stored in the database
|
* @param {WebhookAuthor} author
|
||||||
* 6. If the state content has changed, send it to Matrix and update it in the database for next time
|
* @param {Ty.PkMessage} pkMessage
|
||||||
* @param {string} messageID to call API with
|
* @param {string} roomID
|
||||||
* @param {Ty.WebhookAuthor} author for profile data
|
|
||||||
* @param {string} roomID room to join member to
|
|
||||||
* @param {boolean} shouldActuallySync whether to actually sync updated user data or just ensure it's joined
|
|
||||||
* @returns {Promise<string>} mxid of the updated sim
|
* @returns {Promise<string>} mxid of the updated sim
|
||||||
*/
|
*/
|
||||||
async function syncUser(messageID, author, roomID, shouldActuallySync) {
|
async function syncUser(author, pkMessage, roomID) {
|
||||||
try {
|
|
||||||
// API lookup
|
|
||||||
var pkMessage = await fetchMessage(messageID)
|
|
||||||
db.prepare("REPLACE INTO sim_proxy (user_id, proxy_owner_id, displayname) VALUES (?, ?, ?)").run(pkMessage.member.uuid, pkMessage.sender, author.username)
|
|
||||||
} catch (e) {
|
|
||||||
// Fall back to offline cache
|
|
||||||
const senderMxid = from("sim_proxy").join("sim", "user_id").join("sim_member", "mxid").where({displayname: author.username, room_id: roomID}).pluck("mxid").get()
|
|
||||||
if (!senderMxid) throw e
|
|
||||||
return senderMxid
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create and join the sim to the room if needed
|
|
||||||
const mxid = await ensureSimJoined(pkMessage, roomID)
|
const mxid = await ensureSimJoined(pkMessage, roomID)
|
||||||
|
// Update the sim_proxy table, so mentions can look up the original sender later
|
||||||
if (shouldActuallySync) {
|
db.prepare("INSERT OR IGNORE INTO sim_proxy (user_id, proxy_owner_id, displayname) VALUES (?, ?, ?)").run(pkMessage.member.uuid, pkMessage.sender, author.username)
|
||||||
// Build current profile data and sync if the hash has changed
|
// Sync the member state
|
||||||
const content = await memberToStateContent(pkMessage, author)
|
const content = await memberToStateContent(pkMessage, author)
|
||||||
await registerUser._sendSyncUser(roomID, mxid, content, null)
|
const currentHash = registerUser._hashProfileContent(content, 0)
|
||||||
|
const existingHash = select("sim_member", "hashed_profile_content", {room_id: roomID, mxid}).safeIntegers().pluck().get()
|
||||||
|
// only do the actual sync if the hash has changed since we last looked
|
||||||
|
if (existingHash !== currentHash) {
|
||||||
|
await api.sendState(roomID, "m.room.member", mxid, content, mxid)
|
||||||
|
db.prepare("UPDATE sim_member SET hashed_profile_content = ? WHERE room_id = ? AND mxid = ?").run(currentHash, roomID, mxid)
|
||||||
}
|
}
|
||||||
|
|
||||||
return mxid
|
return mxid
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @returns {Promise<Ty.PkMessage>} */
|
||||||
|
async function fetchMessage(messageID) {
|
||||||
|
// Their backend is weird. Sometimes it says "message not found" (code 20006) on the first try, so we make multiple attempts.
|
||||||
|
let attempts = 0
|
||||||
|
do {
|
||||||
|
var res = await fetch(`https://api.pluralkit.me/v2/messages/${messageID}`)
|
||||||
|
if (res.ok) return res.json()
|
||||||
|
|
||||||
|
// I think the backend needs some time to update.
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 2000))
|
||||||
|
} while (++attempts < 3)
|
||||||
|
|
||||||
|
const errorMessage = await res.json()
|
||||||
|
throw new Error(`PK API returned an error after ${attempts} tries: ${JSON.stringify(errorMessage)}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports._memberToStateContent = memberToStateContent
|
||||||
|
module.exports.ensureSim = ensureSim
|
||||||
|
module.exports.ensureSimJoined = ensureSimJoined
|
||||||
module.exports.syncUser = syncUser
|
module.exports.syncUser = syncUser
|
||||||
|
module.exports.fetchMessage = fetchMessage
|
||||||
|
|
|
||||||
|
|
@ -3,29 +3,23 @@
|
||||||
const assert = require("assert").strict
|
const assert = require("assert").strict
|
||||||
const {reg} = require("../../matrix/read-registration")
|
const {reg} = require("../../matrix/read-registration")
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
const DiscordTypes = require("discord-api-types/v10")
|
||||||
const Ty = require("../../types")
|
const mixin = require("@cloudrac3r/mixin-deep")
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
const passthrough = require("../../passthrough")
|
||||||
const {discord, sync, db, from, select} = passthrough
|
const {discord, sync, db, select} = passthrough
|
||||||
/** @type {import("../../matrix/api")} */
|
/** @type {import("../../matrix/api")} */
|
||||||
const api = sync.require("../../matrix/api")
|
const api = sync.require("../../matrix/api")
|
||||||
/** @type {import("../../matrix/file")} */
|
/** @type {import("../../matrix/file")} */
|
||||||
const file = sync.require("../../matrix/file")
|
const file = sync.require("../../matrix/file")
|
||||||
/** @type {import("../../discord/utils")} */
|
/** @type {import("../../discord/utils")} */
|
||||||
const dUtils = sync.require("../../discord/utils")
|
const utils = sync.require("../../discord/utils")
|
||||||
/** @type {import("../../matrix/utils")} */
|
|
||||||
const mxUtils = sync.require("../../matrix/utils")
|
|
||||||
/** @type {import("../converters/user-to-mxid")} */
|
/** @type {import("../converters/user-to-mxid")} */
|
||||||
const userToMxid = sync.require("../converters/user-to-mxid")
|
const userToMxid = sync.require("../converters/user-to-mxid")
|
||||||
/** @type {import("./create-room")} */
|
|
||||||
const createRoom = sync.require("./create-room")
|
|
||||||
/** @type {import("xxhash-wasm").XXHashAPI} */ // @ts-ignore
|
/** @type {import("xxhash-wasm").XXHashAPI} */ // @ts-ignore
|
||||||
let hasher = null
|
let hasher = null
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
require("xxhash-wasm")().then(h => hasher = h)
|
require("xxhash-wasm")().then(h => hasher = h)
|
||||||
|
|
||||||
const supportsMsc4069 = api.versions().then(v => !!v?.unstable_features?.["org.matrix.msc4069"]).catch(() => false)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A sim is an account that is being simulated by the bridge to copy events from the other side.
|
* A sim is an account that is being simulated by the bridge to copy events from the other side.
|
||||||
* @param {DiscordTypes.APIUser} user
|
* @param {DiscordTypes.APIUser} user
|
||||||
|
|
@ -39,7 +33,7 @@ async function createSim(user) {
|
||||||
|
|
||||||
// Save chosen name in the database forever
|
// Save chosen name in the database forever
|
||||||
// Making this database change right away so that in a concurrent registration, the 2nd registration will already have generated a different localpart because it can see this row when it generates
|
// Making this database change right away so that in a concurrent registration, the 2nd registration will already have generated a different localpart because it can see this row when it generates
|
||||||
db.prepare("INSERT INTO sim (user_id, username, sim_name, mxid) VALUES (?, ?, ?, ?)").run(user.id, user.username, simName, mxid)
|
db.prepare("INSERT INTO sim (user_id, sim_name, localpart, mxid) VALUES (?, ?, ?, ?)").run(user.id, simName, localpart, mxid)
|
||||||
|
|
||||||
// Register matrix user with that name
|
// Register matrix user with that name
|
||||||
try {
|
try {
|
||||||
|
|
@ -86,8 +80,16 @@ async function ensureSimJoined(user, roomID) {
|
||||||
// Ensure joined
|
// Ensure joined
|
||||||
const existing = select("sim_member", "mxid", {room_id: roomID, mxid}).pluck().get()
|
const existing = select("sim_member", "mxid", {room_id: roomID, mxid}).pluck().get()
|
||||||
if (!existing) {
|
if (!existing) {
|
||||||
|
try {
|
||||||
await api.inviteToRoom(roomID, mxid)
|
await api.inviteToRoom(roomID, mxid)
|
||||||
await api.joinRoom(roomID, mxid)
|
await api.joinRoom(roomID, mxid)
|
||||||
|
} catch (e) {
|
||||||
|
if (e.message.includes("is already in the room.")) {
|
||||||
|
// Sweet!
|
||||||
|
} else {
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
db.prepare("INSERT OR IGNORE INTO sim_member (room_id, mxid) VALUES (?, ?)").run(roomID, mxid)
|
db.prepare("INSERT OR IGNORE INTO sim_member (room_id, mxid) VALUES (?, ?)").run(roomID, mxid)
|
||||||
}
|
}
|
||||||
return mxid
|
return mxid
|
||||||
|
|
@ -95,29 +97,12 @@ async function ensureSimJoined(user, roomID) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {DiscordTypes.APIUser} user
|
* @param {DiscordTypes.APIUser} user
|
||||||
*/
|
* @param {Omit<DiscordTypes.APIGuildMember, "user">} member
|
||||||
async function userToGlobalProfile(user) {
|
|
||||||
const globalProfile = {}
|
|
||||||
|
|
||||||
globalProfile.displayname = user.username
|
|
||||||
if (user.global_name) globalProfile.displayname = user.global_name
|
|
||||||
|
|
||||||
if (user.avatar) {
|
|
||||||
const avatarPath = file.userAvatar(user) // the user avatar only
|
|
||||||
globalProfile.avatar_url = await file.uploadDiscordFileToMxc(avatarPath)
|
|
||||||
}
|
|
||||||
|
|
||||||
return globalProfile
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {DiscordTypes.APIUser} user
|
|
||||||
* @param {Omit<DiscordTypes.APIGuildMember, "user"> | undefined} member
|
|
||||||
*/
|
*/
|
||||||
async function memberToStateContent(user, member, guildID) {
|
async function memberToStateContent(user, member, guildID) {
|
||||||
let displayname = user.username
|
let displayname = user.username
|
||||||
if (user.global_name) displayname = user.global_name
|
if (user.global_name) displayname = user.global_name
|
||||||
if (member?.nick) displayname = member.nick
|
if (member.nick) displayname = member.nick
|
||||||
|
|
||||||
const content = {
|
const content = {
|
||||||
displayname,
|
displayname,
|
||||||
|
|
@ -132,7 +117,7 @@ async function memberToStateContent(user, member, guildID) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (member?.avatar || user.avatar) {
|
if (member.avatar || user.avatar) {
|
||||||
// const avatarPath = file.userAvatar(user) // the user avatar only
|
// const avatarPath = file.userAvatar(user) // the user avatar only
|
||||||
const avatarPath = file.memberAvatar(guildID, user, member) // the member avatar or the user avatar
|
const avatarPath = file.memberAvatar(guildID, user, member) // the member avatar or the user avatar
|
||||||
content["moe.cadence.ooye.member"].avatar = avatarPath
|
content["moe.cadence.ooye.member"].avatar = avatarPath
|
||||||
|
|
@ -145,16 +130,13 @@ async function memberToStateContent(user, member, guildID) {
|
||||||
/**
|
/**
|
||||||
* https://gitdab.com/cadence/out-of-your-element/issues/9
|
* https://gitdab.com/cadence/out-of-your-element/issues/9
|
||||||
* @param {DiscordTypes.APIUser} user
|
* @param {DiscordTypes.APIUser} user
|
||||||
* @param {Omit<DiscordTypes.APIGuildMember, "user"> | undefined} member
|
* @param {Omit<DiscordTypes.APIGuildMember, "user">} member
|
||||||
* @param {DiscordTypes.APIGuild} guild
|
* @param {DiscordTypes.APIGuild} guild
|
||||||
* @param {DiscordTypes.APIGuildChannel} channel
|
* @param {DiscordTypes.APIGuildChannel} channel
|
||||||
* @returns {number} 0 to 100
|
* @returns {number} 0 to 100
|
||||||
*/
|
*/
|
||||||
function memberToPowerLevel(user, member, guild, channel) {
|
function memberToPowerLevel(user, member, guild, channel) {
|
||||||
if (!member) return 0
|
const permissions = utils.getPermissions(member.roles, guild.roles, user.id, channel.permission_overwrites)
|
||||||
|
|
||||||
const permissions = dUtils.getPermissions(guild.id, member.roles, guild.roles, user.id, channel.permission_overwrites)
|
|
||||||
const everyonePermissions = dUtils.getPermissions(guild.id, [], guild.roles, undefined, channel.permission_overwrites)
|
|
||||||
/*
|
/*
|
||||||
* PL 100 = Administrator = People who can brick the room. RATIONALE:
|
* PL 100 = Administrator = People who can brick the room. RATIONALE:
|
||||||
* - Administrator.
|
* - Administrator.
|
||||||
|
|
@ -163,7 +145,7 @@ function memberToPowerLevel(user, member, guild, channel) {
|
||||||
* - Manage Channels: People who can manage the channel can delete it.
|
* - Manage Channels: People who can manage the channel can delete it.
|
||||||
* (Setting sim users to PL 100 is safe because even though we can't demote the sims we can use code to make the sims demote themselves.)
|
* (Setting sim users to PL 100 is safe because even though we can't demote the sims we can use code to make the sims demote themselves.)
|
||||||
*/
|
*/
|
||||||
if (guild.owner_id === user.id || dUtils.hasSomePermissions(permissions, ["Administrator", "ManageWebhooks", "ManageGuild", "ManageChannels"])) return 100
|
if (guild.owner_id === user.id || utils.hasSomePermissions(permissions, ["Administrator", "ManageWebhooks", "ManageGuild", "ManageChannels"])) return 100
|
||||||
/*
|
/*
|
||||||
* PL 50 = Moderator = People who can manage people and messages in many ways. RATIONALE:
|
* PL 50 = Moderator = People who can manage people and messages in many ways. RATIONALE:
|
||||||
* - Manage Messages: Can moderate by pinning or deleting the conversation.
|
* - Manage Messages: Can moderate by pinning or deleting the conversation.
|
||||||
|
|
@ -173,19 +155,9 @@ function memberToPowerLevel(user, member, guild, channel) {
|
||||||
* - Mute Members & Deafen Members: Can moderate by silencing disruptive people in ways they can't undo.
|
* - Mute Members & Deafen Members: Can moderate by silencing disruptive people in ways they can't undo.
|
||||||
* - Moderate Members.
|
* - Moderate Members.
|
||||||
*/
|
*/
|
||||||
if (dUtils.hasSomePermissions(permissions, ["ManageMessages", "ManageNicknames", "ManageThreads", "KickMembers", "BanMembers", "MuteMembers", "DeafenMembers", "ModerateMembers"])) return 50
|
if (utils.hasSomePermissions(permissions, ["ManageMessages", "ManageNicknames", "ManageThreads", "KickMembers", "BanMembers", "MuteMembers", "DeafenMembers", "ModerateMembers"])) return 50
|
||||||
/* PL 50 = if room is read-only but the user has been specially allowed to send messages */
|
|
||||||
const everyoneCanSend = dUtils.hasPermission(everyonePermissions, DiscordTypes.PermissionFlagsBits.SendMessages)
|
|
||||||
const userCanSend = dUtils.hasPermission(permissions, DiscordTypes.PermissionFlagsBits.SendMessages)
|
|
||||||
if (!everyoneCanSend && userCanSend) return createRoom.READ_ONLY_ROOM_EVENTS_DEFAULT_POWER
|
|
||||||
/* PL 20 = Mention Everyone for technical reasons. */
|
/* PL 20 = Mention Everyone for technical reasons. */
|
||||||
const everyoneCanMentionEveryone = dUtils.hasPermission(everyonePermissions, DiscordTypes.PermissionFlagsBits.MentionEveryone)
|
if (utils.hasSomePermissions(permissions, ["MentionEveryone"])) return 20
|
||||||
const userCanMentionEveryone = dUtils.hasPermission(permissions, DiscordTypes.PermissionFlagsBits.MentionEveryone)
|
|
||||||
if (!everyoneCanMentionEveryone && userCanMentionEveryone) return 20
|
|
||||||
/* PL 10 = Create Polls for technical reasons. */
|
|
||||||
const everyoneCanCreatePolls = dUtils.hasPermission(everyonePermissions, DiscordTypes.PermissionFlagsBits.SendPolls)
|
|
||||||
const userCanCreatePolls = dUtils.hasPermission(permissions, DiscordTypes.PermissionFlagsBits.SendPolls)
|
|
||||||
if (!everyoneCanCreatePolls && userCanCreatePolls) return 10
|
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -207,7 +179,7 @@ function _hashProfileContent(content, powerLevel) {
|
||||||
* 4. Compare against the previously known state content, which is helpfully stored in the database
|
* 4. Compare against the previously known state content, which is helpfully stored in the database
|
||||||
* 5. If the state content or power level have changed, send them to Matrix and update them in the database for next time
|
* 5. If the state content or power level have changed, send them to Matrix and update them in the database for next time
|
||||||
* @param {DiscordTypes.APIUser} user
|
* @param {DiscordTypes.APIUser} user
|
||||||
* @param {Omit<DiscordTypes.APIGuildMember, "user"> | undefined} member
|
* @param {Omit<DiscordTypes.APIGuildMember, "user">} member
|
||||||
* @param {DiscordTypes.APIGuildChannel} channel
|
* @param {DiscordTypes.APIGuildChannel} channel
|
||||||
* @param {DiscordTypes.APIGuild} guild
|
* @param {DiscordTypes.APIGuild} guild
|
||||||
* @param {string} roomID
|
* @param {string} roomID
|
||||||
|
|
@ -217,53 +189,58 @@ async function syncUser(user, member, channel, guild, roomID) {
|
||||||
const mxid = await ensureSimJoined(user, roomID)
|
const mxid = await ensureSimJoined(user, roomID)
|
||||||
const content = await memberToStateContent(user, member, guild.id)
|
const content = await memberToStateContent(user, member, guild.id)
|
||||||
const powerLevel = memberToPowerLevel(user, member, guild, channel)
|
const powerLevel = memberToPowerLevel(user, member, guild, channel)
|
||||||
await _sendSyncUser(roomID, mxid, content, powerLevel, {
|
const currentHash = _hashProfileContent(content, powerLevel)
|
||||||
// do not overwrite pre-existing data if we already have data and `member` is not accessible, because this would replace good data with bad data
|
const existingHash = select("sim_member", "hashed_profile_content", {room_id: roomID, mxid}).safeIntegers().pluck().get()
|
||||||
allowOverwrite: !!member,
|
// only do the actual sync if the hash has changed since we last looked
|
||||||
globalProfile: await userToGlobalProfile(user)
|
if (existingHash !== currentHash) {
|
||||||
})
|
// Update room member state
|
||||||
|
await api.sendState(roomID, "m.room.member", mxid, content, mxid)
|
||||||
|
// Update power levels
|
||||||
|
const powerLevelsStateContent = await api.getStateEvent(roomID, "m.room.power_levels", "")
|
||||||
|
const oldPowerLevel = powerLevelsStateContent.users?.[mxid] || 0
|
||||||
|
mixin(powerLevelsStateContent, {users: {[mxid]: powerLevel}})
|
||||||
|
if (powerLevel === 0) delete powerLevelsStateContent.users[mxid] // keep the event compact
|
||||||
|
const sendPowerLevelAs = powerLevel < oldPowerLevel ? mxid : undefined // bridge bot won't not have permission to demote equal power users, so do this action as themselves
|
||||||
|
await api.sendState(roomID, "m.room.power_levels", "", powerLevelsStateContent, sendPowerLevelAs)
|
||||||
|
// Update cached hash
|
||||||
|
db.prepare("UPDATE sim_member SET hashed_profile_content = ? WHERE room_id = ? AND mxid = ?").run(currentHash, roomID, mxid)
|
||||||
|
}
|
||||||
return mxid
|
return mxid
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* Sync profile data for a webhook user. The _ooye_webhook name will always be reused.
|
||||||
|
* 1. Join the sim to the room if needed
|
||||||
|
* 2. Make an object of what the new room member state content would be, including uploading the profile picture if it hasn't been done before
|
||||||
|
* 4. Compare against the previously known state content, which is helpfully stored in the database
|
||||||
|
* 5. If the state content has changed, send it to Matrix and update it in the database for next time
|
||||||
|
* @param {DiscordTypes.APIUser} user
|
||||||
|
* @param {DiscordTypes.APIGuildChannel} channel
|
||||||
|
* @param {DiscordTypes.APIGuild} guild
|
||||||
* @param {string} roomID
|
* @param {string} roomID
|
||||||
* @param {string} mxid
|
* @returns {Promise<string>} mxid of the updated sim
|
||||||
* @param {{displayname: string, avatar_url?: string}} content
|
|
||||||
* @param {number | null} powerLevel
|
|
||||||
* @param {{allowOverwrite?: boolean, globalProfile?: {displayname: string, avatar_url?: string}}} [options]
|
|
||||||
*/
|
*/
|
||||||
async function _sendSyncUser(roomID, mxid, content, powerLevel, options) {
|
async function syncWebhook(user, channel, guild, roomID) {
|
||||||
const currentHash = _hashProfileContent(content, powerLevel ?? 0)
|
const mxid = await ensureSimJoined(user, roomID)
|
||||||
|
// @ts-ignore
|
||||||
|
const content = await memberToStateContent(user, {}, guild.id)
|
||||||
|
const currentHash = _hashProfileContent(content, 0)
|
||||||
const existingHash = select("sim_member", "hashed_profile_content", {room_id: roomID, mxid}).safeIntegers().pluck().get()
|
const existingHash = select("sim_member", "hashed_profile_content", {room_id: roomID, mxid}).safeIntegers().pluck().get()
|
||||||
// only do the actual sync if the hash has changed since we last looked
|
// only do the actual sync if the hash has changed since we last looked
|
||||||
const hashHasChanged = existingHash !== currentHash
|
if (existingHash !== currentHash) {
|
||||||
// always okay to add new data. for overwriting, restrict based on options.allowOverwrite, if present
|
|
||||||
const overwriteOkay = !existingHash || (options?.allowOverwrite ?? true)
|
|
||||||
if (hashHasChanged && overwriteOkay) {
|
|
||||||
const actions = []
|
|
||||||
// Update room member state
|
// Update room member state
|
||||||
actions.push(api.sendState(roomID, "m.room.member", mxid, content, mxid))
|
await api.sendState(roomID, "m.room.member", mxid, content, mxid)
|
||||||
// Update power levels
|
|
||||||
if (powerLevel != null) {
|
|
||||||
actions.push(mxUtils.setUserPower(roomID, mxid, powerLevel, api))
|
|
||||||
}
|
|
||||||
// Update global profile (if supported by server)
|
|
||||||
if (await supportsMsc4069) {
|
|
||||||
actions.push(api.profileSetDisplayname(mxid, options?.globalProfile?.displayname || content.displayname, true))
|
|
||||||
actions.push(api.profileSetAvatarUrl(mxid, options?.globalProfile?.avatar_url || content.avatar_url, true))
|
|
||||||
}
|
|
||||||
await Promise.all(actions)
|
|
||||||
// Update cached hash
|
// Update cached hash
|
||||||
db.prepare("UPDATE sim_member SET hashed_profile_content = ? WHERE room_id = ? AND mxid = ?").run(currentHash, roomID, mxid)
|
db.prepare("UPDATE sim_member SET hashed_profile_content = ? WHERE room_id = ? AND mxid = ?").run(currentHash, roomID, mxid)
|
||||||
}
|
}
|
||||||
|
return mxid
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {string} roomID
|
* @param {string} roomID
|
||||||
*/
|
*/
|
||||||
async function syncAllUsersInRoom(roomID) {
|
async function syncAllUsersInRoom(roomID) {
|
||||||
const users = from("sim_member").join("sim", "mxid")
|
const mxids = select("sim_member", "mxid", {room_id: roomID}).pluck().all()
|
||||||
.where({room_id: roomID}).and("and user_id not like '%-%' and user_id not like '%\\_%' escape '\\'").pluck("user_id").all()
|
|
||||||
|
|
||||||
const channelID = select("channel_room", "channel_id", {room_id: roomID}).pluck().get()
|
const channelID = select("channel_room", "channel_id", {room_id: roomID}).pluck().get()
|
||||||
assert.ok(typeof channelID === "string")
|
assert.ok(typeof channelID === "string")
|
||||||
|
|
@ -275,7 +252,10 @@ async function syncAllUsersInRoom(roomID) {
|
||||||
/** @ts-ignore @type {DiscordTypes.APIGuild} */
|
/** @ts-ignore @type {DiscordTypes.APIGuild} */
|
||||||
const guild = discord.guilds.get(guildID)
|
const guild = discord.guilds.get(guildID)
|
||||||
|
|
||||||
for (const userID of users) {
|
for (const mxid of mxids) {
|
||||||
|
const userID = select("sim", "user_id", {mxid}).pluck().get()
|
||||||
|
assert.ok(typeof userID === "string")
|
||||||
|
|
||||||
/** @ts-ignore @type {Required<DiscordTypes.APIGuildMember>} */
|
/** @ts-ignore @type {Required<DiscordTypes.APIGuildMember>} */
|
||||||
const member = await discord.snow.guild.getGuildMember(guildID, userID)
|
const member = await discord.snow.guild.getGuildMember(guildID, userID)
|
||||||
/** @ts-ignore @type {Required<DiscordTypes.APIUser>} user */
|
/** @ts-ignore @type {Required<DiscordTypes.APIUser>} user */
|
||||||
|
|
@ -292,7 +272,5 @@ module.exports._hashProfileContent = _hashProfileContent
|
||||||
module.exports.ensureSim = ensureSim
|
module.exports.ensureSim = ensureSim
|
||||||
module.exports.ensureSimJoined = ensureSimJoined
|
module.exports.ensureSimJoined = ensureSimJoined
|
||||||
module.exports.syncUser = syncUser
|
module.exports.syncUser = syncUser
|
||||||
module.exports._sendSyncUser = _sendSyncUser
|
module.exports.syncWebhook = syncWebhook
|
||||||
module.exports.syncAllUsersInRoom = syncAllUsersInRoom
|
module.exports.syncAllUsersInRoom = syncAllUsersInRoom
|
||||||
module.exports._memberToPowerLevel = memberToPowerLevel
|
|
||||||
module.exports.supportsMsc4069 = supportsMsc4069
|
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,10 @@
|
||||||
const {_memberToStateContent, _memberToPowerLevel} = require("./register-user")
|
const {_memberToStateContent} = require("./register-user")
|
||||||
const {test} = require("supertape")
|
const {test} = require("supertape")
|
||||||
const data = require("../../../test/data")
|
const testData = require("../../../test/data")
|
||||||
const mixin = require("@cloudrac3r/mixin-deep")
|
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
|
||||||
|
|
||||||
test("member2state: without member nick or avatar", async t => {
|
test("member2state: without member nick or avatar", async t => {
|
||||||
t.deepEqual(
|
t.deepEqual(
|
||||||
await _memberToStateContent(data.member.kumaccino.user, data.member.kumaccino, data.guild.general.id),
|
await _memberToStateContent(testData.member.kumaccino.user, testData.member.kumaccino, testData.guild.general.id),
|
||||||
{
|
{
|
||||||
avatar_url: "mxc://cadence.moe/UpAeIqeclhKfeiZNdIWNcXXL",
|
avatar_url: "mxc://cadence.moe/UpAeIqeclhKfeiZNdIWNcXXL",
|
||||||
displayname: "kumaccino",
|
displayname: "kumaccino",
|
||||||
|
|
@ -26,7 +24,7 @@ test("member2state: without member nick or avatar", async t => {
|
||||||
|
|
||||||
test("member2state: with global name, without member nick or avatar", async t => {
|
test("member2state: with global name, without member nick or avatar", async t => {
|
||||||
t.deepEqual(
|
t.deepEqual(
|
||||||
await _memberToStateContent(data.member.papiophidian.user, data.member.papiophidian, data.guild.general.id),
|
await _memberToStateContent(testData.member.papiophidian.user, testData.member.papiophidian, testData.guild.general.id),
|
||||||
{
|
{
|
||||||
avatar_url: "mxc://cadence.moe/JPzSmALLirnIprlSMKohSSoX",
|
avatar_url: "mxc://cadence.moe/JPzSmALLirnIprlSMKohSSoX",
|
||||||
displayname: "PapiOphidian",
|
displayname: "PapiOphidian",
|
||||||
|
|
@ -46,7 +44,7 @@ test("member2state: with global name, without member nick or avatar", async t =>
|
||||||
|
|
||||||
test("member2state: with member nick and avatar", async t => {
|
test("member2state: with member nick and avatar", async t => {
|
||||||
t.deepEqual(
|
t.deepEqual(
|
||||||
await _memberToStateContent(data.member.sheep.user, data.member.sheep, data.guild.general.id),
|
await _memberToStateContent(testData.member.sheep.user, testData.member.sheep, testData.guild.general.id),
|
||||||
{
|
{
|
||||||
avatar_url: "mxc://cadence.moe/rfemHmAtcprjLEiPiEuzPhpl",
|
avatar_url: "mxc://cadence.moe/rfemHmAtcprjLEiPiEuzPhpl",
|
||||||
displayname: "The Expert's Submarine",
|
displayname: "The Expert's Submarine",
|
||||||
|
|
@ -63,64 +61,3 @@ test("member2state: with member nick and avatar", async t => {
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("member2power: default to zero if member roles unknown", async t => {
|
|
||||||
const power = _memberToPowerLevel(data.user.clyde_ai, null, data.guild.data_horde, data.channel.saving_the_world)
|
|
||||||
t.equal(power, 0)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("member2power: unremarkable = 0", async t => {
|
|
||||||
const power = _memberToPowerLevel(data.user.clyde_ai, {
|
|
||||||
roles: []
|
|
||||||
}, data.guild.data_horde, data.channel.general)
|
|
||||||
t.equal(power, 0)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("member2power: can mention everyone = 20", async t => {
|
|
||||||
const power = _memberToPowerLevel(data.user.clyde_ai, {
|
|
||||||
roles: ["684524730274807911"]
|
|
||||||
}, data.guild.data_horde, data.channel.general)
|
|
||||||
t.equal(power, 20)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("member2power: can send messages in protected channel due to role = 50", async t => {
|
|
||||||
const power = _memberToPowerLevel(data.user.clyde_ai, {
|
|
||||||
roles: ["684524730274807911"]
|
|
||||||
}, data.guild.data_horde, data.channel.saving_the_world)
|
|
||||||
t.equal(power, 50)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("member2power: can send messages in protected channel due to user override = 50", async t => {
|
|
||||||
const power = _memberToPowerLevel(data.user.clyde_ai, {
|
|
||||||
roles: []
|
|
||||||
}, data.guild.data_horde, mixin({}, data.channel.saving_the_world, {
|
|
||||||
permission_overwrites: data.channel.saving_the_world.permission_overwrites.concat({
|
|
||||||
type: DiscordTypes.OverwriteType.member,
|
|
||||||
id: data.user.clyde_ai.id,
|
|
||||||
allow: String(DiscordTypes.PermissionFlagsBits.SendMessages),
|
|
||||||
deny: "0"
|
|
||||||
})
|
|
||||||
}))
|
|
||||||
t.equal(power, 50)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("member2power: can kick users = 50", async t => {
|
|
||||||
const power = _memberToPowerLevel(data.user.clyde_ai, {
|
|
||||||
roles: ["682789592390281245"]
|
|
||||||
}, data.guild.data_horde, data.channel.general)
|
|
||||||
t.equal(power, 50)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("member2power: can manage channels = 100", async t => {
|
|
||||||
const power = _memberToPowerLevel(data.user.clyde_ai, {
|
|
||||||
roles: ["665290147377578005"]
|
|
||||||
}, data.guild.data_horde, data.channel.saving_the_world)
|
|
||||||
t.equal(power, 100)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("member2power: pathfinder use case", async t => {
|
|
||||||
const power = _memberToPowerLevel(data.user.jerassicore, {
|
|
||||||
roles: ["1235396773510647810", "1359752622130593802", "1249165855632265267", "1380768596929806356", "1380756348190462015"]
|
|
||||||
}, data.guild.pathfinder, data.channel.character_art)
|
|
||||||
t.equal(power, 50)
|
|
||||||
})
|
|
||||||
|
|
|
||||||
|
|
@ -1,131 +0,0 @@
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const assert = require("assert")
|
|
||||||
const {reg} = require("../../matrix/read-registration")
|
|
||||||
const Ty = require("../../types")
|
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
|
||||||
const {sync, db, select, from} = passthrough
|
|
||||||
/** @type {import("../../matrix/api")} */
|
|
||||||
const api = sync.require("../../matrix/api")
|
|
||||||
/** @type {import("../../matrix/file")} */
|
|
||||||
const file = sync.require("../../matrix/file")
|
|
||||||
/** @type {import("./register-user")} */
|
|
||||||
const registerUser = sync.require("./register-user")
|
|
||||||
/** @type {import("../converters/user-to-mxid")} */
|
|
||||||
const userToMxid = sync.require("../converters/user-to-mxid")
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A sim is an account that is being simulated by the bridge to copy events from the other side.
|
|
||||||
* @param {string} fakeUserID
|
|
||||||
* @param {Ty.WebhookAuthor} author
|
|
||||||
* @returns mxid
|
|
||||||
*/
|
|
||||||
async function createSim(fakeUserID, author) {
|
|
||||||
// Choose sim name
|
|
||||||
const simName = userToMxid.webhookAuthorToSimName(author)
|
|
||||||
const localpart = reg.ooye.namespace_prefix + simName
|
|
||||||
const mxid = `@${localpart}:${reg.ooye.server_name}`
|
|
||||||
|
|
||||||
// Save chosen name in the database forever
|
|
||||||
db.prepare("INSERT INTO sim (user_id, username, sim_name, mxid) VALUES (?, ?, ?, ?)").run(fakeUserID, author.username, simName, mxid)
|
|
||||||
|
|
||||||
// Register matrix user with that name
|
|
||||||
try {
|
|
||||||
await api.register(localpart)
|
|
||||||
} catch (e) {
|
|
||||||
// If user creation fails, manually undo the database change. Still isn't perfect, but should help.
|
|
||||||
// (I would prefer a transaction, but it's not safe to leave transactions open across event loop ticks.)
|
|
||||||
db.prepare("DELETE FROM sim WHERE user_id = ?").run(fakeUserID)
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
return mxid
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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 {string} fakeUserID
|
|
||||||
* @param {Ty.WebhookAuthor} author
|
|
||||||
* @returns {Promise<string>} mxid
|
|
||||||
*/
|
|
||||||
async function ensureSim(fakeUserID, author) {
|
|
||||||
let mxid = null
|
|
||||||
const existing = select("sim", "mxid", {user_id: fakeUserID}).pluck().get()
|
|
||||||
if (existing) {
|
|
||||||
mxid = existing
|
|
||||||
} else {
|
|
||||||
mxid = await createSim(fakeUserID, author)
|
|
||||||
}
|
|
||||||
return mxid
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ensure a sim is registered for the user and is joined to the room.
|
|
||||||
* @param {string} fakeUserID
|
|
||||||
* @param {Ty.WebhookAuthor} author
|
|
||||||
* @param {string} roomID
|
|
||||||
* @returns {Promise<string>} mxid
|
|
||||||
*/
|
|
||||||
async function ensureSimJoined(fakeUserID, author, roomID) {
|
|
||||||
// Ensure room ID is really an ID, not an alias
|
|
||||||
assert.ok(roomID[0] === "!")
|
|
||||||
|
|
||||||
// Ensure user
|
|
||||||
const mxid = await ensureSim(fakeUserID, author)
|
|
||||||
|
|
||||||
// Ensure joined
|
|
||||||
const existing = select("sim_member", "mxid", {room_id: roomID, mxid}).pluck().get()
|
|
||||||
if (!existing) {
|
|
||||||
await api.inviteToRoom(roomID, mxid)
|
|
||||||
await api.joinRoom(roomID, mxid)
|
|
||||||
db.prepare("INSERT OR IGNORE INTO sim_member (room_id, mxid) VALUES (?, ?)").run(roomID, mxid)
|
|
||||||
}
|
|
||||||
return mxid
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generate profile data based on webhook displayname and configured avatar.
|
|
||||||
* @param {Ty.WebhookAuthor} author
|
|
||||||
*/
|
|
||||||
async function authorToStateContent(author) {
|
|
||||||
// We prefer to use the member's avatar URL data since the image upload can be cached across channels,
|
|
||||||
// unlike the userAvatar URL which is unique per channel, due to the webhook ID being in the URL.
|
|
||||||
const avatar = file.userAvatar(author)
|
|
||||||
|
|
||||||
const content = {
|
|
||||||
displayname: author.username,
|
|
||||||
membership: "join",
|
|
||||||
}
|
|
||||||
if (avatar) content.avatar_url = await file.uploadDiscordFileToMxc(avatar)
|
|
||||||
|
|
||||||
return content
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sync profile data for a sim webhook user. This function follows the following process:
|
|
||||||
* 1. Create and join the sim to the room if needed
|
|
||||||
* 2. Make an object of what the new room member state content would be, including uploading the profile picture if it hasn't been done before
|
|
||||||
* 3. Compare against the previously known state content, which is helpfully stored in the database
|
|
||||||
* 4. If the state content has changed, send it to Matrix and update it in the database for next time
|
|
||||||
* @param {Ty.WebhookAuthor} author for profile data
|
|
||||||
* @param {string} roomID room to join member to
|
|
||||||
* @param {boolean} shouldActuallySync whether to actually sync updated user data or just ensure it's joined
|
|
||||||
* @returns {Promise<string>} mxid of the updated sim
|
|
||||||
*/
|
|
||||||
async function syncUser(author, roomID, shouldActuallySync) {
|
|
||||||
const fakeUserID = userToMxid.webhookAuthorToFakeUserID(author)
|
|
||||||
|
|
||||||
// Create and join the sim to the room if needed
|
|
||||||
const mxid = await ensureSimJoined(fakeUserID, author, roomID)
|
|
||||||
|
|
||||||
if (shouldActuallySync) {
|
|
||||||
// Build current profile data and sync if the hash has changed
|
|
||||||
const content = await authorToStateContent(author)
|
|
||||||
await registerUser._sendSyncUser(roomID, mxid, content, null)
|
|
||||||
}
|
|
||||||
|
|
||||||
return mxid
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports.syncUser = syncUser
|
|
||||||
|
|
@ -4,7 +4,7 @@ const Ty = require("../../types")
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
const DiscordTypes = require("discord-api-types/v10")
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
const passthrough = require("../../passthrough")
|
||||||
const {discord, sync, db, from, select} = passthrough
|
const {discord, sync, db, select} = passthrough
|
||||||
/** @type {import("../../matrix/api")} */
|
/** @type {import("../../matrix/api")} */
|
||||||
const api = sync.require("../../matrix/api")
|
const api = sync.require("../../matrix/api")
|
||||||
/** @type {import("../converters/emoji-to-key")} */
|
/** @type {import("../converters/emoji-to-key")} */
|
||||||
|
|
@ -18,15 +18,12 @@ const converter = sync.require("../converters/remove-reaction")
|
||||||
* @param {DiscordTypes.GatewayMessageReactionRemoveDispatchData | DiscordTypes.GatewayMessageReactionRemoveEmojiDispatchData | DiscordTypes.GatewayMessageReactionRemoveAllDispatchData} data
|
* @param {DiscordTypes.GatewayMessageReactionRemoveDispatchData | DiscordTypes.GatewayMessageReactionRemoveEmojiDispatchData | DiscordTypes.GatewayMessageReactionRemoveAllDispatchData} data
|
||||||
*/
|
*/
|
||||||
async function removeSomeReactions(data) {
|
async function removeSomeReactions(data) {
|
||||||
const row = select("channel_room", "room_id", {channel_id: data.channel_id}).get()
|
const roomID = select("channel_room", "room_id", {channel_id: data.channel_id}).pluck().get()
|
||||||
if (!row) return
|
if (!roomID) return
|
||||||
|
const eventIDForMessage = select("event_message", "event_id", {message_id: data.message_id, reaction_part: 0}).pluck().get()
|
||||||
|
if (!eventIDForMessage) return
|
||||||
|
|
||||||
const eventReactedTo = from("event_message").join("message_room", "message_id").join("historical_channel_room", "historical_room_index")
|
const reactions = await api.getFullRelations(roomID, eventIDForMessage, "m.annotation")
|
||||||
.where({message_id: data.message_id}).and("ORDER BY reaction_part").select("event_id", "room_id").get()
|
|
||||||
if (!eventReactedTo) return
|
|
||||||
|
|
||||||
// Due to server restrictions, all relations (i.e. reactions) have to be in the same room as the original event.
|
|
||||||
const reactions = await api.getFullRelations(eventReactedTo.room_id, eventReactedTo.event_id, "m.annotation")
|
|
||||||
|
|
||||||
// Run the proper strategy and any strategy-specific database changes
|
// Run the proper strategy and any strategy-specific database changes
|
||||||
const removals = await
|
const removals = await
|
||||||
|
|
@ -36,7 +33,7 @@ async function removeSomeReactions(data) {
|
||||||
|
|
||||||
// Redact the events and delete individual stored events in the database
|
// Redact the events and delete individual stored events in the database
|
||||||
for (const removal of removals) {
|
for (const removal of removals) {
|
||||||
await api.redactEvent(eventReactedTo.room_id, removal.eventID, removal.mxid)
|
await api.redactEvent(roomID, removal.eventID, removal.mxid)
|
||||||
if (removal.hash) db.prepare("DELETE FROM reaction WHERE hashed_event_id = ?").run(removal.hash)
|
if (removal.hash) db.prepare("DELETE FROM reaction WHERE hashed_event_id = ?").run(removal.hash)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -46,7 +43,7 @@ async function removeSomeReactions(data) {
|
||||||
* @param {Ty.Event.Outer<Ty.Event.M_Reaction>[]} reactions
|
* @param {Ty.Event.Outer<Ty.Event.M_Reaction>[]} reactions
|
||||||
*/
|
*/
|
||||||
async function removeReaction(data, reactions) {
|
async function removeReaction(data, reactions) {
|
||||||
const key = await emojiToKey.emojiToKey(data.emoji, data.message_id)
|
const key = await emojiToKey.emojiToKey(data.emoji)
|
||||||
return converter.removeReaction(data, reactions, key)
|
return converter.removeReaction(data, reactions, key)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -55,8 +52,8 @@ async function removeReaction(data, reactions) {
|
||||||
* @param {Ty.Event.Outer<Ty.Event.M_Reaction>[]} reactions
|
* @param {Ty.Event.Outer<Ty.Event.M_Reaction>[]} reactions
|
||||||
*/
|
*/
|
||||||
async function removeEmojiReaction(data, reactions) {
|
async function removeEmojiReaction(data, reactions) {
|
||||||
const key = await emojiToKey.emojiToKey(data.emoji, data.message_id)
|
const key = await emojiToKey.emojiToKey(data.emoji)
|
||||||
const discordPreferredEncoding = await emoji.encodeEmoji(key, undefined)
|
const discordPreferredEncoding = emoji.encodeEmoji(key, undefined)
|
||||||
db.prepare("DELETE FROM reaction WHERE message_id = ? AND encoded_emoji = ?").run(data.message_id, discordPreferredEncoding)
|
db.prepare("DELETE FROM reaction WHERE message_id = ? AND encoded_emoji = ?").run(data.message_id, discordPreferredEncoding)
|
||||||
|
|
||||||
return converter.removeEmojiReaction(data, reactions, key)
|
return converter.removeEmojiReaction(data, reactions, key)
|
||||||
|
|
|
||||||
|
|
@ -12,81 +12,50 @@ function debugRetrigger(message) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const paused = new Set()
|
|
||||||
const emitter = new EventEmitter()
|
const emitter = new EventEmitter()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Due to Eventual Consistency(TM) an update/delete may arrive before the original message arrives
|
* Due to Eventual Consistency(TM) an update/delete may arrive before the original message arrives
|
||||||
* (or before the it has finished being bridged to an event).
|
* (or before the it has finished being bridged to an event).
|
||||||
* In this case, wait until the original message has finished bridging, then retrigger the passed function.
|
* In this case, wait until the original message has finished bridging, then retrigger the passed function.
|
||||||
* @template {(...args: any[]) => any} T
|
* @template {(...args: any[]) => Promise<any>} T
|
||||||
* @param {string} inputID
|
* @param {string} messageID
|
||||||
* @param {T} fn
|
* @param {T} fn
|
||||||
* @param {Parameters<T>} rest
|
* @param {Parameters<T>} rest
|
||||||
* @returns {boolean} false if the event was found and the function will be ignored, true if the event was not found and the function will be retriggered
|
* @returns {boolean} false if the event was found and the function will be ignored, true if the event was not found and the function will be retriggered
|
||||||
*/
|
*/
|
||||||
function eventNotFoundThenRetrigger(inputID, fn, ...rest) {
|
function eventNotFoundThenRetrigger(messageID, fn, ...rest) {
|
||||||
if (!paused.has(inputID)) {
|
const eventID = select("event_message", "event_id", {message_id: messageID}).pluck().get()
|
||||||
if (inputID.match(/^[0-9]+$/)) {
|
|
||||||
const eventID = select("event_message", "event_id", {message_id: inputID}).pluck().get()
|
|
||||||
if (eventID) {
|
if (eventID) {
|
||||||
debugRetrigger(`[retrigger] OK mid <-> eid = ${inputID} <-> ${eventID}`)
|
debugRetrigger(`[retrigger] OK mid <-> eid = ${messageID} <-> ${eventID}`)
|
||||||
return false // event was found so don't retrigger
|
return false // event was found so don't retrigger
|
||||||
}
|
}
|
||||||
} else if (inputID.match(/^\$/)) {
|
|
||||||
const messageID = select("event_message", "message_id", {event_id: inputID}).pluck().get()
|
|
||||||
if (messageID) {
|
|
||||||
debugRetrigger(`[retrigger] OK eid <-> mid = ${inputID} <-> ${messageID}`)
|
|
||||||
return false // message was found so don't retrigger
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
debugRetrigger(`[retrigger] WAIT id = ${inputID}`)
|
debugRetrigger(`[retrigger] WAIT mid <-> eid = ${messageID} <-> ${eventID}`)
|
||||||
emitter.once(inputID, () => {
|
emitter.once(messageID, () => {
|
||||||
debugRetrigger(`[retrigger] TRIGGER id = ${inputID}`)
|
debugRetrigger(`[retrigger] TRIGGER mid = ${messageID}`)
|
||||||
fn(...rest)
|
fn(...rest)
|
||||||
})
|
})
|
||||||
// if the event never arrives, don't trigger the callback, just clean up
|
// if the event never arrives, don't trigger the callback, just clean up
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (emitter.listeners(inputID).length) {
|
if (emitter.listeners(messageID).length) {
|
||||||
debugRetrigger(`[retrigger] EXPIRE id = ${inputID}`)
|
debugRetrigger(`[retrigger] EXPIRE mid = ${messageID}`)
|
||||||
}
|
}
|
||||||
emitter.removeAllListeners(inputID)
|
emitter.removeAllListeners(messageID)
|
||||||
}, 60 * 1000) // 1 minute
|
}, 60 * 1000) // 1 minute
|
||||||
return true // event was not found, then retrigger
|
return true // event was not found, then retrigger
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Anything calling retrigger during the callback will be paused and retriggered after the callback resolves.
|
|
||||||
* @template T
|
|
||||||
* @param {string} messageID
|
|
||||||
* @param {Promise<T>} promise
|
|
||||||
* @returns {Promise<T>}
|
|
||||||
*/
|
|
||||||
async function pauseChanges(messageID, promise) {
|
|
||||||
try {
|
|
||||||
debugRetrigger(`[retrigger] PAUSE id = ${messageID}`)
|
|
||||||
paused.add(messageID)
|
|
||||||
return await promise
|
|
||||||
} finally {
|
|
||||||
debugRetrigger(`[retrigger] RESUME id = ${messageID}`)
|
|
||||||
paused.delete(messageID)
|
|
||||||
messageFinishedBridging(messageID)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Triggers any pending operations that were waiting on the corresponding event ID.
|
* Triggers any pending operations that were waiting on the corresponding event ID.
|
||||||
* @param {string} messageID
|
* @param {string} messageID
|
||||||
*/
|
*/
|
||||||
function messageFinishedBridging(messageID) {
|
function messageFinishedBridging(messageID) {
|
||||||
if (emitter.listeners(messageID).length) {
|
if (emitter.listeners(messageID).length) {
|
||||||
debugRetrigger(`[retrigger] EMIT id = ${messageID}`)
|
debugRetrigger(`[retrigger] EMIT mid = ${messageID}`)
|
||||||
}
|
}
|
||||||
emitter.emit(messageID)
|
emitter.emit(messageID)
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.eventNotFoundThenRetrigger = eventNotFoundThenRetrigger
|
module.exports.eventNotFoundThenRetrigger = eventNotFoundThenRetrigger
|
||||||
module.exports.messageFinishedBridging = messageFinishedBridging
|
module.exports.messageFinishedBridging = messageFinishedBridging
|
||||||
module.exports.pauseChanges = pauseChanges
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ const assert = require("assert").strict
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
const DiscordTypes = require("discord-api-types/v10")
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
const passthrough = require("../../passthrough")
|
||||||
const { discord, sync, db, select, from} = passthrough
|
const { discord, sync, db } = passthrough
|
||||||
/** @type {import("../converters/message-to-event")} */
|
/** @type {import("../converters/message-to-event")} */
|
||||||
const messageToEvent = sync.require("../converters/message-to-event")
|
const messageToEvent = sync.require("../converters/message-to-event")
|
||||||
/** @type {import("../../matrix/api")} */
|
/** @type {import("../../matrix/api")} */
|
||||||
|
|
@ -13,16 +13,10 @@ const api = sync.require("../../matrix/api")
|
||||||
const registerUser = sync.require("./register-user")
|
const registerUser = sync.require("./register-user")
|
||||||
/** @type {import("./register-pk-user")} */
|
/** @type {import("./register-pk-user")} */
|
||||||
const registerPkUser = sync.require("./register-pk-user")
|
const registerPkUser = sync.require("./register-pk-user")
|
||||||
/** @type {import("./register-webhook-user")} */
|
|
||||||
const registerWebhookUser = sync.require("./register-webhook-user")
|
|
||||||
/** @type {import("../actions/create-room")} */
|
/** @type {import("../actions/create-room")} */
|
||||||
const createRoom = sync.require("../actions/create-room")
|
const createRoom = sync.require("../actions/create-room")
|
||||||
/** @type {import("../actions/poll-end")} */
|
|
||||||
const pollEnd = sync.require("../actions/poll-end")
|
|
||||||
/** @type {import("../../discord/utils")} */
|
/** @type {import("../../discord/utils")} */
|
||||||
const dUtils = sync.require("../../discord/utils")
|
const dUtils = sync.require("../../discord/utils")
|
||||||
/** @type {import("../../m2d/actions/channel-webhook")} */
|
|
||||||
const channelWebhook = sync.require("../../m2d/actions/channel-webhook")
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {DiscordTypes.GatewayMessageCreateDispatchData} message
|
* @param {DiscordTypes.GatewayMessageCreateDispatchData} message
|
||||||
|
|
@ -32,46 +26,29 @@ const channelWebhook = sync.require("../../m2d/actions/channel-webhook")
|
||||||
*/
|
*/
|
||||||
async function sendMessage(message, channel, guild, row) {
|
async function sendMessage(message, channel, guild, row) {
|
||||||
const roomID = await createRoom.ensureRoom(message.channel_id)
|
const roomID = await createRoom.ensureRoom(message.channel_id)
|
||||||
const historicalRoomIndex = select("historical_channel_room", "historical_room_index", {room_id: roomID}).pluck().get()
|
|
||||||
assert(historicalRoomIndex)
|
|
||||||
|
|
||||||
let senderMxid = null
|
let senderMxid = null
|
||||||
if (dUtils.isWebhookMessage(message)) {
|
|
||||||
const useWebhookProfile = select("guild_space", "webhook_profile", {guild_id: guild.id}).pluck().get() ?? 0
|
|
||||||
if (row && row.speedbump_webhook_id === message.webhook_id) {
|
if (row && row.speedbump_webhook_id === message.webhook_id) {
|
||||||
// Handle the PluralKit public instance
|
// Handle the PluralKit public instance
|
||||||
if (row.speedbump_id === "466378653216014359") {
|
if (row.speedbump_id === "466378653216014359") {
|
||||||
senderMxid = await registerPkUser.syncUser(message.id, message.author, roomID, true)
|
const pkMessage = await registerPkUser.fetchMessage(message.id)
|
||||||
|
senderMxid = await registerPkUser.syncUser(message.author, pkMessage, roomID)
|
||||||
}
|
}
|
||||||
} else if (useWebhookProfile) {
|
} else if (message.author.id === discord.application.id) {
|
||||||
senderMxid = await registerWebhookUser.syncUser(message.author, roomID, true)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// not a webhook
|
|
||||||
if (message.author.id === discord.application.id) {
|
|
||||||
// no need to sync the bot's own user
|
// no need to sync the bot's own user
|
||||||
} else {
|
} else if (dUtils.isWebhookMessage(message)) {
|
||||||
|
senderMxid = await registerUser.syncWebhook(message.author, channel, guild, roomID)
|
||||||
|
} else if (message.member) { // available on a gateway message create event
|
||||||
senderMxid = await registerUser.syncUser(message.author, message.member, channel, guild, roomID)
|
senderMxid = await registerUser.syncUser(message.author, message.member, channel, guild, roomID)
|
||||||
}
|
} else { // well, good enough...
|
||||||
|
senderMxid = await registerUser.ensureSimJoined(message.author, roomID)
|
||||||
}
|
}
|
||||||
|
|
||||||
let sentResultsMessage
|
const events = await messageToEvent.messageToEvent(message, guild, {}, {api})
|
||||||
if (message.type === DiscordTypes.MessageType.PollResult) { // ensure all Discord-side votes were pushed to Matrix before a poll is closed
|
|
||||||
const detailedResultsMessage = await pollEnd.endPoll(message)
|
|
||||||
if (detailedResultsMessage) {
|
|
||||||
const threadParent = select("channel_room", "thread_parent", {channel_id: message.channel_id}).pluck().get()
|
|
||||||
const channelID = threadParent ? threadParent : message.channel_id
|
|
||||||
const threadID = threadParent ? message.channel_id : undefined
|
|
||||||
sentResultsMessage = await channelWebhook.sendMessageWithWebhook(channelID, detailedResultsMessage, threadID)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const events = await messageToEvent.messageToEvent(message, guild, {}, {api, snow: discord.snow})
|
|
||||||
const eventIDs = []
|
const eventIDs = []
|
||||||
if (events.length) {
|
if (events.length) {
|
||||||
db.prepare("INSERT OR IGNORE INTO message_room (message_id, historical_room_index) VALUES (?, ?)").run(message.id, historicalRoomIndex)
|
db.prepare("REPLACE INTO message_channel (message_id, channel_id) VALUES (?, ?)").run(message.id, message.channel_id)
|
||||||
const typingMxid = from("sim").join("sim_member", "mxid").where({user_id: message.author.id, room_id: roomID}).pluck("mxid").get()
|
if (senderMxid) api.sendTyping(roomID, false, senderMxid)
|
||||||
if (typingMxid) api.sendTyping(roomID, false, typingMxid).catch(() => {})
|
|
||||||
}
|
}
|
||||||
for (const event of events) {
|
for (const event of events) {
|
||||||
const part = event === events[0] ? 0 : 1
|
const part = event === events[0] ? 0 : 1
|
||||||
|
|
@ -86,19 +63,7 @@ async function sendMessage(message, channel, guild, row) {
|
||||||
|
|
||||||
const useTimestamp = message["backfill"] ? new Date(message.timestamp).getTime() : undefined
|
const useTimestamp = message["backfill"] ? new Date(message.timestamp).getTime() : undefined
|
||||||
const eventID = await api.sendEvent(roomID, eventType, eventWithoutType, senderMxid, useTimestamp)
|
const eventID = await api.sendEvent(roomID, eventType, eventWithoutType, senderMxid, useTimestamp)
|
||||||
eventIDs.push(eventID)
|
|
||||||
|
|
||||||
try {
|
|
||||||
db.prepare("INSERT INTO event_message (event_id, event_type, event_subtype, message_id, part, reaction_part, source) VALUES (?, ?, ?, ?, ?, ?, 1)").run(eventID, eventType, event.msgtype || null, message.id, part, reactionPart) // source 1 = discord
|
db.prepare("INSERT INTO event_message (event_id, event_type, event_subtype, message_id, part, reaction_part, source) VALUES (?, ?, ?, ?, ?, ?, 1)").run(eventID, eventType, event.msgtype || null, message.id, part, reactionPart) // source 1 = discord
|
||||||
} catch (e) {
|
|
||||||
// check if we got rugpulled
|
|
||||||
if (!select("message_room", "message_id", {message_id: message.id}).get()) {
|
|
||||||
for (const eventID of eventIDs) {
|
|
||||||
await api.redactEvent(roomID, eventID)
|
|
||||||
}
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The primary event is part = 0 and has the most important and distinct information. It is used to provide reply previews, be pinned, and possibly future uses.
|
// The primary event is part = 0 and has the most important and distinct information. It is used to provide reply previews, be pinned, and possibly future uses.
|
||||||
// The first event is chosen to be the primary part because it is usually the message text content and is more likely to be distinct.
|
// The first event is chosen to be the primary part because it is usually the message text content and is more likely to be distinct.
|
||||||
|
|
@ -106,35 +71,7 @@ async function sendMessage(message, channel, guild, row) {
|
||||||
|
|
||||||
// The last event gets reaction_part = 0. Reactions are managed there because reactions are supposed to appear at the bottom.
|
// The last event gets reaction_part = 0. Reactions are managed there because reactions are supposed to appear at the bottom.
|
||||||
|
|
||||||
|
eventIDs.push(eventID)
|
||||||
if (eventType === "org.matrix.msc3381.poll.start") {
|
|
||||||
db.transaction(() => {
|
|
||||||
db.prepare("INSERT INTO poll (message_id, max_selections, question_text, is_closed) VALUES (?, ?, ?, 0)").run(
|
|
||||||
message.id,
|
|
||||||
event["org.matrix.msc3381.poll.start"].max_selections,
|
|
||||||
event["org.matrix.msc3381.poll.start"].question["org.matrix.msc1767.text"]
|
|
||||||
)
|
|
||||||
for (const [index, option] of Object.entries(event["org.matrix.msc3381.poll.start"].answers)) {
|
|
||||||
db.prepare("INSERT INTO poll_option (message_id, matrix_option, discord_option, option_text, seq) VALUES (?, ?, ?, ?, ?)").run(
|
|
||||||
message.id,
|
|
||||||
option.id,
|
|
||||||
option.id,
|
|
||||||
option["org.matrix.msc1767.text"],
|
|
||||||
index
|
|
||||||
)
|
|
||||||
}
|
|
||||||
})()
|
|
||||||
}
|
|
||||||
|
|
||||||
// part/reaction_part consistency for polls
|
|
||||||
if (sentResultsMessage) {
|
|
||||||
db.transaction(() => {
|
|
||||||
db.prepare("INSERT OR IGNORE INTO message_room (message_id, historical_room_index) VALUES (?, ?)").run(sentResultsMessage.id, historicalRoomIndex)
|
|
||||||
db.prepare("UPDATE event_message SET reaction_part = 1 WHERE event_id = ?").run(eventID)
|
|
||||||
// part = 1, reaction_part = 0, source = 0 as the results are "from Matrix" and doing otherwise breaks things when that message gets updated by Discord (it just does that sometimes)
|
|
||||||
db.prepare("INSERT INTO event_message (event_id, event_type, event_subtype, message_id, part, reaction_part, source) VALUES (?, ?, ?, ?, ?, ?, 0)").run(eventID, eventType, event.msgtype || null, sentResultsMessage.id, 1, 0)
|
|
||||||
})()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return eventIDs
|
return eventIDs
|
||||||
|
|
|
||||||
|
|
@ -1,114 +0,0 @@
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
|
||||||
const {sync, select} = passthrough
|
|
||||||
/** @type {import("../../matrix/api")} */
|
|
||||||
const api = sync.require("../../matrix/api")
|
|
||||||
|
|
||||||
/*
|
|
||||||
We do this in two phases for optimisation reasons.
|
|
||||||
Discord sends us an event when the presence *changes.*
|
|
||||||
We need to keep the event data in memory because we need to *repeatedly* send it to Matrix using a long-lived loop.
|
|
||||||
|
|
||||||
There are two phases to get it from Discord to Matrix.
|
|
||||||
The first phase stores Discord presence data in memory.
|
|
||||||
The second phase loops over the memory and sends it on to Matrix.
|
|
||||||
|
|
||||||
Optimisations:
|
|
||||||
* Presence can be deactivated per-guild in OOYE settings. If the user doesn't share any presence-enabled-guilds with us, we don't need to do anything.
|
|
||||||
* Presence can be sent for users without sims. In this case, they will be discarded from memory when the next loop begins.
|
|
||||||
* Matrix ID is cached in memory on the Presence class. The alternative to this is querying it every time we receive a presence change event in a valid guild.
|
|
||||||
* Presence can be sent multiple times in a row for the same user for each guild we share. The loop timer prevents these "changes" from individually reaching the homeserver.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Synapse expires each user's presence after 30 seconds and makes them offline, so we have to loop every 28 seconds and update each user again.
|
|
||||||
const presenceLoopInterval = 28e3
|
|
||||||
|
|
||||||
// Cache the list of enabled guilds rather than accessing it like multiple times per second when any user changes presence
|
|
||||||
const guildPresenceSetting = new class {
|
|
||||||
/** @private @type {Set<string>} */ guilds
|
|
||||||
constructor() {
|
|
||||||
this.update()
|
|
||||||
}
|
|
||||||
update() {
|
|
||||||
this.guilds = new Set(select("guild_space", "guild_id", {presence: 1}).pluck().all())
|
|
||||||
}
|
|
||||||
isEnabled(guildID) {
|
|
||||||
return this.guilds.has(guildID)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class Presence extends sync.reloadClassMethods(() => Presence) {
|
|
||||||
/** @type {string} */ userID
|
|
||||||
/** @type {{presence: "online" | "offline" | "unavailable", status_msg?: string}} */ data
|
|
||||||
/** @private @type {?string | undefined} */ mxid
|
|
||||||
/** @private @type {number} */ delay = Math.random()
|
|
||||||
|
|
||||||
constructor(userID) {
|
|
||||||
super()
|
|
||||||
this.userID = userID
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {string} status status field from Discord's PRESENCE_UPDATE event
|
|
||||||
*/
|
|
||||||
setData(status) {
|
|
||||||
const presence =
|
|
||||||
( status === "online" ? "online"
|
|
||||||
: status === "offline" ? "offline"
|
|
||||||
: "unavailable")
|
|
||||||
this.data = {presence}
|
|
||||||
}
|
|
||||||
|
|
||||||
sync(presences) {
|
|
||||||
const mxid = this.mxid ??= select("sim", "mxid", {user_id: this.userID}).pluck().get()
|
|
||||||
if (!mxid) return presences.delete(this.userID)
|
|
||||||
// I haven't tried, but I assume Synapse explodes if you try to update too many presences at the same time.
|
|
||||||
// This random delay will space them out over the whole 28 second cycle.
|
|
||||||
setTimeout(() => {
|
|
||||||
api.setPresence(this.data, mxid).catch(() => {})
|
|
||||||
}, this.delay * presenceLoopInterval).unref()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const presenceTracker = new class {
|
|
||||||
/** @private @type {Map<string, Presence>} userID -> Presence */ presences = sync.remember(() => new Map())
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
sync.addTemporaryInterval(() => this.syncPresences(), presenceLoopInterval)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This function is called for each Discord presence packet.
|
|
||||||
* @param {string} userID Discord user ID
|
|
||||||
* @param {string} guildID Discord guild ID that this presence applies to (really, the same presence applies to every single guild, but is delivered separately by Discord for some reason)
|
|
||||||
* @param {string} status status field from Discord's PRESENCE_UPDATE event
|
|
||||||
*/
|
|
||||||
incomingPresence(userID, guildID, status) {
|
|
||||||
// stop tracking offline presence objects - they will naturally expire and fall offline on the homeserver
|
|
||||||
if (status === "offline") return this.presences.delete(userID)
|
|
||||||
// check if we care about this guild
|
|
||||||
if (!guildPresenceSetting.isEnabled(guildID)) return
|
|
||||||
// start tracking presence for user (we'll check if they have a sim in the next sync loop)
|
|
||||||
this.getOrCreatePresence(userID).setData(status)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @private */
|
|
||||||
getOrCreatePresence(userID) {
|
|
||||||
return this.presences.get(userID) || (() => {
|
|
||||||
const presence = new Presence(userID)
|
|
||||||
this.presences.set(userID, presence)
|
|
||||||
return presence
|
|
||||||
})()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @private */
|
|
||||||
syncPresences() {
|
|
||||||
for (const presence of this.presences.values()) {
|
|
||||||
presence.sync(this.presences)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports.presenceTracker = presenceTracker
|
|
||||||
module.exports.guildPresenceSetting = guildPresenceSetting
|
|
||||||
|
|
@ -4,14 +4,6 @@ const DiscordTypes = require("discord-api-types/v10")
|
||||||
const passthrough = require("../../passthrough")
|
const passthrough = require("../../passthrough")
|
||||||
const {discord, select, db} = passthrough
|
const {discord, select, db} = passthrough
|
||||||
|
|
||||||
const DEBUG_SPEEDBUMP = false
|
|
||||||
|
|
||||||
function debugSpeedbump(message) {
|
|
||||||
if (DEBUG_SPEEDBUMP) {
|
|
||||||
console.log(message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const SPEEDBUMP_SPEED = 4000 // 4 seconds delay
|
const SPEEDBUMP_SPEED = 4000 // 4 seconds delay
|
||||||
const SPEEDBUMP_UPDATE_FREQUENCY = 2 * 60 * 60 // 2 hours
|
const SPEEDBUMP_UPDATE_FREQUENCY = 2 * 60 * 60 // 2 hours
|
||||||
|
|
||||||
|
|
@ -35,8 +27,8 @@ async function updateCache(channelID, lastChecked) {
|
||||||
db.prepare("UPDATE channel_room SET speedbump_id = ?, speedbump_webhook_id = ?, speedbump_checked = ? WHERE channel_id = ?").run(foundApplication, foundWebhook, now, channelID)
|
db.prepare("UPDATE channel_room SET speedbump_id = ?, speedbump_webhook_id = ?, speedbump_checked = ? WHERE channel_id = ?").run(foundApplication, foundWebhook, now, channelID)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @type {Map<string, number>} messageID -> number of gateway events currently bumping */
|
/** @type {Set<string>} set of messageID */
|
||||||
const bumping = new Map()
|
const bumping = new Set()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Slow down a message. After it passes the speedbump, return whether it's okay or if it's been deleted.
|
* Slow down a message. After it passes the speedbump, return whether it's okay or if it's been deleted.
|
||||||
|
|
@ -44,26 +36,9 @@ const bumping = new Map()
|
||||||
* @returns whether it was deleted
|
* @returns whether it was deleted
|
||||||
*/
|
*/
|
||||||
async function doSpeedbump(messageID) {
|
async function doSpeedbump(messageID) {
|
||||||
let value = (bumping.get(messageID) ?? 0) + 1
|
bumping.add(messageID)
|
||||||
bumping.set(messageID, value)
|
|
||||||
debugSpeedbump(`[speedbump] WAIT ${messageID}++ = ${value}`)
|
|
||||||
|
|
||||||
await new Promise(resolve => setTimeout(resolve, SPEEDBUMP_SPEED))
|
await new Promise(resolve => setTimeout(resolve, SPEEDBUMP_SPEED))
|
||||||
|
return !bumping.delete(messageID)
|
||||||
if (!bumping.has(messageID)) {
|
|
||||||
debugSpeedbump(`[speedbump] DELETED ${messageID}`)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
value = (bumping.get(messageID) ?? 0) - 1
|
|
||||||
if (value <= 0) {
|
|
||||||
debugSpeedbump(`[speedbump] OK ${messageID}-- = ${value}`)
|
|
||||||
bumping.delete(messageID)
|
|
||||||
return false
|
|
||||||
} else {
|
|
||||||
debugSpeedbump(`[speedbump] MULTI ${messageID}-- = ${value}`)
|
|
||||||
bumping.set(messageID, value)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,6 @@ const {discord, sync, db} = passthrough
|
||||||
const pinsToList = sync.require("../converters/pins-to-list")
|
const pinsToList = sync.require("../converters/pins-to-list")
|
||||||
/** @type {import("../../matrix/api")} */
|
/** @type {import("../../matrix/api")} */
|
||||||
const api = sync.require("../../matrix/api")
|
const api = sync.require("../../matrix/api")
|
||||||
/** @type {import("../../matrix/kstate")} */
|
|
||||||
const ks = sync.require("../../matrix/kstate")
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @template {string | null | undefined} T
|
* @template {string | null | undefined} T
|
||||||
|
|
@ -25,21 +23,13 @@ function convertTimestamp(timestamp) {
|
||||||
* @param {number?} convertedTimestamp
|
* @param {number?} convertedTimestamp
|
||||||
*/
|
*/
|
||||||
async function updatePins(channelID, roomID, convertedTimestamp) {
|
async function updatePins(channelID, roomID, convertedTimestamp) {
|
||||||
try {
|
const pins = await discord.snow.channel.getChannelPinnedMessages(channelID)
|
||||||
var discordPins = await discord.snow.channel.getChannelPinnedMessages(channelID)
|
const eventIDs = pinsToList.pinsToList(pins)
|
||||||
} catch (e) {
|
if (pins.length === eventIDs.length || eventIDs.length) {
|
||||||
if (e.message === `{"message": "Missing Access", "code": 50001}`) {
|
await api.sendState(roomID, "m.room.pinned_events", "", {
|
||||||
return // Discord sends channel pins update events even for channels that the bot can't view/get pins in, just ignore it
|
pinned: eventIDs
|
||||||
|
})
|
||||||
}
|
}
|
||||||
throw e
|
|
||||||
}
|
|
||||||
|
|
||||||
const kstate = await ks.roomToKState(roomID, [["m.room.pinned_events", ""]])
|
|
||||||
const pinned = pinsToList.pinsToList(discordPins, kstate)
|
|
||||||
|
|
||||||
const diff = ks.diffKState(kstate, {"m.room.pinned_events/": {pinned}})
|
|
||||||
await ks.applyKStateDiffToRoom(roomID, diff)
|
|
||||||
|
|
||||||
db.prepare("UPDATE channel_room SET last_bridged_pin_timestamp = ? WHERE channel_id = ?").run(convertedTimestamp || 0, channelID)
|
db.prepare("UPDATE channel_room SET last_bridged_pin_timestamp = ? WHERE channel_id = ?").run(convertedTimestamp || 0, channelID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,10 +6,8 @@ const passthrough = require("../../passthrough")
|
||||||
const {sync, select, from} = passthrough
|
const {sync, select, from} = passthrough
|
||||||
/** @type {import("./message-to-event")} */
|
/** @type {import("./message-to-event")} */
|
||||||
const messageToEvent = sync.require("../converters/message-to-event")
|
const messageToEvent = sync.require("../converters/message-to-event")
|
||||||
/** @type {import("../../discord/utils")} */
|
/** @type {import("../../m2d/converters/utils")} */
|
||||||
const dUtils = sync.require("../../discord/utils")
|
const utils = sync.require("../../m2d/converters/utils")
|
||||||
/** @type {import("../../matrix/utils")} */
|
|
||||||
const mxUtils = sync.require("../../matrix/utils")
|
|
||||||
|
|
||||||
function eventCanBeEdited(ev) {
|
function eventCanBeEdited(ev) {
|
||||||
// Discord does not allow files, images, attachments, or videos to be edited.
|
// Discord does not allow files, images, attachments, or videos to be edited.
|
||||||
|
|
@ -20,39 +18,27 @@ function eventCanBeEdited(ev) {
|
||||||
if (ev.old.event_type === "m.sticker") {
|
if (ev.old.event_type === "m.sticker") {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
// Discord does not allow the data of polls to be edited, they may only be responded to.
|
|
||||||
if (ev.old.event_type === "org.matrix.msc3381.poll.start" || ev.old.event_type === "org.matrix.msc3381.poll.end") {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
// Anything else is fair game.
|
// Anything else is fair game.
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
function eventIsText(ev) {
|
|
||||||
return ev.old.event_type === "m.room.message" && (ev.old.event_subtype === "m.text" || ev.old.event_subtype === "m.notice")
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {import("discord-api-types/v10").GatewayMessageCreateDispatchData} message
|
* @param {import("discord-api-types/v10").GatewayMessageCreateDispatchData} message
|
||||||
* @param {import("discord-api-types/v10").APIGuild} guild
|
* @param {import("discord-api-types/v10").APIGuild} guild
|
||||||
* @param {import("../../matrix/api")} api simple-as-nails dependency injection for the matrix API
|
* @param {import("../../matrix/api")} api simple-as-nails dependency injection for the matrix API
|
||||||
*/
|
*/
|
||||||
async function editToChanges(message, guild, api) {
|
async function editToChanges(message, guild, api) {
|
||||||
|
// If it is a user edit, allow deleting old messages (e.g. they might have removed text from an image).
|
||||||
|
// If it is the system adding a generated embed to a message, don't delete old messages since the system only sends partial data.
|
||||||
|
// Since an update in August 2024, the system always provides the full data of message updates. I'll leave in the old code since it won't cause problems.
|
||||||
|
|
||||||
|
const isGeneratedEmbed = !("content" in message)
|
||||||
|
|
||||||
// Figure out what events we will be replacing
|
// Figure out what events we will be replacing
|
||||||
|
|
||||||
const roomID = select("channel_room", "room_id", {channel_id: message.channel_id}).pluck().get()
|
const roomID = select("channel_room", "room_id", {channel_id: message.channel_id}).pluck().get()
|
||||||
assert(roomID)
|
assert(roomID)
|
||||||
const oldEventRows = select("event_message", ["event_id", "event_type", "event_subtype", "part", "reaction_part", "source"], {message_id: message.id}).all()
|
const oldEventRows = select("event_message", ["event_id", "event_type", "event_subtype", "part", "reaction_part"], {message_id: message.id}).all()
|
||||||
|
|
||||||
// If it is a user edit, allow deleting old messages (e.g. they might have removed text from an image).
|
|
||||||
// If it is the system adding a generated embed to a message, don't delete old messages since the system only sends partial data.
|
|
||||||
// Since an update in August 2024, the system always provides the full data of message updates.
|
|
||||||
// Now, this code path is only used by generated embeds for messages that were originally sent from Matrix.
|
|
||||||
|
|
||||||
const originallyFromMatrix = oldEventRows.some(r => r.source === 0)
|
|
||||||
const mightBeGeneratedEmbed = !("content" in message) || originallyFromMatrix
|
|
||||||
|
|
||||||
// Figure out who to send as
|
|
||||||
|
|
||||||
/** @type {string?} Null if we don't have a sender in the room, which will happen if it's a webhook's message. The bridge bot will do the edit instead. */
|
/** @type {string?} Null if we don't have a sender in the room, which will happen if it's a webhook's message. The bridge bot will do the edit instead. */
|
||||||
let senderMxid = null
|
let senderMxid = null
|
||||||
|
|
@ -62,7 +48,7 @@ async function editToChanges(message, guild, api) {
|
||||||
// Should be a system generated embed. We want the embed to be sent by the same user who sent the message, so that the messages get grouped in most clients.
|
// Should be a system generated embed. We want the embed to be sent by the same user who sent the message, so that the messages get grouped in most clients.
|
||||||
const eventID = oldEventRows[0].event_id // a calling function should have already checked that there is at least one message to edit
|
const eventID = oldEventRows[0].event_id // a calling function should have already checked that there is at least one message to edit
|
||||||
const event = await api.getEvent(roomID, eventID)
|
const event = await api.getEvent(roomID, eventID)
|
||||||
if (mxUtils.eventSenderIsFromDiscord(event.sender)) {
|
if (utils.eventSenderIsFromDiscord(event.sender)) {
|
||||||
senderMxid = event.sender
|
senderMxid = event.sender
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -81,25 +67,13 @@ async function editToChanges(message, guild, api) {
|
||||||
+ The events must have the same subtype.
|
+ The events must have the same subtype.
|
||||||
Events will therefore be divided into four categories:
|
Events will therefore be divided into four categories:
|
||||||
*/
|
*/
|
||||||
/**
|
/** 1. Events that are matched, and should be edited by sending another m.replace event */
|
||||||
* 1. Events that are matched, and should be edited by sending another m.replace event
|
|
||||||
* @type {{old: typeof oldEventRows[0], oldMentions?: any, newFallbackContent: typeof newFallbackContent[0], newInnerContent: typeof newInnerContent[0]}[]}
|
|
||||||
*/
|
|
||||||
let eventsToReplace = []
|
let eventsToReplace = []
|
||||||
/**
|
/** 2. Events that are present in the old version only, and should be blanked or redacted */
|
||||||
* 2. Events that are present in the old version only, and should be blanked or redacted
|
|
||||||
* @type {{old: typeof oldEventRows[0]}[]}
|
|
||||||
*/
|
|
||||||
let eventsToRedact = []
|
let eventsToRedact = []
|
||||||
/**
|
/** 3. Events that are present in the new version only, and should be sent as new, with references back to the context */
|
||||||
* 3. Events that are present in the new version only, and should be sent as new, with references back to the context
|
|
||||||
* @type {typeof newInnerContent}
|
|
||||||
*/
|
|
||||||
let eventsToSend = []
|
let eventsToSend = []
|
||||||
/**
|
/** 4. Events that are matched and have definitely not changed, so they don't need to be edited or replaced at all. */
|
||||||
* 4. Events that are matched and have definitely not changed, so they don't need to be edited or replaced at all.
|
|
||||||
* @type {(typeof eventsToRedact[0] | typeof eventsToReplace[0])[]}
|
|
||||||
*/
|
|
||||||
let unchangedEvents = []
|
let unchangedEvents = []
|
||||||
|
|
||||||
function shift() {
|
function shift() {
|
||||||
|
|
@ -136,119 +110,68 @@ async function editToChanges(message, guild, api) {
|
||||||
eventsToRedact = oldEventRows.map(e => ({old: e}))
|
eventsToRedact = oldEventRows.map(e => ({old: e}))
|
||||||
|
|
||||||
// If this is a generated embed update, only allow the embeds to be updated, since the system only sends data about events. Ignore changes to other things.
|
// If this is a generated embed update, only allow the embeds to be updated, since the system only sends data about events. Ignore changes to other things.
|
||||||
// This also prevents Matrix events that were re-subtyped during conversion (e.g. large image -> text link) from being mistakenly included.
|
if (isGeneratedEmbed) {
|
||||||
if (mightBeGeneratedEmbed) {
|
unchangedEvents.push(...eventsToRedact.filter(e => e.old.event_subtype !== "m.notice")) // Move them from eventsToRedact to unchangedEvents.
|
||||||
unchangedEvents = unchangedEvents.concat(
|
eventsToRedact = eventsToRedact.filter(e => e.old.event_subtype === "m.notice")
|
||||||
dUtils.filterTo(eventsToRedact, e => e.old.event_subtype === "m.notice" && e.old.source === 1), // Move everything except embeds from eventsToRedact to unchangedEvents.
|
|
||||||
dUtils.filterTo(eventsToReplace, e => e.old.event_subtype === "m.notice" && e.old.source === 1) // Move everything except embeds from eventsToReplace to unchangedEvents.
|
|
||||||
)
|
|
||||||
eventsToSend = eventsToSend.filter(e => e.msgtype === "m.notice") // Don't send new events that aren't the embed.
|
|
||||||
}
|
|
||||||
|
|
||||||
// Don't post new generated embeds for messages if it's been a while since the message was sent. Detached embeds look weird.
|
|
||||||
const messageQuiteOld = message.timestamp && new Date(message.timestamp).getTime() < Date.now() - 30 * 1000 // older than 30 seconds ago
|
|
||||||
// Don't send anything new at all if it's been longer since the message was sent. Detached messages are just inappropriate.
|
|
||||||
const messageReallyOld = message.timestamp && new Date(message.timestamp).getTime() < Date.now() - 2 * 60 * 1000 // older than 2 minutes ago
|
|
||||||
// Don't post new generated embeds for messages if the setting was disabled.
|
|
||||||
const embedsEnabled = select("guild_space", "url_preview", {guild_id: guild?.id}).pluck().get() ?? 1
|
|
||||||
if (messageReallyOld) {
|
|
||||||
eventsToSend = [] // Only allow edits to change and delete, but not send new.
|
|
||||||
} else if ((messageQuiteOld || !embedsEnabled) && !message.author?.bot) {
|
|
||||||
eventsToSend = eventsToSend.filter(e => e.msgtype !== "m.notice") // Only send events that aren't embeds.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Now, everything in eventsToSend and eventsToRedact is a real change, but everything in eventsToReplace might not have actually changed!
|
// Now, everything in eventsToSend and eventsToRedact is a real change, but everything in eventsToReplace might not have actually changed!
|
||||||
// (Example: 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.
|
// So we'll remove entries from eventsToReplace that *definitely* cannot have changed. (This is category 4 mentioned above.) Everything remaining *may* have changed.
|
||||||
unchangedEvents = unchangedEvents.concat(dUtils.filterTo(eventsToReplace, ev => eventCanBeEdited(ev))) // Move them from eventsToReplace to unchangedEvents.
|
unchangedEvents.push(...eventsToReplace.filter(ev => !eventCanBeEdited(ev))) // Move them from eventsToRedact to unchangedEvents.
|
||||||
|
eventsToReplace = eventsToReplace.filter(eventCanBeEdited)
|
||||||
// Now, everything in eventsToReplace has the potential to have changed, but did it actually?
|
|
||||||
// (Example: if a URL preview was generated or updated, the message text won't have changed.)
|
|
||||||
// Only way to detect this is by text content. So we'll remove text events from eventsToReplace that have the same new text as text currently in the event.
|
|
||||||
for (let i = eventsToReplace.length; i--;) { // move backwards through array
|
|
||||||
const event = eventsToReplace[i]
|
|
||||||
if (!eventIsText(event)) continue // not text, can't analyse
|
|
||||||
const oldEvent = await api.getEvent(roomID, eventsToReplace[i].old.event_id)
|
|
||||||
eventsToReplace[i].oldMentions = oldEvent.content["m.mentions"]
|
|
||||||
const oldEventBodyWithoutQuotedReply = oldEvent.content.body?.replace(/^(>.*\n)*\n*/sm, "")
|
|
||||||
if (oldEventBodyWithoutQuotedReply !== event.newInnerContent.body) continue // event changed, must replace it
|
|
||||||
// Move it from eventsToRedact to unchangedEvents.
|
|
||||||
unchangedEvents.push(...eventsToReplace.filter(ev => ev.old.event_id === event.old.event_id))
|
|
||||||
eventsToReplace = eventsToReplace.filter(ev => ev.old.event_id !== event.old.event_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// We want to maintain exactly one part = 0 and one reaction_part = 0 database row at all times.
|
// We want to maintain exactly one part = 0 and one reaction_part = 0 database row at all times.
|
||||||
// This would be disrupted if existing events that are (reaction_)part = 0 will be redacted.
|
|
||||||
// If that is the case, pick a different existing or newly sent event to be (reaction_)part = 0.
|
|
||||||
/** @type {({column: string, eventID: string, value?: number} | {column: string, nextEvent: true})[]} */
|
/** @type {({column: string, eventID: string, value?: number} | {column: string, nextEvent: true})[]} */
|
||||||
const promotions = []
|
const promotions = []
|
||||||
for (const column of ["part", "reaction_part"]) {
|
for (const column of ["part", "reaction_part"]) {
|
||||||
const candidatesForParts = unchangedEvents.concat(eventsToReplace)
|
const candidatesForParts = unchangedEvents.concat(eventsToReplace)
|
||||||
// If no events with part = 0 exist (or will exist), we need to do some management.
|
// If no events with part = 0 exist (or will exist), we need to do some management.
|
||||||
if (!candidatesForParts.some(e => e.old[column] === 0)) {
|
if (!candidatesForParts.some(e => e.old[column] === 0)) {
|
||||||
// Try to find an existing event to promote. Bigger order is better.
|
|
||||||
if (candidatesForParts.length) {
|
if (candidatesForParts.length) {
|
||||||
|
// We can choose an existing event to promote. Bigger order is better.
|
||||||
const order = e => 2*+(e.event_type === "m.room.message") + 1*+(e.old.event_subtype === "m.text")
|
const order = e => 2*+(e.event_type === "m.room.message") + 1*+(e.old.event_subtype === "m.text")
|
||||||
candidatesForParts.sort((a, b) => order(b) - order(a))
|
candidatesForParts.sort((a, b) => order(b) - order(a))
|
||||||
if (column === "part") {
|
if (column === "part") {
|
||||||
promotions.push({column, eventID: candidatesForParts[0].old.event_id}) // part should be the first one
|
promotions.push({column, eventID: candidatesForParts[0].old.event_id}) // part should be the first one
|
||||||
} else if (eventsToSend.length) {
|
|
||||||
promotions.push({column, nextEvent: true}) // reaction_part should be the last one
|
|
||||||
} else {
|
} else {
|
||||||
promotions.push({column, eventID: candidatesForParts[candidatesForParts.length - 1].old.event_id}) // reaction_part should be the last one
|
promotions.push({column, eventID: candidatesForParts[candidatesForParts.length - 1].old.event_id}) // reaction_part should be the last one
|
||||||
}
|
}
|
||||||
}
|
} else {
|
||||||
// Or, if there are no existing events to promote and new events will be sent, whatever gets sent will be the next part = 0.
|
// No existing events to promote, but new events are being sent. Whatever gets sent will be the next part = 0.
|
||||||
else {
|
|
||||||
promotions.push({column, nextEvent: true})
|
promotions.push({column, nextEvent: true})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// If adding events, try to keep reactions attached to the bottom of the group (unless reactions have already been added)
|
// If adding events, try to keep reactions attached to the bottom of the group (unless reactions have already been added)
|
||||||
if (eventsToSend.length && !promotions.length) {
|
if (eventsToSend.length && !promotions.length) {
|
||||||
const existingReaction = select("reaction", "message_id", {message_id: message.id}).pluck().get()
|
const existingReaction = select("reaction", "message_id", {message_id: message.id}).pluck().get()
|
||||||
if (!existingReaction) {
|
if (!existingReaction) {
|
||||||
const existingPartZero = unchangedEvents.concat(eventsToReplace).find(p => p.old.reaction_part === 0)
|
const existingPartZero = candidatesForParts.find(p => p.old.reaction_part === 0)
|
||||||
assert(existingPartZero) // will exist because a reaction_part=0 always exists and no events are being removed
|
assert(existingPartZero) // will exist because a reaction_part=0 always exists and no events are being removed
|
||||||
promotions.push({column: "reaction_part", eventID: existingPartZero.old.event_id, value: 1}) // update the current reaction_part to 1
|
promotions.push({column: "reaction_part", eventID: existingPartZero.old.event_id, value: 1}) // update the current reaction_part to 1
|
||||||
promotions.push({column: "reaction_part", nextEvent: true}) // the newly created event will have reaction_part = 0
|
promotions.push({column: "reaction_part", nextEvent: true}) // the newly created event will have reaction_part = 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Removing unnecessary properties before returning
|
// Removing unnecessary properties before returning
|
||||||
return {
|
eventsToRedact = eventsToRedact.map(e => e.old.event_id)
|
||||||
roomID,
|
eventsToReplace = eventsToReplace.map(e => ({oldID: e.old.event_id, newContent: makeReplacementEventContent(e.old.event_id, e.newFallbackContent, e.newInnerContent)}))
|
||||||
eventsToReplace: eventsToReplace.map(e => ({oldID: e.old.event_id, newContent: makeReplacementEventContent(e.old.event_id, e.oldMentions, e.newFallbackContent, e.newInnerContent)})),
|
|
||||||
eventsToRedact: eventsToRedact.map(e => e.old.event_id),
|
return {roomID, eventsToReplace, eventsToRedact, eventsToSend, senderMxid, promotions}
|
||||||
eventsToSend,
|
|
||||||
senderMxid,
|
|
||||||
promotions
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @template T
|
* @template T
|
||||||
* @param {string} oldID
|
* @param {string} oldID
|
||||||
* @param {any} oldMentions
|
|
||||||
* @param {T} newFallbackContent
|
* @param {T} newFallbackContent
|
||||||
* @param {T} newInnerContent
|
* @param {T} newInnerContent
|
||||||
* @returns {import("../../types").Event.ReplacementContent<T>} content
|
* @returns {import("../../types").Event.ReplacementContent<T>} content
|
||||||
*/
|
*/
|
||||||
function makeReplacementEventContent(oldID, oldMentions, newFallbackContent, newInnerContent) {
|
function makeReplacementEventContent(oldID, newFallbackContent, newInnerContent) {
|
||||||
const mentions = {}
|
|
||||||
const newMentionUsers = new Set(newFallbackContent["m.mentions"]?.user_ids || [])
|
|
||||||
const oldMentionUsers = new Set(oldMentions?.user_ids || [])
|
|
||||||
const mentionDiff = newMentionUsers.difference(oldMentionUsers)
|
|
||||||
if (mentionDiff.size) {
|
|
||||||
mentions.user_ids = [...mentionDiff.values()]
|
|
||||||
}
|
|
||||||
if (newFallbackContent["m.mentions"]?.room && !oldMentions?.room) {
|
|
||||||
mentions.room = true
|
|
||||||
}
|
|
||||||
const content = {
|
const content = {
|
||||||
...newFallbackContent,
|
...newFallbackContent,
|
||||||
"m.mentions": mentions,
|
"m.mentions": {},
|
||||||
"m.new_content": {
|
"m.new_content": {
|
||||||
...newInnerContent
|
...newInnerContent
|
||||||
},
|
},
|
||||||
|
|
@ -264,3 +187,4 @@ function makeReplacementEventContent(oldID, oldMentions, newFallbackContent, new
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.editToChanges = editToChanges
|
module.exports.editToChanges = editToChanges
|
||||||
|
module.exports.makeReplacementEventContent = makeReplacementEventContent
|
||||||
|
|
|
||||||
|
|
@ -4,14 +4,7 @@ const data = require("../../../test/data")
|
||||||
const Ty = require("../../types")
|
const Ty = require("../../types")
|
||||||
|
|
||||||
test("edit2changes: edit by webhook", async t => {
|
test("edit2changes: edit by webhook", async t => {
|
||||||
let called = 0
|
const {senderMxid, eventsToRedact, eventsToReplace, eventsToSend, promotions} = await editToChanges(data.message_update.edit_by_webhook, data.guild.general, {})
|
||||||
const {senderMxid, eventsToRedact, eventsToReplace, eventsToSend, promotions} = await editToChanges(data.message_update.edit_by_webhook, data.guild.general, {
|
|
||||||
getEvent(roomID, eventID) {
|
|
||||||
called++
|
|
||||||
t.equal(eventID, "$zXSlyI78DQqQwwfPUSzZ1b-nXzbUrCDljJgnGDdoI10")
|
|
||||||
return {content: {body: "dummy"}}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.deepEqual(eventsToRedact, [])
|
t.deepEqual(eventsToRedact, [])
|
||||||
t.deepEqual(eventsToSend, [])
|
t.deepEqual(eventsToSend, [])
|
||||||
t.deepEqual(eventsToReplace, [{
|
t.deepEqual(eventsToReplace, [{
|
||||||
|
|
@ -35,22 +28,10 @@ test("edit2changes: edit by webhook", async t => {
|
||||||
}])
|
}])
|
||||||
t.equal(senderMxid, null)
|
t.equal(senderMxid, null)
|
||||||
t.deepEqual(promotions, [])
|
t.deepEqual(promotions, [])
|
||||||
t.equal(called, 1)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test("edit2changes: bot response", async t => {
|
test("edit2changes: bot response", async t => {
|
||||||
const {senderMxid, eventsToRedact, eventsToReplace, eventsToSend, promotions} = await editToChanges(data.message_update.bot_response, data.guild.general, {
|
const {senderMxid, eventsToRedact, eventsToReplace, eventsToSend, promotions} = await editToChanges(data.message_update.bot_response, data.guild.general, {
|
||||||
getEvent(roomID, eventID) {
|
|
||||||
t.equal(eventID, "$fdD9OZ55xg3EAsfvLZza5tMhtjUO91Wg3Otuo96TplY")
|
|
||||||
return {
|
|
||||||
content: {
|
|
||||||
"m.mentions": {
|
|
||||||
user_ids: ["@cadence:cadence.moe"],
|
|
||||||
},
|
|
||||||
body: "dummy"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async getJoinedMembers(roomID) {
|
async getJoinedMembers(roomID) {
|
||||||
t.equal(roomID, "!hYnGGlPHlbujVVfktC:cadence.moe")
|
t.equal(roomID, "!hYnGGlPHlbujVVfktC:cadence.moe")
|
||||||
return new Promise(resolve => {
|
return new Promise(resolve => {
|
||||||
|
|
@ -78,18 +59,18 @@ test("edit2changes: bot response", async t => {
|
||||||
newContent: {
|
newContent: {
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: "* :ae_botrac4r: [@cadence](https://matrix.to/#/@cadence:cadence.moe) asked ````, I respond: Stop drinking paint. (No)\n\nHit :bn_re: to reroll.",
|
body: "* :ae_botrac4r: @cadence asked ````, I respond: Stop drinking paint. (No)\n\nHit :bn_re: to reroll.",
|
||||||
format: "org.matrix.custom.html",
|
format: "org.matrix.custom.html",
|
||||||
formatted_body: '* <img data-mx-emoticon height="32" src="mxc://cadence.moe/skqfuItqxNmBYekzmVKyoLzs" title=":ae_botrac4r:" alt=":ae_botrac4r:"> <a href="https://matrix.to/#/@cadence:cadence.moe">@cadence</a> asked <code></code>, I respond: Stop drinking paint. (No)<br><br>Hit <img data-mx-emoticon height="32" src="mxc://cadence.moe/OIpqpfxTnHKokcsYqDusxkBT" title=":bn_re:" alt=":bn_re:"> to reroll.',
|
formatted_body: '* <img data-mx-emoticon height="32" src="mxc://cadence.moe/skqfuItqxNmBYekzmVKyoLzs" title=":ae_botrac4r:" alt=":ae_botrac4r:"> @cadence asked <code></code>, I respond: Stop drinking paint. (No)<br><br>Hit <img data-mx-emoticon height="32" src="mxc://cadence.moe/OIpqpfxTnHKokcsYqDusxkBT" title=":bn_re:" alt=":bn_re:"> to reroll.',
|
||||||
"m.mentions": {
|
"m.mentions": {
|
||||||
// Client-Server API spec 11.37.7: Copy Discord's behaviour by not re-notifying anyone that an *edit occurred*
|
// Client-Server API spec 11.37.7: Copy Discord's behaviour by not re-notifying anyone that an *edit occurred*
|
||||||
},
|
},
|
||||||
// *** Replaced With: ***
|
// *** Replaced With: ***
|
||||||
"m.new_content": {
|
"m.new_content": {
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: ":ae_botrac4r: [@cadence](https://matrix.to/#/@cadence:cadence.moe) asked ````, I respond: Stop drinking paint. (No)\n\nHit :bn_re: to reroll.",
|
body: ":ae_botrac4r: @cadence asked ````, I respond: Stop drinking paint. (No)\n\nHit :bn_re: to reroll.",
|
||||||
format: "org.matrix.custom.html",
|
format: "org.matrix.custom.html",
|
||||||
formatted_body: '<img data-mx-emoticon height="32" src="mxc://cadence.moe/skqfuItqxNmBYekzmVKyoLzs" title=":ae_botrac4r:" alt=":ae_botrac4r:"> <a href="https://matrix.to/#/@cadence:cadence.moe">@cadence</a> asked <code></code>, I respond: Stop drinking paint. (No)<br><br>Hit <img data-mx-emoticon height="32" src="mxc://cadence.moe/OIpqpfxTnHKokcsYqDusxkBT" title=":bn_re:" alt=":bn_re:"> to reroll.',
|
formatted_body: '<img data-mx-emoticon height="32" src="mxc://cadence.moe/skqfuItqxNmBYekzmVKyoLzs" title=":ae_botrac4r:" alt=":ae_botrac4r:"> @cadence asked <code></code>, I respond: Stop drinking paint. (No)<br><br>Hit <img data-mx-emoticon height="32" src="mxc://cadence.moe/OIpqpfxTnHKokcsYqDusxkBT" title=":bn_re:" alt=":bn_re:"> to reroll.',
|
||||||
"m.mentions": {
|
"m.mentions": {
|
||||||
// Client-Server API spec 11.37.7: This should contain the mentions for the final version of the event
|
// Client-Server API spec 11.37.7: This should contain the mentions for the final version of the event
|
||||||
"user_ids": ["@cadence:cadence.moe"]
|
"user_ids": ["@cadence:cadence.moe"]
|
||||||
|
|
@ -142,14 +123,7 @@ test("edit2changes: add caption back to that image (due to it having a reaction,
|
||||||
})
|
})
|
||||||
|
|
||||||
test("edit2changes: stickers and attachments are not changed, only the content can be edited", async t => {
|
test("edit2changes: stickers and attachments are not changed, only the content can be edited", async t => {
|
||||||
let called = 0
|
const {eventsToRedact, eventsToReplace, eventsToSend} = await editToChanges(data.message_update.edited_content_with_sticker_and_attachments, data.guild.general, {})
|
||||||
const {eventsToRedact, eventsToReplace, eventsToSend} = await editToChanges(data.message_update.edited_content_with_sticker_and_attachments, data.guild.general, {
|
|
||||||
getEvent(roomID, eventID) {
|
|
||||||
called++
|
|
||||||
t.equal(eventID, "$lnAF9IosAECTnlv9p2e18FG8rHn-JgYKHEHIh5qdFv4")
|
|
||||||
return {content: {body: "dummy"}}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.deepEqual(eventsToRedact, [])
|
t.deepEqual(eventsToRedact, [])
|
||||||
t.deepEqual(eventsToSend, [])
|
t.deepEqual(eventsToSend, [])
|
||||||
t.deepEqual(eventsToReplace, [{
|
t.deepEqual(eventsToReplace, [{
|
||||||
|
|
@ -171,16 +145,10 @@ test("edit2changes: stickers and attachments are not changed, only the content c
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}])
|
}])
|
||||||
t.equal(called, 1)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test("edit2changes: edit of reply to skull webp attachment with content", async t => {
|
test("edit2changes: edit of reply to skull webp attachment with content", async t => {
|
||||||
const {eventsToRedact, eventsToReplace, eventsToSend} = await editToChanges(data.message_update.edit_of_reply_to_skull_webp_attachment_with_content, data.guild.general, {
|
const {eventsToRedact, eventsToReplace, eventsToSend} = await editToChanges(data.message_update.edit_of_reply_to_skull_webp_attachment_with_content, data.guild.general, {})
|
||||||
getEvent(roomID, eventID) {
|
|
||||||
t.equal(eventID, "$vgTKOR5ZTYNMKaS7XvgEIDaOWZtVCEyzLLi5Pc5Gz4M")
|
|
||||||
return {content: {body: "dummy"}}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.deepEqual(eventsToRedact, [])
|
t.deepEqual(eventsToRedact, [])
|
||||||
t.deepEqual(eventsToSend, [])
|
t.deepEqual(eventsToSend, [])
|
||||||
t.deepEqual(eventsToReplace, [{
|
t.deepEqual(eventsToReplace, [{
|
||||||
|
|
@ -188,7 +156,12 @@ test("edit2changes: edit of reply to skull webp attachment with content", async
|
||||||
newContent: {
|
newContent: {
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: "* Edit",
|
body: "> Extremity: Image\n\n* Edit",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body:
|
||||||
|
'<mx-reply><blockquote><a href="https://matrix.to/#/!kLRqKKUQXcibIMtOpl:cadence.moe/$oLyUTyZ_7e_SUzGNWZKz880ll9amLZvXGbArJCKai2Q">In reply to</a> Extremity'
|
||||||
|
+ '<br>Image</blockquote></mx-reply>'
|
||||||
|
+ '* Edit',
|
||||||
"m.mentions": {},
|
"m.mentions": {},
|
||||||
"m.new_content": {
|
"m.new_content": {
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
|
|
@ -204,12 +177,7 @@ test("edit2changes: edit of reply to skull webp attachment with content", async
|
||||||
})
|
})
|
||||||
|
|
||||||
test("edit2changes: edits the text event when multiple rows have part = 0 (should never happen in real life, but make sure the safety net works)", async t => {
|
test("edit2changes: edits the text event when multiple rows have part = 0 (should never happen in real life, but make sure the safety net works)", async t => {
|
||||||
const {eventsToRedact, eventsToReplace, eventsToSend} = await editToChanges(data.message_update.edited_content_with_sticker_and_attachments_but_all_parts_equal_0, data.guild.general, {
|
const {eventsToRedact, eventsToReplace, eventsToSend} = await editToChanges(data.message_update.edited_content_with_sticker_and_attachments_but_all_parts_equal_0, data.guild.general, {})
|
||||||
getEvent(roomID, eventID) {
|
|
||||||
t.equal(eventID, "$lnAF9IosAECTnlv9p2e18FG8rHn-JgYKHEHIh5qd999")
|
|
||||||
return {content: {body: "dummy"}}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.deepEqual(eventsToRedact, [])
|
t.deepEqual(eventsToRedact, [])
|
||||||
t.deepEqual(eventsToSend, [])
|
t.deepEqual(eventsToSend, [])
|
||||||
t.deepEqual(eventsToReplace, [{
|
t.deepEqual(eventsToReplace, [{
|
||||||
|
|
@ -234,12 +202,7 @@ test("edit2changes: edits the text event when multiple rows have part = 0 (shoul
|
||||||
})
|
})
|
||||||
|
|
||||||
test("edit2changes: promotes the text event when multiple rows have part = 1 (should never happen in real life, but make sure the safety net works)", async t => {
|
test("edit2changes: promotes the text event when multiple rows have part = 1 (should never happen in real life, but make sure the safety net works)", async t => {
|
||||||
const {eventsToRedact, eventsToReplace, eventsToSend, promotions} = await editToChanges(data.message_update.edited_content_with_sticker_and_attachments_but_all_parts_equal_1, data.guild.general, {
|
const {eventsToRedact, eventsToReplace, eventsToSend, promotions} = await editToChanges(data.message_update.edited_content_with_sticker_and_attachments_but_all_parts_equal_1, data.guild.general, {})
|
||||||
getEvent(roomID, eventID) {
|
|
||||||
t.equal(eventID, "$lnAF9IosAECTnlv9p2e18FG8rHn-JgYKHEHIh5qd111")
|
|
||||||
return {content: {body: "dummy"}}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.deepEqual(eventsToRedact, [])
|
t.deepEqual(eventsToRedact, [])
|
||||||
t.deepEqual(eventsToSend, [])
|
t.deepEqual(eventsToSend, [])
|
||||||
t.deepEqual(eventsToReplace, [{
|
t.deepEqual(eventsToReplace, [{
|
||||||
|
|
@ -273,61 +236,6 @@ test("edit2changes: promotes the text event when multiple rows have part = 1 (sh
|
||||||
])
|
])
|
||||||
})
|
})
|
||||||
|
|
||||||
test("edit2changes: promotes newly sent event", async t => {
|
|
||||||
const {eventsToReplace, eventsToRedact, eventsToSend, promotions} = await editToChanges({
|
|
||||||
channel_id: "1160894080998461480",
|
|
||||||
id: "1404133238414376971",
|
|
||||||
content: "hi",
|
|
||||||
attachments: [{
|
|
||||||
id: "1157854643037163610",
|
|
||||||
filename: "Screenshot_20231001_034036.jpg",
|
|
||||||
size: 51981,
|
|
||||||
url: "https://cdn.discordapp.com/attachments/176333891320283136/1157854643037163610/Screenshot_20231001_034036.jpg?ex=651a1faa&is=6518ce2a&hm=eb5ca80a3fa7add8765bf404aea2028a28a2341e4a62435986bcdcf058da82f3&",
|
|
||||||
proxy_url: "https://media.discordapp.net/attachments/176333891320283136/1157854643037163610/Screenshot_20231001_034036.jpg?ex=651a1faa&is=6518ce2a&hm=eb5ca80a3fa7add8765bf404aea2028a28a2341e4a62435986bcdcf058da82f3&",
|
|
||||||
width: 1080,
|
|
||||||
height: 1170,
|
|
||||||
content_type: "image/jpeg"
|
|
||||||
}],
|
|
||||||
author: {
|
|
||||||
username: "cadence.worm",
|
|
||||||
global_name: "Cadence"
|
|
||||||
}
|
|
||||||
}, data.guild.general, {
|
|
||||||
async getEvent(roomID, eventID) {
|
|
||||||
t.equal(eventID, "$uUKLcTQvik5tgtTGDKuzn0Ci4zcCvSoUcYn2X7mXm9I")
|
|
||||||
return {
|
|
||||||
type: "m.room.message",
|
|
||||||
sender: "@_ooye_cadence.worm:cadence.moe",
|
|
||||||
content: {
|
|
||||||
msgtype: "m.text",
|
|
||||||
body: "hi"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.deepEqual(eventsToRedact, ["$LhmoWWvYyn5_AHkfb6FaXmLI6ZOC1kloql5P40YDmIk"])
|
|
||||||
t.deepEqual(eventsToReplace, [])
|
|
||||||
t.deepEqual(eventsToSend, [{
|
|
||||||
$type: "m.room.message",
|
|
||||||
body: "Screenshot_20231001_034036.jpg",
|
|
||||||
external_url: "https://bridge.example.org/download/discordcdn/176333891320283136/1157854643037163610/Screenshot_20231001_034036.jpg",
|
|
||||||
filename: "Screenshot_20231001_034036.jpg",
|
|
||||||
info: {
|
|
||||||
mimetype: "image/jpeg",
|
|
||||||
size: 51981,
|
|
||||||
w: 1080,
|
|
||||||
h: 1170
|
|
||||||
},
|
|
||||||
url: "mxc://cadence.moe/zAXdQriaJuLZohDDmacwWWDR",
|
|
||||||
"m.mentions": {},
|
|
||||||
msgtype: "m.image"
|
|
||||||
}])
|
|
||||||
t.deepEqual(promotions, [
|
|
||||||
{column: "reaction_part", nextEvent: true}
|
|
||||||
])
|
|
||||||
// assert that the event parts will be consistent in database after this
|
|
||||||
})
|
|
||||||
|
|
||||||
test("edit2changes: generated embed", async t => {
|
test("edit2changes: generated embed", async t => {
|
||||||
let called = 0
|
let called = 0
|
||||||
const {senderMxid, eventsToRedact, eventsToReplace, eventsToSend, promotions} = await editToChanges(data.message_update.embed_generated_social_media_image, data.guild.general, {
|
const {senderMxid, eventsToRedact, eventsToReplace, eventsToSend, promotions} = await editToChanges(data.message_update.embed_generated_social_media_image, data.guild.general, {
|
||||||
|
|
@ -371,32 +279,32 @@ test("edit2changes: generated embed", async t => {
|
||||||
})
|
})
|
||||||
|
|
||||||
test("edit2changes: generated embed on a reply", async t => {
|
test("edit2changes: generated embed on a reply", async t => {
|
||||||
let called = 0
|
const {senderMxid, eventsToRedact, eventsToReplace, eventsToSend, promotions} = await editToChanges(data.message_update.embed_generated_on_reply, data.guild.general, {})
|
||||||
data.message_update.embed_generated_on_reply.timestamp = new Date().toISOString()
|
t.deepEqual(eventsToRedact, [])
|
||||||
const {senderMxid, eventsToRedact, eventsToReplace, eventsToSend, promotions} = await editToChanges(data.message_update.embed_generated_on_reply, data.guild.general, {
|
t.deepEqual(eventsToReplace, [{
|
||||||
getEvent(roomID, eventID) {
|
oldID: "$UTqiL3Zj3FC4qldxRLggN1fhygpKl8sZ7XGY5f9MNbF",
|
||||||
called++
|
newContent: {
|
||||||
t.equal(eventID, "$UTqiL3Zj3FC4qldxRLggN1fhygpKl8sZ7XGY5f9MNbF")
|
$type: "m.room.message",
|
||||||
return {
|
|
||||||
type: "m.room.message",
|
|
||||||
content: {
|
|
||||||
// Unfortunately the edited message doesn't include the message_reference field. Fine. Whatever. It looks normal if you're using a good client.
|
// Unfortunately the edited message doesn't include the message_reference field. Fine. Whatever. It looks normal if you're using a good client.
|
||||||
body: "> a Discord user: [Replied-to message content wasn't provided by Discord]"
|
body: "> a Discord user: [Replied-to message content wasn't provided by Discord]"
|
||||||
+ "\n\nhttps://matrix.to/#/!BnKuBPCvyfOkhcUjEu:cadence.moe/$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM",
|
+ "\n\n* https://matrix.to/#/!BnKuBPCvyfOkhcUjEu:cadence.moe/$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM",
|
||||||
format: "org.matrix.custom.html",
|
format: "org.matrix.custom.html",
|
||||||
formatted_body: "<mx-reply><blockquote><a href=\"https://matrix.to/#/!BnKuBPCvyfOkhcUjEu:cadence.moe/$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM\">In reply to</a> a Discord user<br>[Replied-to message content wasn't provided by Discord]</blockquote></mx-reply><a href=\"https://matrix.to/#/!BnKuBPCvyfOkhcUjEu:cadence.moe/$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM\">https://matrix.to/#/!BnKuBPCvyfOkhcUjEu:cadence.moe/$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM</a>",
|
formatted_body: "<mx-reply><blockquote><a href=\"https://matrix.to/#/!BnKuBPCvyfOkhcUjEu:cadence.moe/$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM\">In reply to</a> a Discord user<br>[Replied-to message content wasn't provided by Discord]</blockquote></mx-reply>* <a href=\"https://matrix.to/#/!BnKuBPCvyfOkhcUjEu:cadence.moe/$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM\">https://matrix.to/#/!BnKuBPCvyfOkhcUjEu:cadence.moe/$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM</a>",
|
||||||
"m.mentions": {},
|
"m.mentions": {},
|
||||||
|
"m.new_content": {
|
||||||
|
body: "https://matrix.to/#/!BnKuBPCvyfOkhcUjEu:cadence.moe/$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: "<a href=\"https://matrix.to/#/!BnKuBPCvyfOkhcUjEu:cadence.moe/$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM\">https://matrix.to/#/!BnKuBPCvyfOkhcUjEu:cadence.moe/$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM</a>",
|
||||||
|
"m.mentions": {},
|
||||||
|
msgtype: "m.text",
|
||||||
|
},
|
||||||
"m.relates_to": {
|
"m.relates_to": {
|
||||||
event_id: "$UTqiL3Zj3FC4qldxRLggN1fhygpKl8sZ7XGY5f9MNbF",
|
event_id: "$UTqiL3Zj3FC4qldxRLggN1fhygpKl8sZ7XGY5f9MNbF",
|
||||||
rel_type: "m.replace",
|
rel_type: "m.replace",
|
||||||
},
|
},
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
}
|
},
|
||||||
}
|
}])
|
||||||
}
|
|
||||||
})
|
|
||||||
t.deepEqual(eventsToRedact, [])
|
|
||||||
t.deepEqual(eventsToReplace, [])
|
|
||||||
t.deepEqual(eventsToSend, [{
|
t.deepEqual(eventsToSend, [{
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
msgtype: "m.notice",
|
msgtype: "m.notice",
|
||||||
|
|
@ -416,23 +324,4 @@ test("edit2changes: generated embed on a reply", async t => {
|
||||||
"nextEvent": true,
|
"nextEvent": true,
|
||||||
}])
|
}])
|
||||||
t.equal(senderMxid, "@_ooye_cadence:cadence.moe")
|
t.equal(senderMxid, "@_ooye_cadence:cadence.moe")
|
||||||
t.equal(called, 1)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("edit2changes: don't generate embed if it's been too long since the message", async t => {
|
|
||||||
const {senderMxid, eventsToRedact, eventsToReplace, eventsToSend, promotions} = await editToChanges(data.message_update.embed_generated_social_media_image_for_matrix_user, data.guild.general)
|
|
||||||
t.deepEqual(eventsToRedact, [])
|
|
||||||
t.deepEqual(eventsToReplace, [])
|
|
||||||
t.deepEqual(eventsToSend, [])
|
|
||||||
t.deepEqual(promotions, [])
|
|
||||||
t.equal(senderMxid, null)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("edit2changes: don't generate new data in situations where m->d(->m) subtypes don't match, like large files", async t => {
|
|
||||||
const {senderMxid, eventsToRedact, eventsToReplace, eventsToSend, promotions} = await editToChanges(data.message.large_file_from_matrix)
|
|
||||||
t.deepEqual(eventsToRedact, [])
|
|
||||||
t.deepEqual(eventsToReplace, [])
|
|
||||||
t.deepEqual(eventsToSend, [])
|
|
||||||
t.deepEqual(promotions, [])
|
|
||||||
t.equal(senderMxid, null)
|
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -8,10 +8,9 @@ const file = sync.require("../../matrix/file")
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {import("discord-api-types/v10").APIEmoji} emoji
|
* @param {import("discord-api-types/v10").APIEmoji} emoji
|
||||||
* @param {string} message_id
|
|
||||||
* @returns {Promise<string>}
|
* @returns {Promise<string>}
|
||||||
*/
|
*/
|
||||||
async function emojiToKey(emoji, message_id) {
|
async function emojiToKey(emoji) {
|
||||||
let key
|
let key
|
||||||
if (emoji.id) {
|
if (emoji.id) {
|
||||||
// Custom emoji
|
// Custom emoji
|
||||||
|
|
@ -31,10 +30,7 @@ async function emojiToKey(emoji, message_id) {
|
||||||
// Default emoji
|
// Default emoji
|
||||||
const name = emoji.name
|
const name = emoji.name
|
||||||
assert(name)
|
assert(name)
|
||||||
// If the reaction was used on Matrix already, it might be using a different arrangement of Variation Selector 16 characters.
|
key = name
|
||||||
// We'll use the same arrangement that was originally used, otherwise a duplicate of the emoji will appear as a separate reaction.
|
|
||||||
const originalEncoding = select("reaction", "original_encoding", {message_id, encoded_emoji: encodeURIComponent(name)}).pluck().get()
|
|
||||||
key = originalEncoding || name
|
|
||||||
}
|
}
|
||||||
return key
|
return key
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,161 +0,0 @@
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const assert = require("assert")
|
|
||||||
|
|
||||||
const {reg} = require("../../matrix/read-registration")
|
|
||||||
const userRegex = reg.namespaces.users.map(u => new RegExp(u.regex))
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @typedef {{text: string, index: number, end: number}} Token
|
|
||||||
*/
|
|
||||||
|
|
||||||
/** @typedef {{mxids: {localpart: string, mxid: string, displayname?: string | null}[], names: {displaynameTokens: Token[], mxid: string}[]}} ProcessedJoined */
|
|
||||||
|
|
||||||
const lengthBonusLengthCap = 50
|
|
||||||
const lengthBonusValue = 0.5
|
|
||||||
/**
|
|
||||||
* Score by how many characters in a row at the start of input are in localpart. 2x if it matches at the start. +1 tiebreaker bonus if it matches all.
|
|
||||||
* 0 = no match
|
|
||||||
* @param {string} localpart
|
|
||||||
* @param {string} input
|
|
||||||
* @param {string | null} [displayname] only for the super tiebreaker
|
|
||||||
* @returns {{score: number, matchedInputTokens: Token[]}}
|
|
||||||
*/
|
|
||||||
function scoreLocalpart(localpart, input, displayname) {
|
|
||||||
let score = 0
|
|
||||||
let atStart = false
|
|
||||||
let matchingLocations = []
|
|
||||||
do {
|
|
||||||
atStart = matchingLocations[0] === 0
|
|
||||||
let chars = input[score]
|
|
||||||
if (score === 0) {
|
|
||||||
// add all possible places
|
|
||||||
let i = 0
|
|
||||||
while ((i = localpart.indexOf(chars, i)) !== -1) {
|
|
||||||
matchingLocations.push(i)
|
|
||||||
i++
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// trim down remaining places
|
|
||||||
matchingLocations = matchingLocations.filter(i => localpart[i+score] === input[score])
|
|
||||||
}
|
|
||||||
if (matchingLocations.length) {
|
|
||||||
score++
|
|
||||||
if (score === localpart.length) break
|
|
||||||
}
|
|
||||||
} while (matchingLocations.length)
|
|
||||||
/** @type {Token} */
|
|
||||||
const fakeToken = {text: input.slice(0, score), index: 0, end: score}
|
|
||||||
const displaynameLength = displayname?.length ?? 0
|
|
||||||
if (score === localpart.length) score = score * 2 + 1 + Math.max(((lengthBonusLengthCap-displaynameLength)/lengthBonusLengthCap)*lengthBonusValue, 0)
|
|
||||||
else if (atStart) score = score * 2
|
|
||||||
return {score, matchedInputTokens: [fakeToken]}
|
|
||||||
}
|
|
||||||
|
|
||||||
const decayDistance = 20
|
|
||||||
const decayValue = 0.33
|
|
||||||
/**
|
|
||||||
* Score by how many tokens in sequence (not necessarily back to back) at the start of input are in display name tokens. Score each token on its length. 2x if it matches at the start. +1 tiebreaker bonus if it matches all
|
|
||||||
* @param {Token[]} displaynameTokens
|
|
||||||
* @param {Token[]} inputTokens
|
|
||||||
* @returns {{score: number, matchedInputTokens: Token[]}}
|
|
||||||
*/
|
|
||||||
function scoreName(displaynameTokens, inputTokens) {
|
|
||||||
let matchedInputTokens = []
|
|
||||||
let score = 0
|
|
||||||
let searchFrom = 0
|
|
||||||
for (let nextInputTokenIndex = 0; nextInputTokenIndex < inputTokens.length; nextInputTokenIndex++) {
|
|
||||||
// take next
|
|
||||||
const nextToken = inputTokens[nextInputTokenIndex]
|
|
||||||
// see if it's there
|
|
||||||
let foundAt = displaynameTokens.findIndex((tk, idx) => idx >= searchFrom && tk.text === nextToken.text)
|
|
||||||
if (foundAt !== -1) {
|
|
||||||
// update scoring
|
|
||||||
matchedInputTokens.push(nextToken)
|
|
||||||
score += nextToken.text.length * Math.max(((decayDistance-foundAt)*(1+decayValue))/(decayDistance*(1+decayValue)), decayValue) // decay score 100%->33% the further into the displayname it's found
|
|
||||||
// prepare for next loop
|
|
||||||
searchFrom = foundAt + 1
|
|
||||||
} else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const firstTextualInputToken = inputTokens.find(t => t.text.match(/^\w/))
|
|
||||||
if (matchedInputTokens[0] === inputTokens[0] || matchedInputTokens[0] === firstTextualInputToken) score *= 2
|
|
||||||
if (matchedInputTokens.length === displaynameTokens.length) score += 1
|
|
||||||
return {score, matchedInputTokens}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {string} name
|
|
||||||
* @returns {Token[]}
|
|
||||||
*/
|
|
||||||
function tokenise(name) {
|
|
||||||
name = name.replaceAll("\ufe0f", "").normalize().toLowerCase()
|
|
||||||
let index = 0
|
|
||||||
let result = []
|
|
||||||
for (const part of name.split(/(_|\s|\b)/g)) {
|
|
||||||
if (part.trim()) {
|
|
||||||
result.push({text: part, index, end: index + part.length})
|
|
||||||
}
|
|
||||||
index += part.length
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {{mxid: string, displayname?: string | null}[]} joined
|
|
||||||
* @returns {ProcessedJoined}
|
|
||||||
*/
|
|
||||||
function processJoined(joined) {
|
|
||||||
joined = joined.filter(j => !userRegex.some(rx => j.mxid.match(rx)))
|
|
||||||
return {
|
|
||||||
mxids: joined.map(j => {
|
|
||||||
const localpart = j.mxid.match(/@([^:]*)/)
|
|
||||||
assert(localpart)
|
|
||||||
return {
|
|
||||||
localpart: localpart[1].toLowerCase(),
|
|
||||||
mxid: j.mxid,
|
|
||||||
displayname: j.displayname
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
names: joined.filter(j => j.displayname).map(j => {
|
|
||||||
return {
|
|
||||||
// @ts-ignore
|
|
||||||
displaynameTokens: tokenise(j.displayname),
|
|
||||||
mxid: j.mxid
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {ProcessedJoined} pjr
|
|
||||||
* @param {string} maximumWrittenSection lowercase please
|
|
||||||
* @param {number} baseOffset
|
|
||||||
* @param {string} prefix
|
|
||||||
* @param {string} content
|
|
||||||
*/
|
|
||||||
function findMention(pjr, maximumWrittenSection, baseOffset, prefix, content) {
|
|
||||||
if (!pjr.mxids.length && !pjr.names.length) return
|
|
||||||
const maximumWrittenSectionTokens = tokenise(maximumWrittenSection)
|
|
||||||
/** @type {{mxid: string, scored: {score: number, matchedInputTokens: Token[]}}[]} */
|
|
||||||
let allItems = pjr.mxids.map(mxid => ({...mxid, scored: scoreLocalpart(mxid.localpart, maximumWrittenSection, mxid.displayname)}))
|
|
||||||
allItems = allItems.concat(pjr.names.map(name => ({...name, scored: scoreName(name.displaynameTokens, maximumWrittenSectionTokens)})))
|
|
||||||
const best = allItems.sort((a, b) => b.scored.score - a.scored.score)[0]
|
|
||||||
if (best.scored.score > 4) { // requires in smallest case perfect match of 2 characters, or in largest case a partial middle match of 5+ characters in a row
|
|
||||||
// Highlight the relevant part of the message
|
|
||||||
const start = baseOffset + best.scored.matchedInputTokens[0].index
|
|
||||||
const end = baseOffset + prefix.length + best.scored.matchedInputTokens.slice(-1)[0].end
|
|
||||||
const newContent = content.slice(0, start) + "[" + content.slice(start, end) + "](https://matrix.to/#/" + best.mxid + ")" + content.slice(end)
|
|
||||||
return {
|
|
||||||
mxid: best.mxid,
|
|
||||||
newContent
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports.scoreLocalpart = scoreLocalpart
|
|
||||||
module.exports.scoreName = scoreName
|
|
||||||
module.exports.tokenise = tokenise
|
|
||||||
module.exports.processJoined = processJoined
|
|
||||||
module.exports.findMention = findMention
|
|
||||||
|
|
@ -1,129 +0,0 @@
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const {test} = require("supertape")
|
|
||||||
const {processJoined, scoreLocalpart, scoreName, tokenise, findMention} = require("./find-mentions")
|
|
||||||
|
|
||||||
test("score localpart: score against cadence", t => {
|
|
||||||
const localparts = [
|
|
||||||
"cadence",
|
|
||||||
"cadence_test",
|
|
||||||
"roblkyogre",
|
|
||||||
"cat",
|
|
||||||
"arcade_cabinet"
|
|
||||||
]
|
|
||||||
t.deepEqual(localparts.map(l => scoreLocalpart(l, "cadence").score), [
|
|
||||||
15.5,
|
|
||||||
14,
|
|
||||||
0,
|
|
||||||
4,
|
|
||||||
4
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("score mxid: tiebreak multiple perfect matches on name length", t => {
|
|
||||||
const users = [
|
|
||||||
{displayname: "Emma [it/its] ⚡️", localpart: "emma"},
|
|
||||||
{displayname: "Emma [it/its]", localpart: "emma"}
|
|
||||||
]
|
|
||||||
const results = users.map(u => scoreLocalpart(u.localpart, "emma", u.displayname).score)
|
|
||||||
t.ok(results[0] < results[1], `comparison: ${results.join(" < ")}`)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("score name: score against cadence", t => {
|
|
||||||
const names = [
|
|
||||||
"bgt lover",
|
|
||||||
"Ash 🦑 (xey/it)",
|
|
||||||
"Cadence, Maid of Creation, Eye of Clarity, Empress of Hope ☆",
|
|
||||||
"underscore_idiot #sunshine",
|
|
||||||
"INX | Evil Lillith (she/her)",
|
|
||||||
"INX | Lillith (she/her)",
|
|
||||||
"🌟luna🌟",
|
|
||||||
"#1 Ritsuko Kinnie"
|
|
||||||
]
|
|
||||||
t.deepEqual(names.map(n => scoreName(tokenise(n), tokenise("cadence")).score), [
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
14,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("score name: nothing scored after a token doesn't match", t => {
|
|
||||||
const names = [
|
|
||||||
"bgt lover",
|
|
||||||
"Ash 🦑 (xey/it)",
|
|
||||||
"Cadence, Maid of Creation, Eye of Clarity, Empress of Hope ☆",
|
|
||||||
"underscore_idiot #sunshine",
|
|
||||||
"INX | Evil Lillith (she/her)",
|
|
||||||
"INX | Lillith (she/her)",
|
|
||||||
"🌟luna🌟",
|
|
||||||
"#1 Ritsuko Kinnie"
|
|
||||||
]
|
|
||||||
t.deepEqual(names.map(n => scoreName(tokenise(n), tokenise("I hope so")).score), [
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("score name: prefers earlier match", t => {
|
|
||||||
const names = [
|
|
||||||
"INX | Lillith (she/her)",
|
|
||||||
"INX | Evil Lillith (she/her)"
|
|
||||||
]
|
|
||||||
const results = names.map(n => scoreName(tokenise(n), tokenise("lillith")).score)
|
|
||||||
t.ok(results[0] > results[1], `comparison: ${results.join(" > ")}`)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("score name: matches lots of tokens", t => {
|
|
||||||
t.deepEqual(
|
|
||||||
Math.round(scoreName(tokenise("Cadence, Maid of Creation, Eye of Clarity, Empress of Hope ☆"), tokenise("cadence maid of creation eye of clarity empress of hope")).score),
|
|
||||||
65
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("score name: prefers variation when you specify it", t => {
|
|
||||||
const names = [
|
|
||||||
"Cadence (test account)",
|
|
||||||
"Cadence"
|
|
||||||
]
|
|
||||||
const results = names.map(n => scoreName(tokenise(n), tokenise("cadence test")).score)
|
|
||||||
t.ok(results[0] > results[1], `comparison: ${results.join(" > ")}`)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("score name: prefers original when not specified", t => {
|
|
||||||
const names = [
|
|
||||||
"Cadence (test account)",
|
|
||||||
"Cadence"
|
|
||||||
]
|
|
||||||
const results = names.map(n => scoreName(tokenise(n), tokenise("cadence")).score)
|
|
||||||
t.ok(results[0] < results[1], `comparison: ${results.join(" < ")}`)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("score name: finds match location", t => {
|
|
||||||
const message = "evil lillith is an inspiration"
|
|
||||||
const result = scoreName(tokenise("INX | Evil Lillith (she/her)"), tokenise(message))
|
|
||||||
const startLocation = result.matchedInputTokens[0].index
|
|
||||||
const endLocation = result.matchedInputTokens.slice(-1)[0].end
|
|
||||||
t.equal(message.slice(startLocation, endLocation), "evil lillith")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("find mention: test various tiebreakers", t => {
|
|
||||||
const found = findMention(processJoined([{
|
|
||||||
mxid: "@emma:conduit.rory.gay",
|
|
||||||
displayname: "Emma [it/its] ⚡️"
|
|
||||||
}, {
|
|
||||||
mxid: "@emma:rory.gay",
|
|
||||||
displayname: "Emma [it/its]"
|
|
||||||
}]), "emma ⚡ curious which one this prefers", 0, "@", "@emma ⚡ curious which one this prefers")
|
|
||||||
t.equal(found?.mxid, "@emma:conduit.rory.gay")
|
|
||||||
})
|
|
||||||
|
|
@ -21,7 +21,7 @@ const Rlottie = (async () => {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {string} text
|
* @param {string} text
|
||||||
* @returns {Promise<stream.Readable>}
|
* @returns {Promise<import("stream").Readable>}
|
||||||
*/
|
*/
|
||||||
async function convert(text) {
|
async function convert(text) {
|
||||||
const r = await Rlottie
|
const r = await Rlottie
|
||||||
|
|
@ -41,7 +41,6 @@ async function convert(text) {
|
||||||
png.data = Buffer.from(rendered)
|
png.data = Buffer.from(rendered)
|
||||||
// png.pack() is a bad stream and will throw away any data it sends if it's not connected to a destination straight away.
|
// png.pack() is a bad stream and will throw away any data it sends if it's not connected to a destination straight away.
|
||||||
// We use Duplex.from to convert it into a good stream.
|
// We use Duplex.from to convert it into a good stream.
|
||||||
// @ts-ignore
|
|
||||||
return stream.Duplex.from(png.pack())
|
return stream.Duplex.from(png.pack())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,34 +1,26 @@
|
||||||
const {test} = require("supertape")
|
const {test} = require("supertape")
|
||||||
const {messageToEvent} = require("./message-to-event")
|
const {messageToEvent} = require("./message-to-event")
|
||||||
const data = require("../../../test/data")
|
const data = require("../../../test/data")
|
||||||
const {mockGetEffectivePower} = require("../../matrix/utils.test")
|
const Ty = require("../../types")
|
||||||
const {db} = require("../../passthrough")
|
|
||||||
|
|
||||||
test("message2event embeds: interaction loading", async t => {
|
|
||||||
const events = await messageToEvent(data.interaction_message.thinking_interaction, data.guild.general, {})
|
|
||||||
t.deepEqual(events, [{
|
|
||||||
$type: "m.room.message",
|
|
||||||
body: "↪️ Brad used `/stats` — interaction loading...",
|
|
||||||
format: "org.matrix.custom.html",
|
|
||||||
formatted_body: "<blockquote><sub>↪️ <a href=\"https://matrix.to/#/@_ooye_papiophidian:cadence.moe\">Brad</a> used <code>/stats</code> — interaction loading...</sub></blockquote>",
|
|
||||||
"m.mentions": {},
|
|
||||||
msgtype: "m.notice",
|
|
||||||
}])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("message2event embeds: nothing but a field", async t => {
|
test("message2event embeds: nothing but a field", async t => {
|
||||||
const events = await messageToEvent(data.message_with_embeds.nothing_but_a_field, data.guild.general, {})
|
const events = await messageToEvent(data.message_with_embeds.nothing_but_a_field, data.guild.general, {})
|
||||||
t.deepEqual(events, [{
|
t.deepEqual(events, [{
|
||||||
|
$type: "m.room.message",
|
||||||
|
body: "> ↪️ @papiophidian: used `/stats`",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: "<blockquote>↪️ <a href=\"https://matrix.to/#/@_ooye_papiophidian:cadence.moe\">@papiophidian</a> used <code>/stats</code></blockquote>",
|
||||||
|
"m.mentions": {},
|
||||||
|
msgtype: "m.text",
|
||||||
|
}, {
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
"m.mentions": {},
|
"m.mentions": {},
|
||||||
msgtype: "m.notice",
|
msgtype: "m.notice",
|
||||||
body: "↪️ PapiOphidian used `/stats`"
|
body: "| ### Amanda 🎵#2192 :online:"
|
||||||
+ "\n| ### Amanda 🎵#2192 :online:"
|
|
||||||
+ "\n| willow tree, branch 0"
|
+ "\n| willow tree, branch 0"
|
||||||
+ "\n| **❯ Uptime:**\n| 3m 55s\n| **❯ Memory:**\n| 64.45MB",
|
+ "\n| **❯ Uptime:**\n| 3m 55s\n| **❯ Memory:**\n| 64.45MB",
|
||||||
format: "org.matrix.custom.html",
|
format: "org.matrix.custom.html",
|
||||||
formatted_body: '<blockquote><sub>↪️ <a href=\"https://matrix.to/#/@_ooye_papiophidian:cadence.moe\">PapiOphidian</a> used <code>/stats</code></sub></blockquote>'
|
formatted_body: '<blockquote><p><strong>Amanda 🎵#2192 <img data-mx-emoticon height=\"32\" src=\"mxc://cadence.moe/LCEqjStXCxvRQccEkuslXEyZ\" title=\":online:\" alt=\":online:\">'
|
||||||
+ '<blockquote><p><strong>Amanda 🎵#2192 <img data-mx-emoticon height=\"32\" src=\"mxc://cadence.moe/LCEqjStXCxvRQccEkuslXEyZ\" title=\":online:\" alt=\":online:\">'
|
|
||||||
+ '<br>willow tree, branch 0</strong>'
|
+ '<br>willow tree, branch 0</strong>'
|
||||||
+ '<br><strong>❯ Uptime:</strong><br>3m 55s'
|
+ '<br><strong>❯ Uptime:</strong><br>3m 55s'
|
||||||
+ '<br><strong>❯ Memory:</strong><br>64.45MB</p></blockquote>'
|
+ '<br><strong>❯ Memory:</strong><br>64.45MB</p></blockquote>'
|
||||||
|
|
@ -41,9 +33,7 @@ test("message2event embeds: reply with just an embed", async t => {
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
msgtype: "m.notice",
|
msgtype: "m.notice",
|
||||||
"m.mentions": {},
|
"m.mentions": {},
|
||||||
body: "> In reply to an unbridged message:"
|
body: "| ## ⏺️ dynastic (@dynastic) https://twitter.com/i/user/719631291747078145"
|
||||||
+ "\n> PokemonGod: https://twitter.com/dynastic/status/1707484191963648161"
|
|
||||||
+ "\n\n| ## ⏺️ dynastic (@dynastic) https://twitter.com/i/user/719631291747078145"
|
|
||||||
+ "\n| \n| does anyone know where to find that one video of the really mysterious yam-like object being held up to a bunch of random objects, like clocks, and they have unexplained impossible reactions to it?"
|
+ "\n| \n| does anyone know where to find that one video of the really mysterious yam-like object being held up to a bunch of random objects, like clocks, and they have unexplained impossible reactions to it?"
|
||||||
+ "\n| \n| ### Retweets"
|
+ "\n| \n| ### Retweets"
|
||||||
+ "\n| 119"
|
+ "\n| 119"
|
||||||
|
|
@ -51,8 +41,7 @@ test("message2event embeds: reply with just an embed", async t => {
|
||||||
+ "\n| 5581"
|
+ "\n| 5581"
|
||||||
+ "\n| — Twitter",
|
+ "\n| — Twitter",
|
||||||
format: "org.matrix.custom.html",
|
format: "org.matrix.custom.html",
|
||||||
formatted_body: '<blockquote>In reply to an unbridged message from PokemonGod:<br><a href=\"https://twitter.com/dynastic/status/1707484191963648161\">https://twitter.com/dynastic/status/1707484191963648161</a></blockquote>'
|
formatted_body: '<blockquote><p><strong><a href="https://twitter.com/i/user/719631291747078145">⏺️ dynastic (@dynastic)</a></strong>'
|
||||||
+ '<blockquote><p><strong><a href="https://twitter.com/i/user/719631291747078145">⏺️ dynastic (@dynastic)</a></strong>'
|
|
||||||
+ '</p><p>does anyone know where to find that one video of the really mysterious yam-like object being held up to a bunch of random objects, like clocks, and they have unexplained impossible reactions to it?'
|
+ '</p><p>does anyone know where to find that one video of the really mysterious yam-like object being held up to a bunch of random objects, like clocks, and they have unexplained impossible reactions to it?'
|
||||||
+ '</p><p><strong>Retweets</strong><br>119</p><p><strong>Likes</strong><br>5581</p>— Twitter</blockquote>'
|
+ '</p><p><strong>Retweets</strong><br>119</p><p><strong>Likes</strong><br>5581</p>— Twitter</blockquote>'
|
||||||
}])
|
}])
|
||||||
|
|
@ -78,7 +67,7 @@ test("message2event embeds: image embed and attachment", async t => {
|
||||||
msgtype: "m.image",
|
msgtype: "m.image",
|
||||||
url: "mxc://cadence.moe/zAXdQriaJuLZohDDmacwWWDR",
|
url: "mxc://cadence.moe/zAXdQriaJuLZohDDmacwWWDR",
|
||||||
body: "Screenshot_20231001_034036.jpg",
|
body: "Screenshot_20231001_034036.jpg",
|
||||||
external_url: "https://bridge.example.org/download/discordcdn/176333891320283136/1157854643037163610/Screenshot_20231001_034036.jpg",
|
external_url: "https://cdn.discordapp.com/attachments/176333891320283136/1157854643037163610/Screenshot_20231001_034036.jpg?ex=651a1faa&is=6518ce2a&hm=eb5ca80a3fa7add8765bf404aea2028a28a2341e4a62435986bcdcf058da82f3&",
|
||||||
filename: "Screenshot_20231001_034036.jpg",
|
filename: "Screenshot_20231001_034036.jpg",
|
||||||
info: {
|
info: {
|
||||||
h: 1170,
|
h: 1170,
|
||||||
|
|
@ -94,7 +83,17 @@ test("message2event embeds: blockquote in embed", async t => {
|
||||||
let called = 0
|
let called = 0
|
||||||
const events = await messageToEvent(data.message_with_embeds.blockquote_in_embed, data.guild.general, {}, {
|
const events = await messageToEvent(data.message_with_embeds.blockquote_in_embed, data.guild.general, {}, {
|
||||||
api: {
|
api: {
|
||||||
getEffectivePower: mockGetEffectivePower(),
|
async getStateEvent(roomID, type, key) {
|
||||||
|
called++
|
||||||
|
t.equal(roomID, "!qzDBLKlildpzrrOnFZ:cadence.moe")
|
||||||
|
t.equal(type, "m.room.power_levels")
|
||||||
|
t.equal(key, "")
|
||||||
|
return {
|
||||||
|
users: {
|
||||||
|
"@_ooye_bot:cadence.moe": 100
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
async getJoinedMembers(roomID) {
|
async getJoinedMembers(roomID) {
|
||||||
called++
|
called++
|
||||||
t.equal(roomID, "!qzDBLKlildpzrrOnFZ:cadence.moe")
|
t.equal(roomID, "!qzDBLKlildpzrrOnFZ:cadence.moe")
|
||||||
|
|
@ -122,7 +121,7 @@ test("message2event embeds: blockquote in embed", async t => {
|
||||||
formatted_body: "<blockquote><p><strong><a href=\"https://matrix.to/#/!qzDBLKlildpzrrOnFZ:cadence.moe/$dVCLyj6kxb3DaAWDtjcv2kdSny8JMMHdDhCMz8mDxVo?via=cadence.moe&via=example.invalid\">⏺️ minimus</a></strong></p><p>reply draft<br><blockquote>The following is a message composed via consensus of the Stinker Council.<br><br>For those who are not currently aware of our existence, we represent the organization known as Wonderland. Our previous mission centered around the assortment and study of puzzling objects, entities and other assorted phenomena. This mission was the focus of our organization for more than 28 years.<br><br>Due to circumstances outside of our control, this directive has now changed. Our new mission will be the extermination of the stinker race.<br><br>There will be no further communication.</blockquote></p><p><a href=\"https://matrix.to/#/!qzDBLKlildpzrrOnFZ:cadence.moe/$dVCLyj6kxb3DaAWDtjcv2kdSny8JMMHdDhCMz8mDxVo?via=cadence.moe&via=example.invalid\">Go to Message</a></p></blockquote>",
|
formatted_body: "<blockquote><p><strong><a href=\"https://matrix.to/#/!qzDBLKlildpzrrOnFZ:cadence.moe/$dVCLyj6kxb3DaAWDtjcv2kdSny8JMMHdDhCMz8mDxVo?via=cadence.moe&via=example.invalid\">⏺️ minimus</a></strong></p><p>reply draft<br><blockquote>The following is a message composed via consensus of the Stinker Council.<br><br>For those who are not currently aware of our existence, we represent the organization known as Wonderland. Our previous mission centered around the assortment and study of puzzling objects, entities and other assorted phenomena. This mission was the focus of our organization for more than 28 years.<br><br>Due to circumstances outside of our control, this directive has now changed. Our new mission will be the extermination of the stinker race.<br><br>There will be no further communication.</blockquote></p><p><a href=\"https://matrix.to/#/!qzDBLKlildpzrrOnFZ:cadence.moe/$dVCLyj6kxb3DaAWDtjcv2kdSny8JMMHdDhCMz8mDxVo?via=cadence.moe&via=example.invalid\">Go to Message</a></p></blockquote>",
|
||||||
"m.mentions": {}
|
"m.mentions": {}
|
||||||
}])
|
}])
|
||||||
t.equal(called, 1, "should call getJoinedMembers once")
|
t.equal(called, 2, "should call getStateEvent and getJoinedMembers once each")
|
||||||
})
|
})
|
||||||
|
|
||||||
test("message2event embeds: crazy html is all escaped", async t => {
|
test("message2event embeds: crazy html is all escaped", async t => {
|
||||||
|
|
@ -152,12 +151,17 @@ test("message2event embeds: title without url", async t => {
|
||||||
const events = await messageToEvent(data.message_with_embeds.title_without_url, data.guild.general)
|
const events = await messageToEvent(data.message_with_embeds.title_without_url, data.guild.general)
|
||||||
t.deepEqual(events, [{
|
t.deepEqual(events, [{
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
msgtype: "m.notice",
|
body: "> ↪️ @papiophidian: used `/stats`",
|
||||||
body: "↪️ PapiOphidian used `/stats`"
|
|
||||||
+ "\n| ## Hi, I'm Amanda!\n| \n| I condone pirating music!",
|
|
||||||
format: "org.matrix.custom.html",
|
format: "org.matrix.custom.html",
|
||||||
formatted_body: '<blockquote><sub>↪️ <a href=\"https://matrix.to/#/@_ooye_papiophidian:cadence.moe\">PapiOphidian</a> used <code>/stats</code></sub></blockquote>'
|
formatted_body: "<blockquote>↪️ <a href=\"https://matrix.to/#/@_ooye_papiophidian:cadence.moe\">@papiophidian</a> used <code>/stats</code></blockquote>",
|
||||||
+ `<blockquote><p><strong>Hi, I'm Amanda!</strong></p><p>I condone pirating music!</p></blockquote>`,
|
"m.mentions": {},
|
||||||
|
msgtype: "m.text",
|
||||||
|
}, {
|
||||||
|
$type: "m.room.message",
|
||||||
|
msgtype: "m.notice",
|
||||||
|
body: "| ## Hi, I'm Amanda!\n| \n| I condone pirating music!",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: `<blockquote><p><strong>Hi, I'm Amanda!</strong></p><p>I condone pirating music!</p></blockquote>`,
|
||||||
"m.mentions": {}
|
"m.mentions": {}
|
||||||
}])
|
}])
|
||||||
})
|
})
|
||||||
|
|
@ -166,12 +170,17 @@ test("message2event embeds: url without title", async t => {
|
||||||
const events = await messageToEvent(data.message_with_embeds.url_without_title, data.guild.general)
|
const events = await messageToEvent(data.message_with_embeds.url_without_title, data.guild.general)
|
||||||
t.deepEqual(events, [{
|
t.deepEqual(events, [{
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
msgtype: "m.notice",
|
body: "> ↪️ @papiophidian: used `/stats`",
|
||||||
body: "↪️ PapiOphidian used `/stats`"
|
|
||||||
+ "\n| I condone pirating music!",
|
|
||||||
format: "org.matrix.custom.html",
|
format: "org.matrix.custom.html",
|
||||||
formatted_body: '<blockquote><sub>↪️ <a href=\"https://matrix.to/#/@_ooye_papiophidian:cadence.moe\">PapiOphidian</a> used <code>/stats</code></sub></blockquote>'
|
formatted_body: "<blockquote>↪️ <a href=\"https://matrix.to/#/@_ooye_papiophidian:cadence.moe\">@papiophidian</a> used <code>/stats</code></blockquote>",
|
||||||
+ `<blockquote><p>I condone pirating music!</p></blockquote>`,
|
"m.mentions": {},
|
||||||
|
msgtype: "m.text",
|
||||||
|
}, {
|
||||||
|
$type: "m.room.message",
|
||||||
|
msgtype: "m.notice",
|
||||||
|
body: "| I condone pirating music!",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: `<blockquote><p>I condone pirating music!</p></blockquote>`,
|
||||||
"m.mentions": {}
|
"m.mentions": {}
|
||||||
}])
|
}])
|
||||||
})
|
})
|
||||||
|
|
@ -180,12 +189,17 @@ test("message2event embeds: author without url", async t => {
|
||||||
const events = await messageToEvent(data.message_with_embeds.author_without_url, data.guild.general)
|
const events = await messageToEvent(data.message_with_embeds.author_without_url, data.guild.general)
|
||||||
t.deepEqual(events, [{
|
t.deepEqual(events, [{
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
msgtype: "m.notice",
|
body: "> ↪️ @papiophidian: used `/stats`",
|
||||||
body: "↪️ PapiOphidian used `/stats`"
|
|
||||||
+ "\n| ## Amanda\n| \n| I condone pirating music!",
|
|
||||||
format: "org.matrix.custom.html",
|
format: "org.matrix.custom.html",
|
||||||
formatted_body: '<blockquote><sub>↪️ <a href=\"https://matrix.to/#/@_ooye_papiophidian:cadence.moe\">PapiOphidian</a> used <code>/stats</code></sub></blockquote>'
|
formatted_body: "<blockquote>↪️ <a href=\"https://matrix.to/#/@_ooye_papiophidian:cadence.moe\">@papiophidian</a> used <code>/stats</code></blockquote>",
|
||||||
+ `<blockquote><p><strong>Amanda</strong></p><p>I condone pirating music!</p></blockquote>`,
|
"m.mentions": {},
|
||||||
|
msgtype: "m.text",
|
||||||
|
}, {
|
||||||
|
$type: "m.room.message",
|
||||||
|
msgtype: "m.notice",
|
||||||
|
body: "| ## Amanda\n| \n| I condone pirating music!",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: `<blockquote><p><strong>Amanda</strong></p><p>I condone pirating music!</p></blockquote>`,
|
||||||
"m.mentions": {}
|
"m.mentions": {}
|
||||||
}])
|
}])
|
||||||
})
|
})
|
||||||
|
|
@ -194,12 +208,17 @@ test("message2event embeds: author url without name", async t => {
|
||||||
const events = await messageToEvent(data.message_with_embeds.author_url_without_name, data.guild.general)
|
const events = await messageToEvent(data.message_with_embeds.author_url_without_name, data.guild.general)
|
||||||
t.deepEqual(events, [{
|
t.deepEqual(events, [{
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
msgtype: "m.notice",
|
body: "> ↪️ @papiophidian: used `/stats`",
|
||||||
body: "↪️ PapiOphidian used `/stats`"
|
|
||||||
+ "\n| I condone pirating music!",
|
|
||||||
format: "org.matrix.custom.html",
|
format: "org.matrix.custom.html",
|
||||||
formatted_body: '<blockquote><sub>↪️ <a href=\"https://matrix.to/#/@_ooye_papiophidian:cadence.moe\">PapiOphidian</a> used <code>/stats</code></sub></blockquote>'
|
formatted_body: "<blockquote>↪️ <a href=\"https://matrix.to/#/@_ooye_papiophidian:cadence.moe\">@papiophidian</a> used <code>/stats</code></blockquote>",
|
||||||
+ `<blockquote><p>I condone pirating music!</p></blockquote>`,
|
"m.mentions": {},
|
||||||
|
msgtype: "m.text",
|
||||||
|
}, {
|
||||||
|
$type: "m.room.message",
|
||||||
|
msgtype: "m.notice",
|
||||||
|
body: "| I condone pirating music!",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: `<blockquote><p>I condone pirating music!</p></blockquote>`,
|
||||||
"m.mentions": {}
|
"m.mentions": {}
|
||||||
}])
|
}])
|
||||||
})
|
})
|
||||||
|
|
@ -299,56 +318,19 @@ test("message2event embeds: youtube video", async t => {
|
||||||
}])
|
}])
|
||||||
})
|
})
|
||||||
|
|
||||||
test("message2event embeds: embed not bridged if its link was spoilered", async t => {
|
|
||||||
const events = await messageToEvent({
|
|
||||||
...data.message_with_embeds.youtube_video,
|
|
||||||
content: "||https://youtu.be/kDMHHw8JqLE?si=NaqNjVTtXugHeG_E\n\n\nJutomi I'm gonna make these sounds in your walls tonight||"
|
|
||||||
}, data.guild.general)
|
|
||||||
t.deepEqual(events, [{
|
|
||||||
$type: "m.room.message",
|
|
||||||
msgtype: "m.text",
|
|
||||||
body: "[spoiler]",
|
|
||||||
format: "org.matrix.custom.html",
|
|
||||||
formatted_body: `<span data-mx-spoiler=""><a href="https://youtu.be/kDMHHw8JqLE?si=NaqNjVTtXugHeG_E">https://youtu.be/kDMHHw8JqLE?si=NaqNjVTtXugHeG_E</a><br><br><br>Jutomi I'm gonna make these sounds in your walls tonight</span>`,
|
|
||||||
"m.mentions": {}
|
|
||||||
}])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("message2event embeds: tenor gif should show a video link without a provider", async t => {
|
|
||||||
const events = await messageToEvent(data.message_with_embeds.tenor_gif, data.guild.general, {}, {})
|
|
||||||
t.deepEqual(events, [{
|
|
||||||
$type: "m.room.message",
|
|
||||||
msgtype: "m.text",
|
|
||||||
body: "@Realdditors: get real https://tenor.com/view/get-real-gif-26176788",
|
|
||||||
format: "org.matrix.custom.html",
|
|
||||||
formatted_body: "<font color=\"#ff4500\">@Realdditors</font> get real <a href=\"https://tenor.com/view/get-real-gif-26176788\">https://tenor.com/view/get-real-gif-26176788</a>",
|
|
||||||
"m.mentions": {}
|
|
||||||
}, {
|
|
||||||
$type: "m.room.message",
|
|
||||||
msgtype: "m.notice",
|
|
||||||
body: "| 🎞️ https://media.tenor.com/Bz5pfRIu81oAAAPo/get-real.mp4",
|
|
||||||
format: "org.matrix.custom.html",
|
|
||||||
formatted_body: "<blockquote><p>🎞️ https://media.tenor.com/Bz5pfRIu81oAAAPo/get-real.mp4</p></blockquote>",
|
|
||||||
"m.mentions": {}
|
|
||||||
}])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("message2event embeds: klipy gif should send in customised format", async t => {
|
|
||||||
const events = await messageToEvent(data.message_with_embeds.klipy_gif, data.guild.general, {}, {})
|
|
||||||
t.deepEqual(events, [{
|
|
||||||
$type: "m.room.message",
|
|
||||||
msgtype: "m.text",
|
|
||||||
body: "[GIF] Cute Corgi Waddle https://static.klipy.com/ii/d7aec6f6f171607374b2065c836f92f4/5b/5b/7ndEhcilPNKJ8O.mp4",
|
|
||||||
format: "org.matrix.custom.html",
|
|
||||||
formatted_body: "<blockquote>➿ <a href=\"https://static.klipy.com/ii/d7aec6f6f171607374b2065c836f92f4/5b/5b/7ndEhcilPNKJ8O.mp4\">Cute Corgi Waddle</a></blockquote>",
|
|
||||||
"m.mentions": {}
|
|
||||||
}])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("message2event embeds: if discord creates an embed preview for a discord channel link, don't copy that embed", async t => {
|
test("message2event embeds: if discord creates an embed preview for a discord channel link, don't copy that embed", async t => {
|
||||||
const events = await messageToEvent(data.message_with_embeds.discord_server_included_punctuation_bad_discord, data.guild.general, {}, {
|
const events = await messageToEvent(data.message_with_embeds.discord_server_included_punctuation_bad_discord, data.guild.general, {}, {
|
||||||
api: {
|
api: {
|
||||||
getEffectivePower: mockGetEffectivePower(),
|
async getStateEvent(roomID, type, key) {
|
||||||
|
t.equal(roomID, "!TqlyQmifxGUggEmdBN:cadence.moe")
|
||||||
|
t.equal(type, "m.room.power_levels")
|
||||||
|
t.equal(key, "")
|
||||||
|
return {
|
||||||
|
users: {
|
||||||
|
"@_ooye_bot:cadence.moe": 100
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
async getJoinedMembers(roomID) {
|
async getJoinedMembers(roomID) {
|
||||||
t.equal(roomID, "!TqlyQmifxGUggEmdBN:cadence.moe")
|
t.equal(roomID, "!TqlyQmifxGUggEmdBN:cadence.moe")
|
||||||
return {
|
return {
|
||||||
|
|
@ -369,16 +351,3 @@ test("message2event embeds: if discord creates an embed preview for a discord ch
|
||||||
"m.mentions": {}
|
"m.mentions": {}
|
||||||
}])
|
}])
|
||||||
})
|
})
|
||||||
|
|
||||||
test("message2event embeds: nothing generated if embeds are disabled in settings", async t => {
|
|
||||||
db.prepare("UPDATE guild_space SET url_preview = 0 WHERE guild_id = ?").run(data.guild.general.id)
|
|
||||||
const events = await messageToEvent(data.message_with_embeds.youtube_video, data.guild.general)
|
|
||||||
t.deepEqual(events, [{
|
|
||||||
$type: "m.room.message",
|
|
||||||
msgtype: "m.text",
|
|
||||||
body: "https://youtu.be/kDMHHw8JqLE?si=NaqNjVTtXugHeG_E\n\n\nJutomi I'm gonna make these sounds in your walls tonight",
|
|
||||||
format: "org.matrix.custom.html",
|
|
||||||
formatted_body: `<a href="https://youtu.be/kDMHHw8JqLE?si=NaqNjVTtXugHeG_E">https://youtu.be/kDMHHw8JqLE?si=NaqNjVTtXugHeG_E</a><br><br><br>Jutomi I'm gonna make these sounds in your walls tonight`,
|
|
||||||
"m.mentions": {}
|
|
||||||
}])
|
|
||||||
})
|
|
||||||
|
|
@ -14,33 +14,28 @@ const file = sync.require("../../matrix/file")
|
||||||
const emojiToKey = sync.require("./emoji-to-key")
|
const emojiToKey = sync.require("./emoji-to-key")
|
||||||
/** @type {import("../actions/lottie")} */
|
/** @type {import("../actions/lottie")} */
|
||||||
const lottie = sync.require("../actions/lottie")
|
const lottie = sync.require("../actions/lottie")
|
||||||
/** @type {import("../../matrix/utils")} */
|
/** @type {import("../../m2d/converters/utils")} */
|
||||||
const mxUtils = sync.require("../../matrix/utils")
|
const mxUtils = sync.require("../../m2d/converters/utils")
|
||||||
/** @type {import("../../discord/utils")} */
|
/** @type {import("../../discord/utils")} */
|
||||||
const dUtils = sync.require("../../discord/utils")
|
const dUtils = sync.require("../../discord/utils")
|
||||||
/** @type {import("./find-mentions")} */
|
|
||||||
const findMentions = sync.require("./find-mentions")
|
|
||||||
/** @type {import("../../discord/interactions/poll-responses")} */
|
|
||||||
const pollResponses = sync.require("../../discord/interactions/poll-responses")
|
|
||||||
const {reg} = require("../../matrix/read-registration")
|
const {reg} = require("../../matrix/read-registration")
|
||||||
|
|
||||||
|
const userRegex = reg.namespaces.users.map(u => new RegExp(u.regex))
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {DiscordTypes.APIMessage} message
|
* @param {DiscordTypes.APIMessage} message
|
||||||
* @param {DiscordTypes.APIGuild} guild
|
* @param {DiscordTypes.APIGuild} guild
|
||||||
* @param {boolean} useHTML
|
* @param {boolean} useHTML
|
||||||
* @param {string[]} spoilers
|
|
||||||
*/
|
*/
|
||||||
function getDiscordParseCallbacks(message, guild, useHTML, spoilers = []) {
|
function getDiscordParseCallbacks(message, guild, useHTML) {
|
||||||
return {
|
return {
|
||||||
/** @param {{id: string, type: "discordUser"}} node */
|
/** @param {{id: string, type: "discordUser"}} node */
|
||||||
user: node => {
|
user: node => {
|
||||||
const mxid = select("sim", "mxid", {user_id: node.id}).pluck().get()
|
const mxid = select("sim", "mxid", {user_id: node.id}).pluck().get()
|
||||||
const interaction = message.interaction_metadata || message.interaction
|
const interaction = message.interaction_metadata || message.interaction
|
||||||
const username = message.mentions?.find(ment => ment.id === node.id)?.username
|
const username = message.mentions.find(ment => ment.id === node.id)?.username
|
||||||
|| message.referenced_message?.mentions?.find(ment => ment.id === node.id)?.username
|
|
||||||
|| (interaction?.user.id === node.id ? interaction.user.username : null)
|
|| (interaction?.user.id === node.id ? interaction.user.username : null)
|
||||||
|| (message.author?.id === node.id ? message.author.username : null)
|
|| node.id
|
||||||
|| "unknown-user"
|
|
||||||
if (mxid && useHTML) {
|
if (mxid && useHTML) {
|
||||||
return `<a href="https://matrix.to/#/${mxid}">@${username}</a>`
|
return `<a href="https://matrix.to/#/${mxid}">@${username}</a>`
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -93,10 +88,6 @@ function getDiscordParseCallbacks(message, guild, useHTML, spoilers = []) {
|
||||||
here: () => {
|
here: () => {
|
||||||
if (message.mention_everyone) return "@room"
|
if (message.mention_everyone) return "@room"
|
||||||
return "@here"
|
return "@here"
|
||||||
},
|
|
||||||
spoiler: node => {
|
|
||||||
spoilers.push(node.raw)
|
|
||||||
return useHTML
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -109,11 +100,10 @@ const embedTitleParser = markdown.markdownEngine.parserFor({
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {{room?: boolean, user_ids?: string[]}} mentions
|
* @param {{room?: boolean, user_ids?: string[]}} mentions
|
||||||
* @param {Omit<DiscordTypes.APIAttachment, "id" | "proxy_url">} attachment
|
* @param {DiscordTypes.APIAttachment} attachment
|
||||||
* @param {boolean} [alwaysLink]
|
|
||||||
*/
|
*/
|
||||||
async function attachmentToEvent(mentions, attachment, alwaysLink) {
|
async function attachmentToEvent(mentions, attachment) {
|
||||||
const external_url = dUtils.getPublicUrlForCdn(attachment.url)
|
const publicURL = dUtils.getPublicUrlForCdn(attachment.url)
|
||||||
const emoji =
|
const emoji =
|
||||||
attachment.content_type?.startsWith("image/jp") ? "📸"
|
attachment.content_type?.startsWith("image/jp") ? "📸"
|
||||||
: attachment.content_type?.startsWith("image/") ? "🖼️"
|
: attachment.content_type?.startsWith("image/") ? "🖼️"
|
||||||
|
|
@ -127,20 +117,20 @@ async function attachmentToEvent(mentions, attachment, alwaysLink) {
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
"m.mentions": mentions,
|
"m.mentions": mentions,
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: `${emoji} Uploaded SPOILER file: ${external_url} (${pb(attachment.size)})`,
|
body: `${emoji} Uploaded SPOILER file: ${publicURL} (${pb(attachment.size)})`,
|
||||||
format: "org.matrix.custom.html",
|
format: "org.matrix.custom.html",
|
||||||
formatted_body: `<blockquote>${emoji} Uploaded SPOILER file: <a href="${external_url}">${external_url}</a> (${pb(attachment.size)})</blockquote>`
|
formatted_body: `<blockquote>${emoji} Uploaded SPOILER file: <a href="${publicURL}">${publicURL}</a> (${pb(attachment.size)})</blockquote>`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// for large files, always link them instead of uploading so I don't use up all the space in the content repo
|
// for large files, always link them instead of uploading so I don't use up all the space in the content repo
|
||||||
else if (alwaysLink || attachment.size > reg.ooye.max_file_size) {
|
else if (attachment.size > reg.ooye.max_file_size) {
|
||||||
return {
|
return {
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
"m.mentions": mentions,
|
"m.mentions": mentions,
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: `${emoji} Uploaded file: ${external_url} (${pb(attachment.size)})`,
|
body: `${emoji} Uploaded file: ${publicURL} (${pb(attachment.size)})`,
|
||||||
format: "org.matrix.custom.html",
|
format: "org.matrix.custom.html",
|
||||||
formatted_body: `${emoji} Uploaded file: <a href="${external_url}">${attachment.filename}</a> (${pb(attachment.size)})`
|
formatted_body: `${emoji} Uploaded file: <a href="${publicURL}">${attachment.filename}</a> (${pb(attachment.size)})`
|
||||||
}
|
}
|
||||||
} else if (attachment.content_type?.startsWith("image/") && attachment.width && attachment.height) {
|
} else if (attachment.content_type?.startsWith("image/") && attachment.width && attachment.height) {
|
||||||
return {
|
return {
|
||||||
|
|
@ -148,7 +138,7 @@ async function attachmentToEvent(mentions, attachment, alwaysLink) {
|
||||||
"m.mentions": mentions,
|
"m.mentions": mentions,
|
||||||
msgtype: "m.image",
|
msgtype: "m.image",
|
||||||
url: await file.uploadDiscordFileToMxc(attachment.url),
|
url: await file.uploadDiscordFileToMxc(attachment.url),
|
||||||
external_url,
|
external_url: attachment.url,
|
||||||
body: attachment.description || attachment.filename,
|
body: attachment.description || attachment.filename,
|
||||||
filename: attachment.filename,
|
filename: attachment.filename,
|
||||||
info: {
|
info: {
|
||||||
|
|
@ -164,7 +154,7 @@ async function attachmentToEvent(mentions, attachment, alwaysLink) {
|
||||||
"m.mentions": mentions,
|
"m.mentions": mentions,
|
||||||
msgtype: "m.video",
|
msgtype: "m.video",
|
||||||
url: await file.uploadDiscordFileToMxc(attachment.url),
|
url: await file.uploadDiscordFileToMxc(attachment.url),
|
||||||
external_url,
|
external_url: attachment.url,
|
||||||
body: attachment.description || attachment.filename,
|
body: attachment.description || attachment.filename,
|
||||||
filename: attachment.filename,
|
filename: attachment.filename,
|
||||||
info: {
|
info: {
|
||||||
|
|
@ -180,13 +170,13 @@ async function attachmentToEvent(mentions, attachment, alwaysLink) {
|
||||||
"m.mentions": mentions,
|
"m.mentions": mentions,
|
||||||
msgtype: "m.audio",
|
msgtype: "m.audio",
|
||||||
url: await file.uploadDiscordFileToMxc(attachment.url),
|
url: await file.uploadDiscordFileToMxc(attachment.url),
|
||||||
external_url,
|
external_url: attachment.url,
|
||||||
body: attachment.description || attachment.filename,
|
body: attachment.description || attachment.filename,
|
||||||
filename: attachment.filename,
|
filename: attachment.filename,
|
||||||
info: {
|
info: {
|
||||||
mimetype: attachment.content_type,
|
mimetype: attachment.content_type,
|
||||||
size: attachment.size,
|
size: attachment.size,
|
||||||
duration: attachment.duration_secs && Math.round(attachment.duration_secs * 1000)
|
duration: attachment.duration_secs ? attachment.duration_secs * 1000 : undefined
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -195,7 +185,7 @@ async function attachmentToEvent(mentions, attachment, alwaysLink) {
|
||||||
"m.mentions": mentions,
|
"m.mentions": mentions,
|
||||||
msgtype: "m.file",
|
msgtype: "m.file",
|
||||||
url: await file.uploadDiscordFileToMxc(attachment.url),
|
url: await file.uploadDiscordFileToMxc(attachment.url),
|
||||||
external_url,
|
external_url: attachment.url,
|
||||||
body: attachment.description || attachment.filename,
|
body: attachment.description || attachment.filename,
|
||||||
filename: attachment.filename,
|
filename: attachment.filename,
|
||||||
info: {
|
info: {
|
||||||
|
|
@ -206,74 +196,15 @@ async function attachmentToEvent(mentions, attachment, alwaysLink) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param {DiscordTypes.APIPoll} poll */
|
|
||||||
async function pollToEvent(poll) {
|
|
||||||
let fallbackText = poll.question.text
|
|
||||||
if (poll.allow_multiselect) {
|
|
||||||
var maxSelections = poll.answers.length;
|
|
||||||
} else {
|
|
||||||
var maxSelections = 1;
|
|
||||||
}
|
|
||||||
let answers = poll.answers.map(answer=>{
|
|
||||||
let matrixText = answer.poll_media.text
|
|
||||||
if (answer.poll_media.emoji) {
|
|
||||||
if (answer.poll_media.emoji.id) {
|
|
||||||
// Custom emoji. It seems like no Matrix client allows custom emoji in poll answers, so leaving this unimplemented.
|
|
||||||
} else {
|
|
||||||
matrixText = "[" + answer.poll_media.emoji.name + "] " + matrixText
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let matrixAnswer = {
|
|
||||||
id: answer.answer_id.toString(),
|
|
||||||
"org.matrix.msc1767.text": matrixText
|
|
||||||
}
|
|
||||||
fallbackText = fallbackText + "\n" + answer.answer_id.toString() + ". " + matrixText
|
|
||||||
return matrixAnswer;
|
|
||||||
})
|
|
||||||
return {
|
|
||||||
/** @type {"org.matrix.msc3381.poll.start"} */
|
|
||||||
$type: "org.matrix.msc3381.poll.start",
|
|
||||||
"org.matrix.msc3381.poll.start": {
|
|
||||||
question: {
|
|
||||||
"org.matrix.msc1767.text": poll.question.text,
|
|
||||||
body: poll.question.text,
|
|
||||||
msgtype: "m.text"
|
|
||||||
},
|
|
||||||
kind: "org.matrix.msc3381.poll.disclosed", // Discord always lets you see results, so keeping this consistent with that.
|
|
||||||
max_selections: maxSelections,
|
|
||||||
answers: answers
|
|
||||||
},
|
|
||||||
"org.matrix.msc1767.text": fallbackText
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {DiscordTypes.APIMessageInteraction} interaction
|
* @param {import("discord-api-types/v10").APIMessage} message
|
||||||
* @param {boolean} isThinkingInteraction
|
* @param {import("discord-api-types/v10").APIGuild} guild
|
||||||
*/
|
* @param {{includeReplyFallback?: boolean, includeEditFallbackStar?: boolean}} options default values:
|
||||||
function getFormattedInteraction(interaction, isThinkingInteraction) {
|
|
||||||
const mxid = select("sim", "mxid", {user_id: interaction.user.id}).pluck().get()
|
|
||||||
const username = interaction.member?.nick || interaction.user.global_name || interaction.user.username
|
|
||||||
const thinkingText = isThinkingInteraction ? " — interaction loading..." : ""
|
|
||||||
return {
|
|
||||||
body: `↪️ ${username} used \`/${interaction.name}\`${thinkingText}`,
|
|
||||||
html: `<blockquote><sub>↪️ ${mxid ? tag`<a href="https://matrix.to/#/${mxid}">${username}</a>` : username} used <code>/${interaction.name}</code>${thinkingText}</sub></blockquote>`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {DiscordTypes.APIMessage} message
|
|
||||||
* @param {DiscordTypes.APIGuild} guild
|
|
||||||
* @param {{includeReplyFallback?: boolean, includeEditFallbackStar?: boolean, alwaysReturnFormattedBody?: boolean, scanTextForMentions?: boolean}} options default values:
|
|
||||||
* - includeReplyFallback: true
|
* - includeReplyFallback: true
|
||||||
* - includeEditFallbackStar: false
|
* - includeEditFallbackStar: false
|
||||||
* - alwaysReturnFormattedBody: false - formatted_body will be skipped if it is the same as body because the message is plaintext. if you want the formatted_body to be returned anyway, for example to merge it with another message, then set this to true.
|
* @param {{api: import("../../matrix/api")}} di simple-as-nails dependency injection for the matrix API
|
||||||
* - scanTextForMentions: true - needs to be set to false when converting forwarded messages etc which may be from a different channel that can't be scanned.
|
|
||||||
* @param {{api: import("../../matrix/api"), snow?: import("snowtransfer").SnowTransfer}} di simple-as-nails dependency injection for the matrix API
|
|
||||||
* @returns {Promise<{$type: string, $sender?: string, [x: string]: any}[]>}
|
|
||||||
*/
|
*/
|
||||||
async function messageToEvent(message, guild, options = {}, di) {
|
async function messageToEvent(message, guild, options = {}, di) {
|
||||||
message = structuredClone(message)
|
|
||||||
const events = []
|
const events = []
|
||||||
|
|
||||||
/* c8 ignore next 7 */
|
/* c8 ignore next 7 */
|
||||||
|
|
@ -285,38 +216,6 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
return []
|
return []
|
||||||
}
|
}
|
||||||
|
|
||||||
if (message.type === DiscordTypes.MessageType.PollResult) {
|
|
||||||
const pollMessageID = message.message_reference?.message_id
|
|
||||||
if (!pollMessageID) return []
|
|
||||||
const event_id = select("event_message", "event_id", {message_id: pollMessageID}).pluck().get()
|
|
||||||
const roomID = select("channel_room", "room_id", {channel_id: message.channel_id}).pluck().get()
|
|
||||||
const pollQuestionText = select("poll", "question_text", {message_id: pollMessageID}).pluck().get()
|
|
||||||
if (!event_id || !roomID || !pollQuestionText) return [] // drop it if the corresponding poll start was not bridged
|
|
||||||
|
|
||||||
const rep = new mxUtils.MatrixStringBuilder()
|
|
||||||
rep.addLine(`The poll ${pollQuestionText} has closed.`, tag`The poll <a href="https://matrix.to/#/${roomID}/${event_id}">${pollQuestionText}</a> has closed.`)
|
|
||||||
|
|
||||||
const {messageString} = pollResponses.getCombinedResults(pollMessageID, true) // poll results have already been double-checked before this point, so these totals will be accurate
|
|
||||||
rep.addLine(markdown.toHTML(messageString, {discordOnly: true, escapeHTML: false}), markdown.toHTML(messageString, {}))
|
|
||||||
|
|
||||||
const {body, formatted_body} = rep.get()
|
|
||||||
|
|
||||||
return [{
|
|
||||||
$type: "org.matrix.msc3381.poll.end",
|
|
||||||
"m.relates_to": {
|
|
||||||
rel_type: "m.reference",
|
|
||||||
event_id
|
|
||||||
},
|
|
||||||
"org.matrix.msc3381.poll.end": {},
|
|
||||||
"org.matrix.msc1767.text": body,
|
|
||||||
"org.matrix.msc1767.html": formatted_body,
|
|
||||||
body: body,
|
|
||||||
format: "org.matrix.custom.html",
|
|
||||||
formatted_body: formatted_body,
|
|
||||||
msgtype: "m.text"
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
|
|
||||||
if (message.type === DiscordTypes.MessageType.ThreadStarterMessage) {
|
if (message.type === DiscordTypes.MessageType.ThreadStarterMessage) {
|
||||||
// This is the message that appears at the top of a thread when the thread was based off an existing message.
|
// This is the message that appears at the top of a thread when the thread was based off an existing message.
|
||||||
// It's just a message reference, no content.
|
// It's just a message reference, no content.
|
||||||
|
|
@ -335,8 +234,11 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const interaction = message.interaction_metadata || message.interaction
|
const interaction = message.interaction_metadata || message.interaction
|
||||||
const isInteraction = message.type === DiscordTypes.MessageType.ChatInputCommand && !!interaction && "name" in interaction
|
if (message.type === DiscordTypes.MessageType.ChatInputCommand && interaction && "name" in interaction) {
|
||||||
const isThinkingInteraction = isInteraction && !!((message.flags || 0) & DiscordTypes.MessageFlags.Loading)
|
// Commands are sent by the responding bot. Need to attach the metadata of the person using the command at the top.
|
||||||
|
if (message.content) message.content = `\n${message.content}`
|
||||||
|
message.content = `> ↪️ <@${interaction.user.id}> used \`/${interaction.name}\`${message.content}`
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@type {{room?: boolean, user_ids?: string[]}}
|
@type {{room?: boolean, user_ids?: string[]}}
|
||||||
|
|
@ -355,10 +257,7 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
- So make sure we don't do anything in this case.
|
- So make sure we don't do anything in this case.
|
||||||
*/
|
*/
|
||||||
const mentions = {}
|
const mentions = {}
|
||||||
/** @type {{event_id: string, room_id: string, source: number, channel_id: string}?} */
|
|
||||||
let repliedToEventRow = null
|
let repliedToEventRow = null
|
||||||
let repliedToEventInDifferentRoom = false
|
|
||||||
let repliedToUnknownEvent = false
|
|
||||||
let repliedToEventSenderMxid = null
|
let repliedToEventSenderMxid = null
|
||||||
|
|
||||||
if (message.mention_everyone) mentions.room = true
|
if (message.mention_everyone) mentions.room = true
|
||||||
|
|
@ -371,11 +270,9 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
// Mentions scenarios 1 and 2, part A. i.e. translate relevant message.mentions to m.mentions
|
// Mentions scenarios 1 and 2, part A. i.e. translate relevant message.mentions to m.mentions
|
||||||
// (Still need to do scenarios 1 and 2 part B, and scenario 3.)
|
// (Still need to do scenarios 1 and 2 part B, and scenario 3.)
|
||||||
if (message.type === DiscordTypes.MessageType.Reply && message.message_reference?.message_id) {
|
if (message.type === DiscordTypes.MessageType.Reply && message.message_reference?.message_id) {
|
||||||
const row = await getHistoricalEventRow(message.message_reference?.message_id)
|
const row = from("event_message").join("message_channel", "message_id").join("channel_room", "channel_id").select("event_id", "room_id", "source").and("WHERE message_id = ? AND part = 0").get(message.message_reference.message_id)
|
||||||
if (row && "event_id" in row) {
|
if (row) {
|
||||||
repliedToEventRow = Object.assign(row, {channel_id: row.reference_channel_id})
|
repliedToEventRow = row
|
||||||
} else if (message.referenced_message) {
|
|
||||||
repliedToUnknownEvent = true
|
|
||||||
}
|
}
|
||||||
} else if (dUtils.isWebhookMessage(message) && message.embeds[0]?.author?.name?.endsWith("↩️")) {
|
} else if (dUtils.isWebhookMessage(message) && message.embeds[0]?.author?.name?.endsWith("↩️")) {
|
||||||
// It could be a PluralKit emulated reply, let's see if it has a message link
|
// It could be a PluralKit emulated reply, let's see if it has a message link
|
||||||
|
|
@ -385,8 +282,8 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
assert(message.embeds[0].description)
|
assert(message.embeds[0].description)
|
||||||
const match = message.embeds[0].description.match(/\/channels\/[0-9]*\/[0-9]*\/([0-9]{2,})/)
|
const match = message.embeds[0].description.match(/\/channels\/[0-9]*\/[0-9]*\/([0-9]{2,})/)
|
||||||
if (match) {
|
if (match) {
|
||||||
const row = await getHistoricalEventRow(match[1])
|
const row = from("event_message").join("message_channel", "message_id").join("channel_room", "channel_id").select("event_id", "room_id", "source").and("WHERE message_id = ? AND part = 0").get(match[1])
|
||||||
if (row && "event_id" in row) {
|
if (row) {
|
||||||
/*
|
/*
|
||||||
we generate a partial referenced_message based on what PK provided. we don't need everything, since this will only be used for further message-to-event converting.
|
we generate a partial referenced_message based on what PK provided. we don't need everything, since this will only be used for further message-to-event converting.
|
||||||
the following properties are necessary:
|
the following properties are necessary:
|
||||||
|
|
@ -404,7 +301,7 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
message.embeds.shift()
|
message.embeds.shift()
|
||||||
repliedToEventRow = Object.assign(row, {channel_id: row.reference_channel_id})
|
repliedToEventRow = row
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -431,34 +328,6 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
return promise
|
return promise
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {string} messageID
|
|
||||||
* @param {string} [timestampChannelID]
|
|
||||||
*/
|
|
||||||
async function getHistoricalEventRow(messageID, timestampChannelID) {
|
|
||||||
/** @type {{room_id: string} | {event_id: string, room_id: string, reference_channel_id: string, source: number} | null | undefined} */
|
|
||||||
let row = from("event_message").join("message_room", "message_id").join("historical_channel_room", "historical_room_index")
|
|
||||||
.select("event_id", "room_id", "reference_channel_id", "source").where({message_id: messageID}).and("ORDER BY part ASC").get()
|
|
||||||
if (!row && timestampChannelID) {
|
|
||||||
const ts = dUtils.snowflakeToTimestampExact(messageID)
|
|
||||||
const oldestRow = from("historical_channel_room").selectUnsafe("max(upgraded_timestamp)", "room_id")
|
|
||||||
.where({reference_channel_id: timestampChannelID}).and("and upgraded_timestamp < ?").get(ts)
|
|
||||||
if (oldestRow?.room_id) {
|
|
||||||
row = {room_id: oldestRow.room_id}
|
|
||||||
try {
|
|
||||||
const {event_id} = await di.api.getEventForTimestamp(oldestRow.room_id, ts)
|
|
||||||
row = {
|
|
||||||
event_id,
|
|
||||||
room_id: oldestRow.room_id,
|
|
||||||
reference_channel_id: oldestRow.reference_channel_id,
|
|
||||||
source: 1
|
|
||||||
}
|
|
||||||
} catch (e) {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return row
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Translate Discord message links to Matrix event links.
|
* Translate Discord message links to Matrix event links.
|
||||||
* If OOYE has handled this message in the past, this is an instant database lookup.
|
* If OOYE has handled this message in the past, this is an instant database lookup.
|
||||||
|
|
@ -470,13 +339,27 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
for (const match of [...content.matchAll(/https:\/\/(?:ptb\.|canary\.|www\.)?discord(?:app)?\.com\/channels\/[0-9]+\/([0-9]+)\/([0-9]+)/g)]) {
|
for (const match of [...content.matchAll(/https:\/\/(?:ptb\.|canary\.|www\.)?discord(?:app)?\.com\/channels\/[0-9]+\/([0-9]+)\/([0-9]+)/g)]) {
|
||||||
assert(typeof match.index === "number")
|
assert(typeof match.index === "number")
|
||||||
const [_, channelID, messageID] = match
|
const [_, channelID, messageID] = match
|
||||||
const result = await (async () => {
|
let result
|
||||||
const row = await getHistoricalEventRow(messageID, channelID)
|
|
||||||
if (!row) return `${match[0]} [event is from another server]`
|
const roomID = select("channel_room", "room_id", {channel_id: channelID}).pluck().get()
|
||||||
const via = await getViaServersMemo(row.room_id)
|
if (roomID) {
|
||||||
if (!("event_id" in row)) return `[unknown event in https://matrix.to/#/${row.room_id}?${via}]`
|
const eventID = select("event_message", "event_id", {message_id: messageID}).pluck().get()
|
||||||
return `https://matrix.to/#/${row.room_id}/${row.event_id}?${via}`
|
const via = await getViaServersMemo(roomID)
|
||||||
})()
|
if (eventID && roomID) {
|
||||||
|
result = `https://matrix.to/#/${roomID}/${eventID}?${via}`
|
||||||
|
} else {
|
||||||
|
const ts = dUtils.snowflakeToTimestampExact(messageID)
|
||||||
|
try {
|
||||||
|
const {event_id} = await di.api.getEventForTimestamp(roomID, ts)
|
||||||
|
result = `https://matrix.to/#/${roomID}/${event_id}?${via}`
|
||||||
|
} catch (e) {
|
||||||
|
// M_NOT_FOUND: Unable to find event from <ts> in direction Direction.FORWARDS
|
||||||
|
result = `[unknown event, timestamp resolution failed, in room: https://matrix.to/#/${roomID}?${via}]`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result = `${match[0]} [event is from another server]`
|
||||||
|
}
|
||||||
|
|
||||||
content = content.slice(0, match.index + offset) + result + content.slice(match.index + match[0].length + offset)
|
content = content.slice(0, match.index + offset) + result + content.slice(match.index + match[0].length + offset)
|
||||||
offset += result.length - match[0].length
|
offset += result.length - match[0].length
|
||||||
|
|
@ -491,7 +374,6 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
return content.replace(/https:\/\/(cdn|media)\.discordapp\.(?:com|net)\/attachments\/([0-9]+)\/([0-9]+)\/([-A-Za-z0-9_.,]+)/g, url => dUtils.getPublicUrlForCdn(url))
|
return content.replace(/https:\/\/(cdn|media)\.discordapp\.(?:com|net)\/attachments\/([0-9]+)\/([0-9]+)\/([-A-Za-z0-9_.,]+)/g, url => dUtils.getPublicUrlForCdn(url))
|
||||||
}
|
}
|
||||||
|
|
||||||
const spoilers = []
|
|
||||||
/**
|
/**
|
||||||
* Translate links and emojis and mentions and stuff. Give back the text and HTML so they can be combined into bigger events.
|
* Translate links and emojis and mentions and stuff. Give back the text and HTML so they can be combined into bigger events.
|
||||||
* @param {string} content Partial or complete Discord message content
|
* @param {string} content Partial or complete Discord message content
|
||||||
|
|
@ -503,12 +385,6 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
content = transformAttachmentLinks(content)
|
content = transformAttachmentLinks(content)
|
||||||
content = await transformContentMessageLinks(content)
|
content = await transformContentMessageLinks(content)
|
||||||
|
|
||||||
// Remove smalltext from non-bots (I don't like it). Webhooks included due to PluralKit.
|
|
||||||
const isHumanOrDataMissing = !message.author?.bot
|
|
||||||
if (isHumanOrDataMissing || dUtils.isWebhookMessage(message)) {
|
|
||||||
content = content.replaceAll(/^-# +([^\n].*?)/gm, "...$1")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handling emojis that we don't know about. The emoji has to be present in the DB for it to be picked up in the emoji markdown converter.
|
// Handling emojis that we don't know about. The emoji has to be present in the DB for it to be picked up in the emoji markdown converter.
|
||||||
// So we scan the message ahead of time for all its emojis and ensure they are in the DB.
|
// So we scan the message ahead of time for all its emojis and ensure they are in the DB.
|
||||||
const emojiMatches = [...content.matchAll(/<(a?):([^:>]{1,64}):([0-9]+)>/g)]
|
const emojiMatches = [...content.matchAll(/<(a?):([^:>]{1,64}):([0-9]+)>/g)]
|
||||||
|
|
@ -516,28 +392,26 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
const id = match[3]
|
const id = match[3]
|
||||||
const name = match[2]
|
const name = match[2]
|
||||||
const animated = !!match[1]
|
const animated = !!match[1]
|
||||||
return emojiToKey.emojiToKey({id, name, animated}, message.id) // Register the custom emoji if needed
|
return emojiToKey.emojiToKey({id, name, animated}) // Register the custom emoji if needed
|
||||||
}))
|
}))
|
||||||
|
|
||||||
async function transformParsedVia(parsed) {
|
async function transformParsedVia(parsed) {
|
||||||
for (const node of parsed) {
|
for (const node of parsed) {
|
||||||
if (node.type === "discordChannel" || node.type === "discordChannelLink") {
|
if (node.type === "discordChannel") {
|
||||||
node.row = select("channel_room", ["room_id", "name", "nick"], {channel_id: node.id}).get()
|
node.row = select("channel_room", ["room_id", "name", "nick"], {channel_id: node.id}).get()
|
||||||
if (node.row?.room_id) {
|
if (node.row?.room_id) {
|
||||||
node.via = await getViaServersMemo(node.row.room_id)
|
node.via = await getViaServersMemo(node.row.room_id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const maybeChildNodesArray of [node, node.content, node.items]) {
|
if (Array.isArray(node.content)) {
|
||||||
if (Array.isArray(maybeChildNodesArray)) {
|
await transformParsedVia(node.content)
|
||||||
await transformParsedVia(maybeChildNodesArray)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return parsed
|
return parsed
|
||||||
}
|
}
|
||||||
|
|
||||||
let html = await markdown.toHtmlWithPostParser(content, transformParsedVia, {
|
let html = await markdown.toHtmlWithPostParser(content, transformParsedVia, {
|
||||||
discordCallback: getDiscordParseCallbacks(message, guild, true, spoilers),
|
discordCallback: getDiscordParseCallbacks(message, guild, true),
|
||||||
...customOptions
|
...customOptions
|
||||||
}, customParser, customHtmlOutput)
|
}, customParser, customHtmlOutput)
|
||||||
|
|
||||||
|
|
@ -551,13 +425,8 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
return {body, html}
|
return {body, html}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// FIXME: What was the scanMentions parameter supposed to activate? It's unused.
|
||||||
* After converting Discord content to Matrix plaintext and HTML content, post-process the bodies and push the resulting text event
|
async function addTextEvent(body, html, msgtype, {scanMentions}) {
|
||||||
* @param {string} body matrix event plaintext body
|
|
||||||
* @param {string} html matrix event HTML body
|
|
||||||
* @param {string} msgtype matrix event msgtype (maybe m.text or m.notice)
|
|
||||||
*/
|
|
||||||
async function addTextEvent(body, html, msgtype) {
|
|
||||||
// Star * prefix for fallback edits
|
// Star * prefix for fallback edits
|
||||||
if (options.includeEditFallbackStar) {
|
if (options.includeEditFallbackStar) {
|
||||||
body = "* " + body
|
body = "* " + body
|
||||||
|
|
@ -565,44 +434,27 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const flags = message.flags || 0
|
const flags = message.flags || 0
|
||||||
if (flags & DiscordTypes.MessageFlags.IsCrosspost) {
|
if (flags & 2) {
|
||||||
body = `[🔀 ${message.author.username}]\n` + body
|
body = `[🔀 ${message.author.username}]\n` + body
|
||||||
html = `🔀 <strong>${message.author.username}</strong><br>` + html
|
html = `🔀 <strong>${message.author.username}</strong><br>` + html
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback body/formatted_body for replies
|
// Fallback body/formatted_body for replies
|
||||||
// Generate a fallback if native replies are unsupported, which is in the following situations:
|
|
||||||
// 1. The replied-to event is in a different room to where the reply will be sent (i.e. a room upgrade occurred between)
|
|
||||||
// 2. The replied-to message has no corresponding Matrix event (repliedToUnknownEvent is true)
|
|
||||||
// This branch is optional - do NOT change anything apart from the reply fallback, since it may not be run
|
// This branch is optional - do NOT change anything apart from the reply fallback, since it may not be run
|
||||||
if ((repliedToEventRow || repliedToUnknownEvent) && options.includeReplyFallback !== false && events.length === 0) {
|
if (repliedToEventRow && options.includeReplyFallback !== false) {
|
||||||
const latestRoomID = repliedToEventRow ? select("channel_room", "room_id", {channel_id: repliedToEventRow.channel_id}).pluck().get() : null
|
|
||||||
if (latestRoomID !== repliedToEventRow?.room_id) repliedToEventInDifferentRoom = true
|
|
||||||
|
|
||||||
// check that condition 1 or 2 is met
|
|
||||||
if (repliedToEventInDifferentRoom || repliedToUnknownEvent) {
|
|
||||||
let referenced = message.referenced_message
|
|
||||||
if (!referenced) { // backend couldn't be bothered to dereference the message, have to do it ourselves
|
|
||||||
assert(message.message_reference?.message_id)
|
|
||||||
referenced = await discord.snow.channel.getChannelMessage(message.message_reference.channel_id, message.message_reference.message_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Username
|
|
||||||
let repliedToDisplayName
|
let repliedToDisplayName
|
||||||
let repliedToUserHtml
|
let repliedToUserHtml
|
||||||
if (repliedToEventRow?.source === 0 && repliedToEventSenderMxid) {
|
if (repliedToEventRow?.source === 0 && repliedToEventSenderMxid) {
|
||||||
const match = repliedToEventSenderMxid.match(/^@([^:]*)/)
|
const match = repliedToEventSenderMxid.match(/^@([^:]*)/)
|
||||||
assert(match)
|
assert(match)
|
||||||
repliedToDisplayName = referenced.author.username || match[1] || "a Matrix user" // grab the localpart as the display name, whatever
|
repliedToDisplayName = message.referenced_message?.author.username || match[1] || "a Matrix user" // grab the localpart as the display name, whatever
|
||||||
repliedToUserHtml = `<a href="https://matrix.to/#/${repliedToEventSenderMxid}">${repliedToDisplayName}</a>`
|
repliedToUserHtml = `<a href="https://matrix.to/#/${repliedToEventSenderMxid}">${repliedToDisplayName}</a>`
|
||||||
} else {
|
} else {
|
||||||
repliedToDisplayName = referenced.author.global_name || referenced.author.username || "a Discord user"
|
repliedToDisplayName = message.referenced_message?.author.global_name || message.referenced_message?.author.username || "a Discord user"
|
||||||
repliedToUserHtml = repliedToDisplayName
|
repliedToUserHtml = repliedToDisplayName
|
||||||
}
|
}
|
||||||
|
let repliedToContent = message.referenced_message?.content
|
||||||
// Content
|
if (repliedToContent?.match(/^(-# )?> (-# )?<:L1:/)) {
|
||||||
let repliedToContent = referenced.content
|
|
||||||
if (repliedToContent?.match(/^(-# )?> (-# )?<?:L1:/)) {
|
|
||||||
// If the Discord user is replying to a Matrix user's reply, the fallback is going to contain the emojis and stuff from the bridged rep of the Matrix user's reply quote.
|
// If the Discord user is replying to a Matrix user's reply, the fallback is going to contain the emojis and stuff from the bridged rep of the Matrix user's reply quote.
|
||||||
// Need to remove that previous reply rep from this fallback body. The fallbody body should only contain the Matrix user's actual message.
|
// Need to remove that previous reply rep from this fallback body. The fallbody body should only contain the Matrix user's actual message.
|
||||||
// ┌──────A─────┐ A reply rep starting with >quote or -#smalltext >quote. Match until the end of the line.
|
// ┌──────A─────┐ A reply rep starting with >quote or -#smalltext >quote. Match until the end of the line.
|
||||||
|
|
@ -610,39 +462,37 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
repliedToContent = repliedToContent.replace(/^((-# )?> .*\n){1,2}/, "")
|
repliedToContent = repliedToContent.replace(/^((-# )?> .*\n){1,2}/, "")
|
||||||
}
|
}
|
||||||
if (repliedToContent == "") repliedToContent = "[Media]"
|
if (repliedToContent == "") repliedToContent = "[Media]"
|
||||||
const {body: repliedToBody, html: repliedToHtml} = await transformContent(repliedToContent)
|
else if (!repliedToContent) repliedToContent = "[Replied-to message content wasn't provided by Discord]"
|
||||||
|
const repliedToHtml = markdown.toHTML(repliedToContent, {
|
||||||
// Now branch on condition 1 or 2 for a different kind of fallback
|
discordCallback: getDiscordParseCallbacks(message, guild, true)
|
||||||
if (repliedToEventRow) {
|
})
|
||||||
html = `<blockquote><a href="https://matrix.to/#/${repliedToEventRow.room_id}/${repliedToEventRow.event_id}">In reply to</a> ${repliedToUserHtml}`
|
const repliedToBody = markdown.toHTML(repliedToContent, {
|
||||||
+ `<br>${repliedToHtml}</blockquote>`
|
discordCallback: getDiscordParseCallbacks(message, guild, false),
|
||||||
|
discordOnly: true,
|
||||||
|
escapeHTML: false,
|
||||||
|
})
|
||||||
|
html = `<mx-reply><blockquote><a href="https://matrix.to/#/${repliedToEventRow.room_id}/${repliedToEventRow.event_id}">In reply to</a> ${repliedToUserHtml}`
|
||||||
|
+ `<br>${repliedToHtml}</blockquote></mx-reply>`
|
||||||
+ html
|
+ html
|
||||||
body = `${repliedToDisplayName}: ${repliedToBody}`.split("\n").map(line => "> " + line).join("\n") // scenario 1 part B for mentions
|
body = (`${repliedToDisplayName}: ` // scenario 1 part B for mentions
|
||||||
|
+ repliedToBody).split("\n").map(line => "> " + line).join("\n")
|
||||||
+ "\n\n" + body
|
+ "\n\n" + body
|
||||||
} else { // repliedToUnknownEvent
|
|
||||||
const dateDisplay = dUtils.howOldUnbridgedMessage(referenced.timestamp, message.timestamp)
|
|
||||||
html = `<blockquote>In reply to ${dateDisplay} from ${repliedToDisplayName}:`
|
|
||||||
+ `<br>${repliedToHtml}</blockquote>`
|
|
||||||
+ html
|
|
||||||
body = `In reply to ${dateDisplay}:\n${repliedToDisplayName}: ${repliedToBody}`.split("\n").map(line => "> " + line).join("\n")
|
|
||||||
+ "\n\n" + body
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isInteraction && !isThinkingInteraction && events.length === 0) {
|
|
||||||
const formattedInteraction = getFormattedInteraction(interaction, false)
|
|
||||||
body = `${formattedInteraction.body}\n${body}`
|
|
||||||
html = `${formattedInteraction.html}${html}`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const newTextMessageEvent = {
|
const newTextMessageEvent = {
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
"m.mentions": mentions,
|
"m.mentions": mentions,
|
||||||
msgtype,
|
msgtype,
|
||||||
body: body,
|
body: body
|
||||||
|
}
|
||||||
|
|
||||||
|
const isPlaintext = body === html
|
||||||
|
|
||||||
|
if (!isPlaintext) {
|
||||||
|
Object.assign(newTextMessageEvent, {
|
||||||
format: "org.matrix.custom.html",
|
format: "org.matrix.custom.html",
|
||||||
formatted_body: html
|
formatted_body: html
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
events.push(newTextMessageEvent)
|
events.push(newTextMessageEvent)
|
||||||
|
|
@ -656,332 +506,51 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
message.content = "changed the channel name to **" + message.content + "**"
|
message.content = "changed the channel name to **" + message.content + "**"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle message type 63, new emoji announcement
|
|
||||||
// @ts-expect-error - should be changed to a DiscordTypes reference once it has been documented
|
|
||||||
if (message.type === 63) {
|
|
||||||
const match = message.content.match(/^<(a?):([^:>]{1,64}):([0-9]+)>$/)
|
|
||||||
assert(match, `message type 63, which announces a new emoji, did not include an emoji. the actual content was: "${message.content}"`)
|
|
||||||
const name = match[2]
|
|
||||||
msgtype = "m.emote"
|
|
||||||
message.content = `added a new emoji, ${message.content} :${name}:`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send Klipy GIFs in customised form
|
if (message.content) {
|
||||||
let isKlipyGIF = false
|
|
||||||
let isOnlyKlipyGIF = false
|
|
||||||
if (message.embeds?.length === 1 && message.embeds[0].provider?.name === "Klipy" && message.embeds[0].video?.url) {
|
|
||||||
isKlipyGIF = true
|
|
||||||
if (message.content.match(/^https?:\/\/klipy\.com[^ \n]+$/)) {
|
|
||||||
isOnlyKlipyGIF = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Forwarded content appears first
|
|
||||||
if (message.message_reference?.type === DiscordTypes.MessageReferenceType.Forward && message.message_reference.message_id && message.message_snapshots?.length) {
|
|
||||||
// Forwarded notice
|
|
||||||
const row = await getHistoricalEventRow(message.message_reference.message_id, message.message_reference.channel_id)
|
|
||||||
const room = select("channel_room", ["room_id", "name", "nick"], {channel_id: message.message_reference.channel_id}).get()
|
|
||||||
const forwardedNotice = new mxUtils.MatrixStringBuilder()
|
|
||||||
if (room) {
|
|
||||||
const roomName = room && (room.nick || room.name)
|
|
||||||
if (row && "event_id" in row) {
|
|
||||||
const via = await getViaServersMemo(row.room_id)
|
|
||||||
forwardedNotice.addLine(
|
|
||||||
`[🔀 Forwarded from #${roomName}]`,
|
|
||||||
tag`🔀 <em>Forwarded from ${roomName} <a href="https://matrix.to/#/${room.room_id}/${row.event_id}?${via}">[jump to event]</a></em>`
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
const via = await getViaServersMemo(room.room_id)
|
|
||||||
forwardedNotice.addLine(
|
|
||||||
`[🔀 Forwarded from #${roomName}]`,
|
|
||||||
tag`🔀 <em>Forwarded from ${roomName} <a href="https://matrix.to/#/${room.room_id}?${via}">[jump to room]</a></em>`
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
forwardedNotice.addLine(
|
|
||||||
`[🔀 Forwarded message]`,
|
|
||||||
tag`🔀 <em>Forwarded message</em>`
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Forwarded content
|
|
||||||
// @ts-ignore
|
|
||||||
const forwardedEvents = await messageToEvent(message.message_snapshots[0].message, guild, {includeReplyFallback: false, includeEditFallbackStar: false, alwaysReturnFormattedBody: true, scanTextForMentions: false}, di)
|
|
||||||
|
|
||||||
// Indent
|
|
||||||
for (const event of forwardedEvents) {
|
|
||||||
if (["m.text", "m.notice"].includes(event.msgtype)) {
|
|
||||||
event.body = event.body.split("\n").map(l => "» " + l).join("\n")
|
|
||||||
event.formatted_body = `<blockquote>${event.formatted_body}</blockquote>`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to merge the forwarded content with the forwarded notice
|
|
||||||
let {body, formatted_body} = forwardedNotice.get()
|
|
||||||
if (forwardedEvents.length >= 1 && ["m.text", "m.notice"].includes(forwardedEvents[0].msgtype)) { // Try to merge the forwarded content and the forwarded notice
|
|
||||||
forwardedEvents[0].body = body + "\n" + forwardedEvents[0].body
|
|
||||||
forwardedEvents[0].formatted_body = formatted_body + "<br>" + forwardedEvents[0].formatted_body
|
|
||||||
} else {
|
|
||||||
await addTextEvent(body, formatted_body, "m.notice")
|
|
||||||
}
|
|
||||||
events.push(...forwardedEvents)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isThinkingInteraction) {
|
|
||||||
const formattedInteraction = getFormattedInteraction(interaction, true)
|
|
||||||
await addTextEvent(formattedInteraction.body, formattedInteraction.html, "m.notice")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then text content
|
|
||||||
if (message.content && !isOnlyKlipyGIF && !isThinkingInteraction) {
|
|
||||||
// Mentions scenario 3: scan the message content for written @mentions of matrix users. Allows for up to one space between @ and mention.
|
// Mentions scenario 3: scan the message content for written @mentions of matrix users. Allows for up to one space between @ and mention.
|
||||||
let content = message.content
|
const matches = [...message.content.matchAll(/@ ?([a-z0-9._]+)\b/gi)]
|
||||||
if (options.scanTextForMentions !== false) {
|
if (matches.length && matches.some(m => m[1].match(/[a-z]/i) && m[1] !== "everyone" && m[1] !== "here")) {
|
||||||
const matches = [...content.matchAll(/(@ ?)([a-z0-9_.#$][^@\n]+)/gi)]
|
const writtenMentionsText = matches.map(m => m[1].toLowerCase())
|
||||||
for (let i = matches.length; i--;) {
|
const roomID = select("channel_room", "room_id", {channel_id: message.channel_id}).pluck().get()
|
||||||
const m = matches[i]
|
|
||||||
const prefix = m[1]
|
|
||||||
const maximumWrittenSection = m[2].toLowerCase()
|
|
||||||
if (m.index > 0 && !content[m.index-1].match(/ |\(|\n/)) continue // must have space before it
|
|
||||||
if (maximumWrittenSection.match(/^everyone\b/) || maximumWrittenSection.match(/^here\b/)) continue // ignore @everyone/@here
|
|
||||||
|
|
||||||
var roomID = roomID ?? select("channel_room", "room_id", {channel_id: message.channel_id}).pluck().get()
|
|
||||||
assert(roomID)
|
assert(roomID)
|
||||||
var pjr = pjr ?? findMentions.processJoined(Object.entries((await di.api.getJoinedMembers(roomID)).joined).map(([mxid, ev]) => ({mxid, displayname: ev.display_name})))
|
const {joined} = await di.api.getJoinedMembers(roomID)
|
||||||
|
for (const [mxid, member] of Object.entries(joined)) {
|
||||||
const found = findMentions.findMention(pjr, maximumWrittenSection, m.index, prefix, content)
|
if (!userRegex.some(rx => mxid.match(rx))) {
|
||||||
if (found) {
|
const localpart = mxid.match(/@([^:]*)/)
|
||||||
addMention(found.mxid)
|
assert(localpart)
|
||||||
content = found.newContent
|
const displayName = member.display_name || localpart[1]
|
||||||
|
if (writtenMentionsText.includes(localpart[1].toLowerCase()) || writtenMentionsText.includes(displayName.toLowerCase())) addMention(mxid)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Scan the content for emojihax and replace them with real emojis
|
// Text content appears first
|
||||||
content = content.replaceAll(/\[([a-zA-Z0-9_-]{2,32})(?:~[0-9]+)?\]\(https:\/\/cdn\.discordapp\.com\/emojis\/([0-9]+)\.[^ \n)`]+\)/g, (_, name, id) => {
|
const {body, html} = await transformContent(message.content)
|
||||||
return `<:${name}:${id}>`
|
await addTextEvent(body, html, msgtype, {scanMentions: true})
|
||||||
})
|
|
||||||
|
|
||||||
const {body, html} = await transformContent(content)
|
|
||||||
await addTextEvent(body, html, msgtype)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then scheduled events
|
|
||||||
if (message.content && di?.snow) {
|
|
||||||
for (const match of [...message.content.matchAll(/discord\.gg\/([A-Za-z0-9]+)\?event=([0-9]{18,})/g)]) { // snowflake has minimum 18 because the events feature is at least that old
|
|
||||||
const invite = await di.snow.invite.getInvite(match[1], {guild_scheduled_event_id: match[2]})
|
|
||||||
const event = invite.guild_scheduled_event
|
|
||||||
if (!event) continue // the event ID provided was not valid
|
|
||||||
|
|
||||||
const formatter = new Intl.DateTimeFormat("en-NZ", {month: "long", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "shortGeneric", timeZone: reg.ooye.time_zone}) // 9 June at 3:00 pm NZT
|
|
||||||
const rep = new mxUtils.MatrixStringBuilder()
|
|
||||||
|
|
||||||
// Add time
|
|
||||||
if (event.scheduled_end_time) {
|
|
||||||
// @ts-ignore - no definition available for formatRange
|
|
||||||
rep.addParagraph(`Scheduled Event - ${formatter.formatRange(new Date(event.scheduled_start_time), new Date(event.scheduled_end_time))}`)
|
|
||||||
} else {
|
|
||||||
rep.addParagraph(`Scheduled Event - ${formatter.format(new Date(event.scheduled_start_time))}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add details
|
|
||||||
rep.addLine(`## ${event.name}`, tag`<strong>${event.name}</strong>`)
|
|
||||||
if (event.description) rep.addLine(event.description)
|
|
||||||
|
|
||||||
// Add location
|
|
||||||
if (event.entity_metadata?.location) {
|
|
||||||
rep.addParagraph(`📍 ${event.entity_metadata.location}`)
|
|
||||||
} else if (invite.channel?.name) {
|
|
||||||
const roomID = select("channel_room", "room_id", {channel_id: invite.channel.id}).pluck().get()
|
|
||||||
if (roomID) {
|
|
||||||
const via = await getViaServersMemo(roomID)
|
|
||||||
rep.addParagraph(`🔊 ${invite.channel.name} - https://matrix.to/#/${roomID}?${via}`, tag`🔊 ${invite.channel.name} - <a href="https://matrix.to/#/${roomID}?${via}">${invite.channel.name}</a>`)
|
|
||||||
} else {
|
|
||||||
rep.addParagraph(`🔊 ${invite.channel.name}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send like an embed
|
|
||||||
let {body, formatted_body: html} = rep.get()
|
|
||||||
body = body.split("\n").map(l => "| " + l).join("\n")
|
|
||||||
html = `<blockquote>${html}</blockquote>`
|
|
||||||
await addTextEvent(body, html, "m.notice")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Then attachments
|
// Then attachments
|
||||||
if (message.attachments) {
|
if (message.attachments) {
|
||||||
const attachmentEvents = await Promise.all(message.attachments.map(attachment => attachmentToEvent(mentions, attachment)))
|
const attachmentEvents = await Promise.all(message.attachments.map(attachmentToEvent.bind(null, mentions)))
|
||||||
|
events.push(...attachmentEvents)
|
||||||
// Try to merge attachment events with the previous event
|
|
||||||
// This means that if the attachments ended up as a text link, and especially if there were many of them, the events will be joined together.
|
|
||||||
let prev = events.at(-1)
|
|
||||||
for (const atch of attachmentEvents) {
|
|
||||||
if (atch.msgtype === "m.text" && prev?.body && prev?.formatted_body && ["m.text", "m.notice"].includes(prev?.msgtype)) {
|
|
||||||
prev.body = prev.body + "\n" + atch.body
|
|
||||||
prev.formatted_body = prev.formatted_body + "<br>" + atch.formatted_body
|
|
||||||
} else {
|
|
||||||
events.push(atch)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then components
|
|
||||||
if (message.components?.length) {
|
|
||||||
const stack = new mxUtils.MatrixStringBuilderStack()
|
|
||||||
/** @param {DiscordTypes.APIMessageComponent} component */
|
|
||||||
async function processComponent(component) {
|
|
||||||
// Standalone components
|
|
||||||
if (component.type === DiscordTypes.ComponentType.TextDisplay) {
|
|
||||||
const {body, html} = await transformContent(component.content)
|
|
||||||
stack.msb.addParagraph(body, html)
|
|
||||||
}
|
|
||||||
else if (component.type === DiscordTypes.ComponentType.Separator) {
|
|
||||||
stack.msb.addParagraph("----", "<hr>")
|
|
||||||
}
|
|
||||||
else if (component.type === DiscordTypes.ComponentType.File) {
|
|
||||||
/** @type {{[k in keyof DiscordTypes.APIUnfurledMediaItem]-?: NonNullable<DiscordTypes.APIUnfurledMediaItem[k]>}} */ // @ts-ignore
|
|
||||||
const file = component.file
|
|
||||||
assert(component.name && component.size && file.content_type)
|
|
||||||
const ev = await attachmentToEvent({}, {...file, filename: component.name, size: component.size}, true)
|
|
||||||
stack.msb.addLine(ev.body, ev.formatted_body)
|
|
||||||
}
|
|
||||||
else if (component.type === DiscordTypes.ComponentType.MediaGallery) {
|
|
||||||
const description = component.items.length === 1 ? component.items[0].description || "Image:" : "Image gallery:"
|
|
||||||
const images = component.items.map(item => {
|
|
||||||
const publicURL = dUtils.getPublicUrlForCdn(item.media.url)
|
|
||||||
return {
|
|
||||||
url: publicURL,
|
|
||||||
estimatedName: item.media.url.match(/\/([^/?]+)(\?|$)/)?.[1] || publicURL
|
|
||||||
}
|
|
||||||
})
|
|
||||||
stack.msb.addLine(`🖼️ ${description} ${images.map(i => i.url).join(", ")}`, tag`🖼️ ${description} $${images.map(i => tag`<a href="${i.url}">${i.estimatedName}</a>`).join(", ")}`)
|
|
||||||
}
|
|
||||||
// string select, text input, user select, role select, mentionable select, channel select
|
|
||||||
|
|
||||||
// Components that can have things nested
|
|
||||||
else if (component.type === DiscordTypes.ComponentType.Container) {
|
|
||||||
// May contain action row, text display, section, media gallery, separator, file
|
|
||||||
stack.bump()
|
|
||||||
for (const innerComponent of component.components) {
|
|
||||||
await processComponent(innerComponent)
|
|
||||||
}
|
|
||||||
let {body, formatted_body} = stack.shift().get()
|
|
||||||
body = body.split("\n").map(l => "| " + l).join("\n")
|
|
||||||
formatted_body = `<blockquote>${formatted_body}</blockquote>`
|
|
||||||
if (stack.msb.body) stack.msb.body += "\n\n"
|
|
||||||
stack.msb.add(body, formatted_body)
|
|
||||||
}
|
|
||||||
else if (component.type === DiscordTypes.ComponentType.Section) {
|
|
||||||
// May contain text display, possibly more in the future
|
|
||||||
// Accessory may be button or thumbnail
|
|
||||||
stack.bump()
|
|
||||||
for (const innerComponent of component.components) {
|
|
||||||
await processComponent(innerComponent)
|
|
||||||
}
|
|
||||||
if (component.accessory) {
|
|
||||||
stack.bump()
|
|
||||||
await processComponent(component.accessory)
|
|
||||||
const {body, formatted_body} = stack.shift().get()
|
|
||||||
stack.msb.addLine(body, formatted_body)
|
|
||||||
}
|
|
||||||
const {body, formatted_body} = stack.shift().get()
|
|
||||||
stack.msb.addParagraph(body, formatted_body)
|
|
||||||
}
|
|
||||||
else if (component.type === DiscordTypes.ComponentType.ActionRow) {
|
|
||||||
const linkButtons = component.components.filter(c => c.type === DiscordTypes.ComponentType.Button && c.style === DiscordTypes.ButtonStyle.Link)
|
|
||||||
if (linkButtons.length) {
|
|
||||||
stack.msb.addLine("")
|
|
||||||
for (const linkButton of linkButtons) {
|
|
||||||
await processComponent(linkButton)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Components that can only be inside things
|
|
||||||
else if (component.type === DiscordTypes.ComponentType.Thumbnail) {
|
|
||||||
// May only be a section accessory
|
|
||||||
stack.msb.add(`🖼️ ${component.media.url}`, tag`🖼️ <a href="${component.media.url}">${component.media.url}</a>`)
|
|
||||||
}
|
|
||||||
else if (component.type === DiscordTypes.ComponentType.Button) {
|
|
||||||
// May only be a section accessory or in an action row (up to 5)
|
|
||||||
if (component.style === DiscordTypes.ButtonStyle.Link) {
|
|
||||||
if (component.label) {
|
|
||||||
stack.msb.add(`[${component.label} ${component.url}] `, tag`<a href="${component.url}">${component.label}</a> `)
|
|
||||||
} else {
|
|
||||||
stack.msb.add(component.url)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Not handling file upload or label because they are modal-only components
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const component of message.components) {
|
|
||||||
await processComponent(component)
|
|
||||||
}
|
|
||||||
|
|
||||||
const {body, formatted_body} = stack.msb.get()
|
|
||||||
if (body.trim().length) {
|
|
||||||
await addTextEvent(body, formatted_body, "m.text")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then polls
|
|
||||||
if (message.poll) {
|
|
||||||
const pollEvent = await pollToEvent(message.poll)
|
|
||||||
events.push(pollEvent)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Then embeds
|
// Then embeds
|
||||||
const urlPreviewEnabled = select("guild_space", "url_preview", {guild_id: guild?.id}).pluck().get() ?? 1
|
|
||||||
for (const embed of message.embeds || []) {
|
for (const embed of message.embeds || []) {
|
||||||
if (!urlPreviewEnabled && !message.author?.bot) {
|
|
||||||
continue // show embeds for everyone if enabled, or bot users only if disabled (bots often send content in embeds)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (embed.type === "image") {
|
if (embed.type === "image") {
|
||||||
continue // Matrix's own URL previews are fine for images.
|
continue // Matrix's own URL previews are fine for images.
|
||||||
}
|
}
|
||||||
|
|
||||||
if (embed.type === "video" && embed.video?.url && !embed.title && message.content.includes(embed.video.url)) {
|
|
||||||
continue // Doesn't add extra information and the direct video URL is already there.
|
|
||||||
}
|
|
||||||
|
|
||||||
if (embed.type === "poll_result") {
|
|
||||||
// The code here is only for the message to be bridged to Matrix. Dealing with the Discord-side updates is in d2m/actions/poll-end.js.
|
|
||||||
}
|
|
||||||
|
|
||||||
if (embed.url?.startsWith("https://discord.com/")) {
|
if (embed.url?.startsWith("https://discord.com/")) {
|
||||||
continue // If discord creates an embed preview for a discord channel link, don't copy that embed
|
continue // If discord creates an embed preview for a discord channel link, don't copy that embed
|
||||||
}
|
}
|
||||||
|
|
||||||
if (embed.url && spoilers.some(sp => sp.match(/\bhttps?:\/\/[a-z]/))) {
|
|
||||||
// If the original message had spoilered URLs, don't generate any embeds for links.
|
|
||||||
// This logic is the same as the Discord desktop client. It doesn't match specific embeds to specific spoilered text, it's all or nothing.
|
|
||||||
// It's not easy to do much better because posting a link like youtu.be generates an embed.url with youtube.com/watch, so you can't match up the text without making at least that a special case.
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start building up a replica ("rep") of the embed in Discord-markdown format, which we will convert into both plaintext and formatted body at once
|
// Start building up a replica ("rep") of the embed in Discord-markdown format, which we will convert into both plaintext and formatted body at once
|
||||||
const rep = new mxUtils.MatrixStringBuilder()
|
const rep = new mxUtils.MatrixStringBuilder()
|
||||||
|
|
||||||
if (isKlipyGIF) {
|
|
||||||
assert(embed.video?.url)
|
|
||||||
rep.add("[GIF] ", "➿ ")
|
|
||||||
if (embed.title) {
|
|
||||||
rep.add(`${embed.title} ${embed.video.url}`, tag`<a href="${embed.video.url}">${embed.title}</a>`)
|
|
||||||
} else {
|
|
||||||
rep.add(embed.video.url)
|
|
||||||
}
|
|
||||||
|
|
||||||
let {body, formatted_body: html} = rep.get()
|
|
||||||
html = `<blockquote>${html}</blockquote>`
|
|
||||||
await addTextEvent(body, html, "m.text")
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Provider
|
// Provider
|
||||||
if (embed.provider?.name && embed.provider.name !== "Tenor") {
|
if (embed.provider?.name) {
|
||||||
if (embed.provider.url) {
|
if (embed.provider.url) {
|
||||||
rep.addParagraph(`via ${embed.provider.name} ${embed.provider.url}`, tag`<sub><a href="${embed.provider.url}">${embed.provider.name}</a></sub>`)
|
rep.addParagraph(`via ${embed.provider.name} ${embed.provider.url}`, tag`<sub><a href="${embed.provider.url}">${embed.provider.name}</a></sub>`)
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -1030,9 +599,9 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
let chosenImage = embed.image?.url
|
let chosenImage = embed.image?.url
|
||||||
// the thumbnail seems to be used for "article" type but displayed big at the bottom by discord
|
// the thumbnail seems to be used for "article" type but displayed big at the bottom by discord
|
||||||
if (embed.type === "article" && embed.thumbnail?.url && !chosenImage) chosenImage = embed.thumbnail.url
|
if (embed.type === "article" && embed.thumbnail?.url && !chosenImage) chosenImage = embed.thumbnail.url
|
||||||
if (chosenImage) rep.addParagraph(`📸 ${dUtils.getPublicUrlForCdn(chosenImage)}`)
|
if (chosenImage) rep.addParagraph(`📸 ${chosenImage}`)
|
||||||
|
|
||||||
if (embed.video?.url) rep.addParagraph(`🎞️ ${dUtils.getPublicUrlForCdn(embed.video.url)}`)
|
if (embed.video?.url) rep.addParagraph(`🎞️ ${embed.video.url}`)
|
||||||
|
|
||||||
if (embed.footer?.text) rep.addLine(`— ${embed.footer.text}`, tag`— ${embed.footer.text}`)
|
if (embed.footer?.text) rep.addLine(`— ${embed.footer.text}`, tag`— ${embed.footer.text}`)
|
||||||
let {body, formatted_body: html} = rep.get()
|
let {body, formatted_body: html} = rep.get()
|
||||||
|
|
@ -1040,7 +609,7 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
html = `<blockquote>${html}</blockquote>`
|
html = `<blockquote>${html}</blockquote>`
|
||||||
|
|
||||||
// Send as m.notice to apply the usual automated/subtle appearance, showing this wasn't actually typed by the person
|
// Send as m.notice to apply the usual automated/subtle appearance, showing this wasn't actually typed by the person
|
||||||
await addTextEvent(body, html, "m.notice")
|
await addTextEvent(body, html, "m.notice", {scanMentions: false})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Then stickers
|
// Then stickers
|
||||||
|
|
@ -1076,7 +645,7 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rich replies
|
// Rich replies
|
||||||
if (repliedToEventRow && !repliedToEventInDifferentRoom) {
|
if (repliedToEventRow) {
|
||||||
Object.assign(events[0], {
|
Object.assign(events[0], {
|
||||||
"m.relates_to": {
|
"m.relates_to": {
|
||||||
"m.in_reply_to": {
|
"m.in_reply_to": {
|
||||||
|
|
@ -1086,16 +655,6 @@ async function messageToEvent(message, guild, options = {}, di) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Strip formatted_body where equivalent to body
|
|
||||||
if (!options.alwaysReturnFormattedBody) {
|
|
||||||
for (const event of events) {
|
|
||||||
if (event.$type === "m.room.message" && "msgtype" in event && ["m.text", "m.notice"].includes(event.msgtype) && event.body === event.formatted_body) {
|
|
||||||
delete event.format
|
|
||||||
delete event.formatted_body
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return events
|
return events
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -50,7 +50,11 @@ test("message2event: pk reply to matrix is converted to native matrix reply", as
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: "this is a reply",
|
body: "> cadence [they]: now for my next experiment:\n\nthis is a reply",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: '<mx-reply><blockquote><a href="https://matrix.to/#/!TqlyQmifxGUggEmdBN:cadence.moe/$NB6nPgO2tfXyIwwDSF0Ga0BUrsgX1S-0Xl-jAvI8ucU">In reply to</a> <a href="https://matrix.to/#/@cadence:cadence.moe">cadence [they]</a><br>'
|
||||||
|
+ "now for my next experiment:</blockquote></mx-reply>"
|
||||||
|
+ "this is a reply",
|
||||||
"m.relates_to": {
|
"m.relates_to": {
|
||||||
"m.in_reply_to": {
|
"m.in_reply_to": {
|
||||||
event_id: "$NB6nPgO2tfXyIwwDSF0Ga0BUrsgX1S-0Xl-jAvI8ucU"
|
event_id: "$NB6nPgO2tfXyIwwDSF0Ga0BUrsgX1S-0Xl-jAvI8ucU"
|
||||||
|
|
@ -76,7 +80,11 @@ test("message2event: pk reply to discord is converted to native matrix reply", a
|
||||||
$type: "m.room.message",
|
$type: "m.room.message",
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
"m.mentions": {},
|
"m.mentions": {},
|
||||||
body: "this is a reply",
|
body: "> wing: some text\n\nthis is a reply",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: '<mx-reply><blockquote><a href="https://matrix.to/#/!kLRqKKUQXcibIMtOpl:cadence.moe/$mtR8cJqM4fKno1bVsm8F4wUVqSntt2sq6jav1lyavuA">In reply to</a> wing<br>'
|
||||||
|
+ "some text</blockquote></mx-reply>"
|
||||||
|
+ "this is a reply",
|
||||||
"m.relates_to": {
|
"m.relates_to": {
|
||||||
"m.in_reply_to": {
|
"m.in_reply_to": {
|
||||||
event_id: "$mtR8cJqM4fKno1bVsm8F4wUVqSntt2sq6jav1lyavuA"
|
event_id: "$mtR8cJqM4fKno1bVsm8F4wUVqSntt2sq6jav1lyavuA"
|
||||||
|
|
@ -112,7 +120,11 @@ test("message2event: pk reply to matrix attachment is converted to native matrix
|
||||||
"m.mentions": {
|
"m.mentions": {
|
||||||
user_ids: ["@ampflower:matrix.org"]
|
user_ids: ["@ampflower:matrix.org"]
|
||||||
},
|
},
|
||||||
body: "Cat nod",
|
body: "> Ampflower 🌺: [Media]\n\nCat nod",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: '<mx-reply><blockquote><a href="https://matrix.to/#/!TqlyQmifxGUggEmdBN:cadence.moe/$OEEK-Wam2FTh6J-6kVnnJ6KnLA_lLRnLTHatKKL62-Y">In reply to</a> <a href="https://matrix.to/#/@ampflower:matrix.org">Ampflower 🌺</a><br>'
|
||||||
|
+ "[Media]</blockquote></mx-reply>"
|
||||||
|
+ "Cat nod",
|
||||||
"m.relates_to": {
|
"m.relates_to": {
|
||||||
"m.in_reply_to": {
|
"m.in_reply_to": {
|
||||||
event_id: "$OEEK-Wam2FTh6J-6kVnnJ6KnLA_lLRnLTHatKKL62-Y"
|
event_id: "$OEEK-Wam2FTh6J-6kVnnJ6KnLA_lLRnLTHatKKL62-Y"
|
||||||
|
|
@ -1,79 +0,0 @@
|
||||||
const {test} = require("supertape")
|
|
||||||
const {messageToEvent} = require("./message-to-event")
|
|
||||||
const data = require("../../../test/data")
|
|
||||||
|
|
||||||
test("message2event components: pk question mark output", async t => {
|
|
||||||
const events = await messageToEvent(data.message_with_components.pk_question_mark_response, data.guild.general, {})
|
|
||||||
t.deepEqual(events, [{
|
|
||||||
$type: "m.room.message",
|
|
||||||
body:
|
|
||||||
"| ### Lillith (INX)"
|
|
||||||
+ "\n| "
|
|
||||||
+ "\n| **Display name:** Lillith (she/her)"
|
|
||||||
+ "\n| **Pronouns:** She/Her"
|
|
||||||
+ "\n| **Message count:** 3091"
|
|
||||||
+ "\n| 🖼️ https://files.inx.moe/p/cdn/lillith.webp"
|
|
||||||
+ "\n| "
|
|
||||||
+ "\n| ----"
|
|
||||||
+ "\n| "
|
|
||||||
+ "\n| **Proxy tags:**"
|
|
||||||
+ "\n| ``l;text``"
|
|
||||||
+ "\n| ``l:text``"
|
|
||||||
+ "\n| ``l.text``"
|
|
||||||
+ "\n| ``textl.``"
|
|
||||||
+ "\n| ``textl;``"
|
|
||||||
+ "\n| ``textl:``"
|
|
||||||
+ "\n"
|
|
||||||
+ "\n-# System ID: `xffgnx` ∙ Member ID: `pphhoh`"
|
|
||||||
+ "\n-# Created: 2025-12-31 03:16:45 UTC"
|
|
||||||
+ "\n[View on dashboard https://dash.pluralkit.me/profile/m/pphhoh] "
|
|
||||||
+ "\n"
|
|
||||||
+ "\n----"
|
|
||||||
+ "\n"
|
|
||||||
+ "\n| **System:** INX (`xffgnx`)"
|
|
||||||
+ "\n| **Member:** Lillith (`pphhoh`)"
|
|
||||||
+ "\n| **Sent by:** infinidoge1337 (@unknown-user:)"
|
|
||||||
+ "\n| "
|
|
||||||
+ "\n| **Account Roles (7)**"
|
|
||||||
+ "\n| §b, !, ‼, Ears Port Ping, Ears Update Ping, Yttr Ping, unsup Ping"
|
|
||||||
+ "\n| 🖼️ https://files.inx.moe/p/cdn/lillith.webp"
|
|
||||||
+ "\n| "
|
|
||||||
+ "\n| ----"
|
|
||||||
+ "\n| "
|
|
||||||
+ "\n| Same hat"
|
|
||||||
+ "\n| 🖼️ Image: https://bridge.example.org/download/discordcdn/934955898965729280/1466556006527012987/image.png"
|
|
||||||
+ "\n"
|
|
||||||
+ "\n-# Original Message ID: 1466556003645657118 · <t:1769724599:f>",
|
|
||||||
format: "org.matrix.custom.html",
|
|
||||||
formatted_body: "<blockquote>"
|
|
||||||
+ "<h3>Lillith (INX)</h3>"
|
|
||||||
+ "<p><strong>Display name:</strong> Lillith (she/her)"
|
|
||||||
+ "<br><strong>Pronouns:</strong> She/Her"
|
|
||||||
+ "<br><strong>Message count:</strong> 3091</p>"
|
|
||||||
+ `🖼️ <a href="https://files.inx.moe/p/cdn/lillith.webp">https://files.inx.moe/p/cdn/lillith.webp</a>`
|
|
||||||
+ "<hr>"
|
|
||||||
+ "<p><strong>Proxy tags:</strong>"
|
|
||||||
+ "<br><code>l;text</code>"
|
|
||||||
+ "<br><code>l:text</code>"
|
|
||||||
+ "<br><code>l.text</code>"
|
|
||||||
+ "<br><code>textl.</code>"
|
|
||||||
+ "<br><code>textl;</code>"
|
|
||||||
+ "<br><code>textl:</code></p></blockquote>"
|
|
||||||
+ "<p><sub>System ID: <code>xffgnx</code> ∙ Member ID: <code>pphhoh</code></sub><br>"
|
|
||||||
+ "<sub>Created: 2025-12-31 03:16:45 UTC</sub></p>"
|
|
||||||
+ `<a href="https://dash.pluralkit.me/profile/m/pphhoh">View on dashboard</a> `
|
|
||||||
+ "<hr>"
|
|
||||||
+ "<blockquote><p><strong>System:</strong> INX (<code>xffgnx</code>)"
|
|
||||||
+ "<br><strong>Member:</strong> Lillith (<code>pphhoh</code>)"
|
|
||||||
+ "<br><strong>Sent by:</strong> infinidoge1337 (@unknown-user:)"
|
|
||||||
+ "<br><br><strong>Account Roles (7)</strong>"
|
|
||||||
+ "<br>§b, !, ‼, Ears Port Ping, Ears Update Ping, Yttr Ping, unsup Ping</p>"
|
|
||||||
+ `🖼️ <a href="https://files.inx.moe/p/cdn/lillith.webp">https://files.inx.moe/p/cdn/lillith.webp</a>`
|
|
||||||
+ "<hr>"
|
|
||||||
+ "<p>Same hat</p>"
|
|
||||||
+ `🖼️ Image: <a href="https://bridge.example.org/download/discordcdn/934955898965729280/1466556006527012987/image.png">image.png</a></blockquote>`
|
|
||||||
+ "<p><sub>Original Message ID: 1466556003645657118 · <t:1769724599:f></sub></p>",
|
|
||||||
"m.mentions": {},
|
|
||||||
msgtype: "m.text",
|
|
||||||
}])
|
|
||||||
})
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -3,30 +3,17 @@
|
||||||
const {select} = require("../../passthrough")
|
const {select} = require("../../passthrough")
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {import("discord-api-types/v10").RESTGetAPIChannelMessagesPinsResult} pins
|
* @param {import("discord-api-types/v10").RESTGetAPIChannelPinsResult} pins
|
||||||
* @param {{"m.room.pinned_events/"?: {pinned?: string[]}}} kstate
|
|
||||||
*/
|
*/
|
||||||
function pinsToList(pins, kstate) {
|
function pinsToList(pins) {
|
||||||
/** Most recent last. */
|
|
||||||
let alreadyPinned = kstate["m.room.pinned_events/"]?.pinned || []
|
|
||||||
|
|
||||||
// If any of the already pinned messages are bridged messages then remove them from the already pinned list.
|
|
||||||
// * If a bridged message is still pinned then it'll be added back in the next step.
|
|
||||||
// * If a bridged message was unpinned from Discord-side then it'll be unpinned from our side due to this step.
|
|
||||||
// * Matrix-only unbridged messages that are pinned will remain pinned.
|
|
||||||
alreadyPinned = alreadyPinned.filter(event_id => {
|
|
||||||
const messageID = select("event_message", "message_id", {event_id}).pluck().get()
|
|
||||||
return !messageID || pins.items.find(m => m.message.id === messageID) // if it is bridged then remove it from the filter
|
|
||||||
})
|
|
||||||
|
|
||||||
/** @type {string[]} */
|
/** @type {string[]} */
|
||||||
const result = []
|
const result = []
|
||||||
for (const pin of pins.items) {
|
for (const message of pins) {
|
||||||
const eventID = select("event_message", "event_id", {message_id: pin.message.id, part: 0}).pluck().get()
|
const eventID = select("event_message", "event_id", {message_id: message.id, part: 0}).pluck().get()
|
||||||
if (eventID && !alreadyPinned.includes(eventID)) result.push(eventID)
|
if (eventID) result.push(eventID)
|
||||||
}
|
}
|
||||||
result.reverse()
|
result.reverse()
|
||||||
return alreadyPinned.concat(result)
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.pinsToList = pinsToList
|
module.exports.pinsToList = pinsToList
|
||||||
|
|
|
||||||
|
|
@ -1,64 +1,12 @@
|
||||||
const {test} = require("supertape")
|
const {test} = require("supertape")
|
||||||
const data = require("../../../test/data")
|
const data = require("../../../test/data")
|
||||||
const {pinsToList} = require("./pins-to-list")
|
const {pinsToList} = require("./pins-to-list")
|
||||||
const mixin = require("@cloudrac3r/mixin-deep")
|
|
||||||
|
|
||||||
test("pins2list: converts known IDs, ignores unknown IDs", t => {
|
test("pins2list: converts known IDs, ignores unknown IDs", t => {
|
||||||
const result = pinsToList(data.pins.faked, {})
|
const result = pinsToList(data.pins.faked)
|
||||||
t.deepEqual(result, [
|
t.deepEqual(result, [
|
||||||
"$lnAF9IosAECTnlv9p2e18FG8rHn-JgYKHEHIh5qdFv4",
|
"$lnAF9IosAECTnlv9p2e18FG8rHn-JgYKHEHIh5qdFv4",
|
||||||
"$mtR8cJqM4fKno1bVsm8F4wUVqSntt2sq6jav1lyavuA",
|
"$mtR8cJqM4fKno1bVsm8F4wUVqSntt2sq6jav1lyavuA",
|
||||||
"$X16nfVks1wsrhq4E9SSLiqrf2N8KD0erD0scZG7U5xg"
|
"$X16nfVks1wsrhq4E9SSLiqrf2N8KD0erD0scZG7U5xg"
|
||||||
])
|
])
|
||||||
})
|
})
|
||||||
|
|
||||||
test("pins2list: already pinned duplicate items are not moved", t => {
|
|
||||||
const result = pinsToList(data.pins.faked, {
|
|
||||||
"m.room.pinned_events/": {
|
|
||||||
pinned: [
|
|
||||||
"$mtR8cJqM4fKno1bVsm8F4wUVqSntt2sq6jav1lyavuA"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.deepEqual(result, [
|
|
||||||
"$mtR8cJqM4fKno1bVsm8F4wUVqSntt2sq6jav1lyavuA",
|
|
||||||
"$lnAF9IosAECTnlv9p2e18FG8rHn-JgYKHEHIh5qdFv4",
|
|
||||||
"$X16nfVks1wsrhq4E9SSLiqrf2N8KD0erD0scZG7U5xg"
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("pins2list: already pinned unknown items are not moved", t => {
|
|
||||||
const result = pinsToList(data.pins.faked, {
|
|
||||||
"m.room.pinned_events/": {
|
|
||||||
pinned: [
|
|
||||||
"$unknown1",
|
|
||||||
"$mtR8cJqM4fKno1bVsm8F4wUVqSntt2sq6jav1lyavuA",
|
|
||||||
"$unknown2"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.deepEqual(result, [
|
|
||||||
"$unknown1",
|
|
||||||
"$mtR8cJqM4fKno1bVsm8F4wUVqSntt2sq6jav1lyavuA",
|
|
||||||
"$unknown2",
|
|
||||||
"$lnAF9IosAECTnlv9p2e18FG8rHn-JgYKHEHIh5qdFv4",
|
|
||||||
"$X16nfVks1wsrhq4E9SSLiqrf2N8KD0erD0scZG7U5xg"
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("pins2list: bridged messages can be unpinned", t => {
|
|
||||||
const shortPins = mixin({}, data.pins.faked)
|
|
||||||
shortPins.items = shortPins.items.slice(0, -2)
|
|
||||||
const result = pinsToList(shortPins, {
|
|
||||||
"m.room.pinned_events/": {
|
|
||||||
pinned: [
|
|
||||||
"$mtR8cJqM4fKno1bVsm8F4wUVqSntt2sq6jav1lyavuA",
|
|
||||||
"$lnAF9IosAECTnlv9p2e18FG8rHn-JgYKHEHIh5qdFv4"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.deepEqual(result, [
|
|
||||||
"$mtR8cJqM4fKno1bVsm8F4wUVqSntt2sq6jav1lyavuA",
|
|
||||||
"$X16nfVks1wsrhq4E9SSLiqrf2N8KD0erD0scZG7U5xg",
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
|
||||||
|
|
@ -5,8 +5,8 @@ const DiscordTypes = require("discord-api-types/v10")
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
const passthrough = require("../../passthrough")
|
||||||
const {discord, sync, select} = passthrough
|
const {discord, sync, select} = passthrough
|
||||||
/** @type {import("../../matrix/utils")} */
|
/** @type {import("../../m2d/converters/utils")} */
|
||||||
const utils = sync.require("../../matrix/utils")
|
const utils = sync.require("../../m2d/converters/utils")
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef ReactionRemoveRequest
|
* @typedef ReactionRemoveRequest
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@ const assert = require("assert").strict
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
const passthrough = require("../../passthrough")
|
||||||
const {discord, sync, db, select} = passthrough
|
const {discord, sync, db, select} = passthrough
|
||||||
/** @type {import("../../matrix/utils")} */
|
/** @type {import("../../m2d/converters/utils")} */
|
||||||
const mxUtils = sync.require("../../matrix/utils")
|
const mxUtils = sync.require("../../m2d/converters/utils")
|
||||||
const {reg} = require("../../matrix/read-registration.js")
|
const {reg} = require("../../matrix/read-registration.js")
|
||||||
|
|
||||||
const userRegex = reg.namespaces.users.map(u => new RegExp(u.regex))
|
const userRegex = reg.namespaces.users.map(u => new RegExp(u.regex))
|
||||||
|
|
@ -32,10 +32,13 @@ async function threadToAnnouncement(parentRoomID, threadRoomID, creatorMxid, thr
|
||||||
const template = creatorMxid ? "started a thread:" : "Thread started:"
|
const template = creatorMxid ? "started a thread:" : "Thread started:"
|
||||||
const via = await mxUtils.getViaServersQuery(threadRoomID, di.api)
|
const via = await mxUtils.getViaServersQuery(threadRoomID, di.api)
|
||||||
let body = `${template} ${thread.name} https://matrix.to/#/${threadRoomID}?${via.toString()}`
|
let body = `${template} ${thread.name} https://matrix.to/#/${threadRoomID}?${via.toString()}`
|
||||||
|
let html = `${template} <a href="https://matrix.to/#/${threadRoomID}?${via.toString()}">${thread.name}</a>`
|
||||||
|
|
||||||
return {
|
return {
|
||||||
msgtype,
|
msgtype,
|
||||||
body,
|
body,
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: html,
|
||||||
"m.mentions": {},
|
"m.mentions": {},
|
||||||
...context
|
...context
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ const {test} = require("supertape")
|
||||||
const {threadToAnnouncement} = require("./thread-to-announcement")
|
const {threadToAnnouncement} = require("./thread-to-announcement")
|
||||||
const data = require("../../../test/data")
|
const data = require("../../../test/data")
|
||||||
const Ty = require("../../types")
|
const Ty = require("../../types")
|
||||||
const {mockGetEffectivePower} = require("../../matrix/utils.test")
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {string} roomID
|
* @param {string} roomID
|
||||||
|
|
@ -31,7 +30,13 @@ function mockGetEvent(t, roomID_in, eventID_in, outer) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const viaApi = {
|
const viaApi = {
|
||||||
getEffectivePower: mockGetEffectivePower(),
|
async getStateEvent(roomID, type, key) {
|
||||||
|
return {
|
||||||
|
users: {
|
||||||
|
"@_ooye_bot:cadence.moe": 100
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
async getJoinedMembers(roomID) {
|
async getJoinedMembers(roomID) {
|
||||||
return {
|
return {
|
||||||
joined: {
|
joined: {
|
||||||
|
|
@ -50,6 +55,8 @@ test("thread2announcement: no known creator, no branched from event", async t =>
|
||||||
t.deepEqual(content, {
|
t.deepEqual(content, {
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: "Thread started: test thread https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org",
|
body: "Thread started: test thread https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: `Thread started: <a href="https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org">test thread</a>`,
|
||||||
"m.mentions": {}
|
"m.mentions": {}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -62,6 +69,8 @@ test("thread2announcement: known creator, no branched from event", async t => {
|
||||||
t.deepEqual(content, {
|
t.deepEqual(content, {
|
||||||
msgtype: "m.emote",
|
msgtype: "m.emote",
|
||||||
body: "started a thread: test thread https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org",
|
body: "started a thread: test thread https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: `started a thread: <a href="https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org">test thread</a>`,
|
||||||
"m.mentions": {}
|
"m.mentions": {}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -86,6 +95,8 @@ test("thread2announcement: no known creator, branched from discord event", async
|
||||||
t.deepEqual(content, {
|
t.deepEqual(content, {
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: "Thread started: test thread https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org",
|
body: "Thread started: test thread https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: `Thread started: <a href="https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org">test thread</a>`,
|
||||||
"m.mentions": {},
|
"m.mentions": {},
|
||||||
"m.relates_to": {
|
"m.relates_to": {
|
||||||
"m.in_reply_to": {
|
"m.in_reply_to": {
|
||||||
|
|
@ -115,6 +126,8 @@ test("thread2announcement: known creator, branched from discord event", async t
|
||||||
t.deepEqual(content, {
|
t.deepEqual(content, {
|
||||||
msgtype: "m.emote",
|
msgtype: "m.emote",
|
||||||
body: "started a thread: test thread https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org",
|
body: "started a thread: test thread https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: `started a thread: <a href="https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org">test thread</a>`,
|
||||||
"m.mentions": {},
|
"m.mentions": {},
|
||||||
"m.relates_to": {
|
"m.relates_to": {
|
||||||
"m.in_reply_to": {
|
"m.in_reply_to": {
|
||||||
|
|
@ -144,6 +157,8 @@ test("thread2announcement: no known creator, branched from matrix event", async
|
||||||
t.deepEqual(content, {
|
t.deepEqual(content, {
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: "Thread started: test thread https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org",
|
body: "Thread started: test thread https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org",
|
||||||
|
format: "org.matrix.custom.html",
|
||||||
|
formatted_body: `Thread started: <a href="https://matrix.to/#/!thread?via=cadence.moe&via=matrix.org">test thread</a>`,
|
||||||
"m.mentions": {
|
"m.mentions": {
|
||||||
user_ids: ["@cadence:cadence.moe"]
|
user_ids: ["@cadence:cadence.moe"]
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@
|
||||||
|
|
||||||
const assert = require("assert")
|
const assert = require("assert")
|
||||||
const {reg} = require("../../matrix/read-registration")
|
const {reg} = require("../../matrix/read-registration")
|
||||||
const Ty = require("../../types")
|
|
||||||
|
|
||||||
const passthrough = require("../../passthrough")
|
const passthrough = require("../../passthrough")
|
||||||
const {select} = passthrough
|
const {select} = passthrough
|
||||||
|
|
@ -14,16 +13,16 @@ const SPECIAL_USER_MAPPINGS = new Map([
|
||||||
/**
|
/**
|
||||||
* Downcased and stripped username. Can only include a basic set of characters.
|
* Downcased and stripped username. Can only include a basic set of characters.
|
||||||
* https://spec.matrix.org/v1.6/appendices/#user-identifiers
|
* https://spec.matrix.org/v1.6/appendices/#user-identifiers
|
||||||
* @param {import("discord-api-types/v10").APIUser | Ty.WebhookAuthor} user
|
* @param {import("discord-api-types/v10").APIUser} user
|
||||||
* @returns {string} localpart
|
* @returns {string} localpart
|
||||||
*/
|
*/
|
||||||
function downcaseUsername(user) {
|
function downcaseUsername(user) {
|
||||||
// First, try to convert the username to the set of allowed characters
|
// First, try to convert the username to the set of allowed characters
|
||||||
let downcased = user.username.toLowerCase()
|
let downcased = user.username.toLowerCase()
|
||||||
// spaces and slashes to underscores...
|
// spaces to underscores...
|
||||||
.replace(/[ /]/g, "_")
|
.replace(/ /g, "_")
|
||||||
// remove disallowed characters...
|
// remove disallowed characters...
|
||||||
.replace(/[^a-z0-9._=-]*/g, "")
|
.replace(/[^a-z0-9._=/-]*/g, "")
|
||||||
// remove leading and trailing dashes and underscores...
|
// remove leading and trailing dashes and underscores...
|
||||||
.replace(/(?:^[_-]*|[_-]*$)/g, "")
|
.replace(/(?:^[_-]*|[_-]*$)/g, "")
|
||||||
// If requested, also make the Discord user ID part of the username
|
// If requested, also make the Discord user ID part of the username
|
||||||
|
|
@ -61,11 +60,11 @@ function* generateLocalpartAlternatives(preferences) {
|
||||||
*/
|
*/
|
||||||
function userToSimName(user) {
|
function userToSimName(user) {
|
||||||
if (!SPECIAL_USER_MAPPINGS.has(user.id)) { // skip this check for known special users
|
if (!SPECIAL_USER_MAPPINGS.has(user.id)) { // skip this check for known special users
|
||||||
assert.notEqual(user.discriminator, "0000", `cannot create user for a webhook: ${JSON.stringify(user)}`)
|
if (user.discriminator === "0000") return "webhook"
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. Is sim user already registered?
|
// 1. Is sim user already registered?
|
||||||
const existing = select("sim", "user_id", {user_id: user.id}).pluck().get()
|
const existing = select("sim", "sim_name", {user_id: user.id}).pluck().get()
|
||||||
assert.equal(existing, null, "Shouldn't try to create a new name for an existing sim")
|
assert.equal(existing, null, "Shouldn't try to create a new name for an existing sim")
|
||||||
|
|
||||||
// 2. Register based on username (could be new or old format)
|
// 2. Register based on username (could be new or old format)
|
||||||
|
|
@ -86,49 +85,4 @@ function userToSimName(user) {
|
||||||
throw new Error(`Ran out of suggestions when generating sim name. downcased: "${downcased}"`)
|
throw new Error(`Ran out of suggestions when generating sim name. downcased: "${downcased}"`)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Webhooks have an ID specific to that webhook, but a single webhook can send messages with any user name.
|
|
||||||
* The point of this feature (gated by guild_space webhook_profile) is to create persistent Matrix accounts for individual webhook "users".
|
|
||||||
* This is convenient when using a bridge to a platform that does not assign persistent user IDs (e.g. IRC, Minecraft).
|
|
||||||
* In this case, webhook "users" are disambiguated by their username (downcased).
|
|
||||||
* @param {Ty.WebhookAuthor} author
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
function webhookAuthorToFakeUserID(author) {
|
|
||||||
const downcased = downcaseUsername(author)
|
|
||||||
return `webhook_${downcased}`
|
|
||||||
}
|
|
||||||
|
|
||||||
function isWebhookUserID(userID) {
|
|
||||||
return userID.match(/^webhook_[a-z90-9._=/-]+$/)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {Ty.WebhookAuthor} author
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
function webhookAuthorToSimName(author) {
|
|
||||||
assert(!SPECIAL_USER_MAPPINGS.has(author.id), "Special users should have followed the other code path.")
|
|
||||||
|
|
||||||
// 1. Is sim user already registered?
|
|
||||||
const fakeUserID = webhookAuthorToFakeUserID(author)
|
|
||||||
const existing = select("sim", "user_id", {user_id: fakeUserID}).pluck().get()
|
|
||||||
assert.equal(existing, null, "Shouldn't try to create a new name for an existing sim")
|
|
||||||
|
|
||||||
// 2. Register based on username (could be new or old format)
|
|
||||||
const downcased = "webhook_" + downcaseUsername(author)
|
|
||||||
|
|
||||||
// Check for conflicts with already registered sims
|
|
||||||
const matches = select("sim", "sim_name", {}, "WHERE sim_name LIKE ? ESCAPE '@'").pluck().all(downcased + "%")
|
|
||||||
// Keep generating until we get a suggestion that doesn't conflict
|
|
||||||
for (const suggestion of generateLocalpartAlternatives([downcased])) {
|
|
||||||
if (!matches.includes(suggestion)) return suggestion
|
|
||||||
}
|
|
||||||
/* c8 ignore next */
|
|
||||||
throw new Error(`Ran out of suggestions when generating sim name. downcased: "${downcased}"`)
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports.userToSimName = userToSimName
|
module.exports.userToSimName = userToSimName
|
||||||
module.exports.webhookAuthorToFakeUserID = webhookAuthorToFakeUserID
|
|
||||||
module.exports.webhookAuthorToSimName = webhookAuthorToSimName
|
|
||||||
module.exports.isWebhookUserID = isWebhookUserID
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ const {test} = require("supertape")
|
||||||
const tryToCatch = require("try-to-catch")
|
const tryToCatch = require("try-to-catch")
|
||||||
const assert = require("assert")
|
const assert = require("assert")
|
||||||
const data = require("../../../test/data")
|
const data = require("../../../test/data")
|
||||||
const {userToSimName, webhookAuthorToSimName} = require("./user-to-mxid")
|
const {userToSimName} = require("./user-to-mxid")
|
||||||
|
|
||||||
test("user2name: cannot create user for a webhook", async t => {
|
test("user2name: cannot create user for a webhook", async t => {
|
||||||
const [error] = await tryToCatch(() => userToSimName({discriminator: "0000"}))
|
const [error] = await tryToCatch(() => userToSimName({discriminator: "0000"}))
|
||||||
|
|
@ -21,12 +21,8 @@ test("user2name: works on single emoji at the end", t => {
|
||||||
t.equal(userToSimName({username: "Melody 🎵", discriminator: "2192"}), "melody")
|
t.equal(userToSimName({username: "Melody 🎵", discriminator: "2192"}), "melody")
|
||||||
})
|
})
|
||||||
|
|
||||||
test("user2name: works on really weird name", t => {
|
test("user2name: works on crazy name", t => {
|
||||||
t.equal(userToSimName({username: "*** D3 &W (89) _7//-", discriminator: "0001"}), "d3_w_89__7")
|
t.equal(userToSimName({username: "*** D3 &W (89) _7//-", discriminator: "0001"}), "d3_w_89__7//")
|
||||||
})
|
|
||||||
|
|
||||||
test("user2name: treats slashes", t => {
|
|
||||||
t.equal(userToSimName({username: "Evil Lillith (she/her)", discriminator: "5892"}), "evil_lillith_she_her")
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test("user2name: adds discriminator if name is unavailable (old tag format)", t => {
|
test("user2name: adds discriminator if name is unavailable (old tag format)", t => {
|
||||||
|
|
@ -49,17 +45,10 @@ test("user2name: works on special user", t => {
|
||||||
t.equal(userToSimName(data.user.clyde_ai), "clyde_ai")
|
t.equal(userToSimName(data.user.clyde_ai), "clyde_ai")
|
||||||
})
|
})
|
||||||
|
|
||||||
test("webhook author: can generate sim names", t => {
|
|
||||||
t.equal(webhookAuthorToSimName({
|
|
||||||
username: "Cadence, Maid of Creation, Eye of Clarity, Empress of Hope ☆",
|
|
||||||
avatar: null,
|
|
||||||
id: "123"
|
|
||||||
}), "webhook_cadence_maid_of_creation_eye_of_clarity_empress_of_hope")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("user2name: includes ID if requested in config", t => {
|
test("user2name: includes ID if requested in config", t => {
|
||||||
const {reg} = require("../../matrix/read-registration")
|
const {reg} = require("../../matrix/read-registration")
|
||||||
reg.ooye.include_user_id_in_mxid = true
|
reg.ooye.include_user_id_in_mxid = true
|
||||||
t.equal(userToSimName({username: "Harry Styles!", discriminator: "0001", id: "123456"}), "123456_harry_styles")
|
t.equal(userToSimName({username: "Harry Styles!", discriminator: "0001", id: "123456"}), "123456_harry_styles")
|
||||||
t.equal(userToSimName({username: "f***", discriminator: "0001", id: "123456"}), "123456_f")
|
t.equal(userToSimName({username: "f***", discriminator: "0001", id: "123456"}), "123456_f")
|
||||||
|
reg.ooye.include_user_id_in_mxid = false
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,10 @@
|
||||||
// @ts-check
|
// @ts-check
|
||||||
|
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
const { SnowTransfer } = require("snowtransfer")
|
||||||
const {Endpoints, SnowTransfer} = require("snowtransfer")
|
const { Client: CloudStorm } = require("cloudstorm")
|
||||||
const {reg} = require("../matrix/read-registration")
|
|
||||||
const {Client: CloudStorm} = require("cloudstorm")
|
|
||||||
|
|
||||||
// @ts-ignore
|
|
||||||
Endpoints.BASE_HOST = reg.ooye.discord_origin || "https://discord.com"; Endpoints.CDN_URL = reg.ooye.discord_cdn_origin || "https://cdn.discordapp.com"
|
|
||||||
|
|
||||||
const passthrough = require("../passthrough")
|
const passthrough = require("../passthrough")
|
||||||
const {sync} = passthrough
|
const { sync } = passthrough
|
||||||
|
|
||||||
/** @type {import("./discord-packets")} */
|
/** @type {import("./discord-packets")} */
|
||||||
const discordPackets = sync.require("./discord-packets")
|
const discordPackets = sync.require("./discord-packets")
|
||||||
|
|
@ -20,34 +15,32 @@ class DiscordClient {
|
||||||
* @param {string} listen "full", "half", "no" - whether to set up the event listeners for OOYE to operate
|
* @param {string} listen "full", "half", "no" - whether to set up the event listeners for OOYE to operate
|
||||||
*/
|
*/
|
||||||
constructor(discordToken, listen = "full") {
|
constructor(discordToken, listen = "full") {
|
||||||
/** @type {import("cloudstorm").IClientOptions["intents"]} */
|
|
||||||
const intents = [
|
|
||||||
"DIRECT_MESSAGES", "DIRECT_MESSAGE_REACTIONS", "DIRECT_MESSAGE_TYPING",
|
|
||||||
"GUILDS", "GUILD_EMOJIS_AND_STICKERS", "GUILD_MESSAGES", "GUILD_MESSAGE_REACTIONS", "GUILD_MESSAGE_TYPING", "GUILD_WEBHOOKS", "GUILD_MESSAGE_POLLS",
|
|
||||||
"MESSAGE_CONTENT"
|
|
||||||
]
|
|
||||||
if (reg.ooye.receive_presences !== false) intents.push("GUILD_PRESENCES")
|
|
||||||
this.discordToken = discordToken
|
this.discordToken = discordToken
|
||||||
this.snow = new SnowTransfer(discordToken)
|
this.snow = new SnowTransfer(discordToken)
|
||||||
this.cloud = new CloudStorm(discordToken, {
|
this.cloud = new CloudStorm(discordToken, {
|
||||||
shards: [0],
|
shards: [0],
|
||||||
|
reconnect: true,
|
||||||
snowtransferInstance: this.snow,
|
snowtransferInstance: this.snow,
|
||||||
intents,
|
intents: [
|
||||||
|
"DIRECT_MESSAGES", "DIRECT_MESSAGE_REACTIONS", "DIRECT_MESSAGE_TYPING",
|
||||||
|
"GUILDS", "GUILD_EMOJIS_AND_STICKERS", "GUILD_MESSAGES", "GUILD_MESSAGE_REACTIONS", "GUILD_MESSAGE_TYPING", "GUILD_WEBHOOKS",
|
||||||
|
"MESSAGE_CONTENT"
|
||||||
|
],
|
||||||
ws: {
|
ws: {
|
||||||
compress: false,
|
compress: false,
|
||||||
encoding: "json"
|
encoding: "json"
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
this.ready = false
|
this.ready = false
|
||||||
/** @type {DiscordTypes.APIUser} */
|
/** @type {import("discord-api-types/v10").APIUser} */
|
||||||
// @ts-ignore avoid setting as or null because we know we need to wait for ready anyways
|
// @ts-ignore avoid setting as or null because we know we need to wait for ready anyways
|
||||||
this.user = null
|
this.user = null
|
||||||
/** @type {Pick<DiscordTypes.APIApplication, "id" | "flags">} */
|
/** @type {Pick<import("discord-api-types/v10").APIApplication, "id" | "flags">} */
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
this.application = null
|
this.application = null
|
||||||
/** @type {Map<string, DiscordTypes.APIChannel>} */
|
/** @type {Map<string, import("discord-api-types/v10").APIChannel>} */
|
||||||
this.channels = new Map()
|
this.channels = new Map()
|
||||||
/** @type {Map<string, DiscordTypes.APIGuild & {members: DiscordTypes.APIGuildMember[]}>} */ // we get members from the GUILD_CREATE and we do maintain it
|
/** @type {Map<string, import("discord-api-types/v10").APIGuild>} */
|
||||||
this.guilds = new Map()
|
this.guilds = new Map()
|
||||||
/** @type {Map<string, Array<string>>} */
|
/** @type {Map<string, Array<string>>} */
|
||||||
this.guildChannelMap = new Map()
|
this.guildChannelMap = new Map()
|
||||||
|
|
@ -64,6 +57,9 @@ class DiscordClient {
|
||||||
addEventLogger("error", "Error")
|
addEventLogger("error", "Error")
|
||||||
addEventLogger("disconnected", "Disconnected")
|
addEventLogger("disconnected", "Disconnected")
|
||||||
addEventLogger("ready", "Ready")
|
addEventLogger("ready", "Ready")
|
||||||
|
this.snow.requestHandler.on("requestError", (requestID, error) => {
|
||||||
|
console.error("request error:", error)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
|
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
const DiscordTypes = require("discord-api-types/v10")
|
||||||
const passthrough = require("../passthrough")
|
const passthrough = require("../passthrough")
|
||||||
const {sync, db} = passthrough
|
const { sync } = passthrough
|
||||||
|
|
||||||
const utils = {
|
const utils = {
|
||||||
/**
|
/**
|
||||||
|
|
@ -28,7 +28,6 @@ const utils = {
|
||||||
console.log(`Discord logged in as ${client.user.username}#${client.user.discriminator} (${client.user.id})`)
|
console.log(`Discord logged in as ${client.user.username}#${client.user.discriminator} (${client.user.id})`)
|
||||||
|
|
||||||
} else if (message.t === "GUILD_CREATE") {
|
} else if (message.t === "GUILD_CREATE") {
|
||||||
message.d.members = message.d.members.filter(m => m.user.id === client.user.id) // only keep the bot's own member - it's needed to determine private channels on web
|
|
||||||
client.guilds.set(message.d.id, message.d)
|
client.guilds.set(message.d.id, message.d)
|
||||||
const arr = []
|
const arr = []
|
||||||
client.guildChannelMap.set(message.d.id, arr)
|
client.guildChannelMap.set(message.d.id, arr)
|
||||||
|
|
@ -44,17 +43,10 @@ const utils = {
|
||||||
arr.push(thread.id)
|
arr.push(thread.id)
|
||||||
client.channels.set(thread.id, thread)
|
client.channels.set(thread.id, thread)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (listen === "full") {
|
if (listen === "full") {
|
||||||
try {
|
eventDispatcher.checkMissedExpressions(message.d)
|
||||||
interactions.registerInteractions()
|
eventDispatcher.checkMissedPins(client, message.d)
|
||||||
await eventDispatcher.checkMissedExpressions(message.d)
|
eventDispatcher.checkMissedMessages(client, message.d)
|
||||||
await eventDispatcher.checkMissedPins(client, message.d)
|
|
||||||
await eventDispatcher.checkMissedMessages(client, message.d)
|
|
||||||
} catch (e) {
|
|
||||||
console.error("Failed to sync missed events. To retry, please fix this error and restart OOYE:")
|
|
||||||
console.error(e)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (message.t === "GUILD_UPDATE") {
|
} else if (message.t === "GUILD_UPDATE") {
|
||||||
|
|
@ -97,19 +89,9 @@ const utils = {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (message.t === "GUILD_MEMBER_UPDATE") {
|
|
||||||
const guild = client.guilds.get(message.d.guild_id)
|
|
||||||
const member = guild?.members.find(m => m.user.id === message.d.user.id)
|
|
||||||
if (member) { // only update existing members (i.e. the bot's own member) - don't want to inflate the cache with new irrelevant ones
|
|
||||||
Object.assign(member, message.d)
|
|
||||||
}
|
|
||||||
|
|
||||||
} else if (message.t === "THREAD_CREATE") {
|
} else if (message.t === "THREAD_CREATE") {
|
||||||
client.channels.set(message.d.id, message.d)
|
client.channels.set(message.d.id, message.d)
|
||||||
if (message.d["guild_id"]) {
|
|
||||||
const channels = client.guildChannelMap.get(message.d["guild_id"])
|
|
||||||
if (channels && !channels.includes(message.d.id)) channels.push(message.d.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
} else if (message.t === "CHANNEL_UPDATE" || message.t === "THREAD_UPDATE") {
|
} else if (message.t === "CHANNEL_UPDATE" || message.t === "THREAD_UPDATE") {
|
||||||
client.channels.set(message.d.id, message.d)
|
client.channels.set(message.d.id, message.d)
|
||||||
|
|
@ -131,14 +113,14 @@ const utils = {
|
||||||
client.guildChannelMap.delete(message.d.id)
|
client.guildChannelMap.delete(message.d.id)
|
||||||
|
|
||||||
|
|
||||||
} else if (message.t === "CHANNEL_CREATE") {
|
} else if (message.t === "CHANNEL_CREATE" || message.t === "CHANNEL_DELETE") {
|
||||||
|
if (message.t === "CHANNEL_CREATE") {
|
||||||
client.channels.set(message.d.id, message.d)
|
client.channels.set(message.d.id, message.d)
|
||||||
if (message.d["guild_id"]) { // obj[prop] notation can be used to access a property without typescript complaining that it doesn't exist on all values something can have
|
if (message.d["guild_id"]) { // obj[prop] notation can be used to access a property without typescript complaining that it doesn't exist on all values something can have
|
||||||
const channels = client.guildChannelMap.get(message.d["guild_id"])
|
const channels = client.guildChannelMap.get(message.d["guild_id"])
|
||||||
if (channels && !channels.includes(message.d.id)) channels.push(message.d.id)
|
if (channels && !channels.includes(message.d.id)) channels.push(message.d.id)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
} else if (message.t === "CHANNEL_DELETE") {
|
|
||||||
client.channels.delete(message.d.id)
|
client.channels.delete(message.d.id)
|
||||||
if (message.d["guild_id"]) {
|
if (message.d["guild_id"]) {
|
||||||
const channels = client.guildChannelMap.get(message.d["guild_id"])
|
const channels = client.guildChannelMap.get(message.d["guild_id"])
|
||||||
|
|
@ -148,19 +130,58 @@ const utils = {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Event dispatcher for OOYE bridge operations
|
// Event dispatcher for OOYE bridge operations
|
||||||
if (listen === "full" && message.t) {
|
if (listen === "full") {
|
||||||
try {
|
try {
|
||||||
if (message.t === "MESSAGE_REACTION_REMOVE" || message.t === "MESSAGE_REACTION_REMOVE_EMOJI" || message.t === "MESSAGE_REACTION_REMOVE_ALL") {
|
if (message.t === "GUILD_UPDATE") {
|
||||||
|
await eventDispatcher.onGuildUpdate(client, message.d)
|
||||||
|
|
||||||
|
} else if (message.t === "GUILD_EMOJIS_UPDATE" || message.t === "GUILD_STICKERS_UPDATE") {
|
||||||
|
await eventDispatcher.onExpressionsUpdate(client, message.d)
|
||||||
|
|
||||||
|
} else if (message.t === "CHANNEL_UPDATE") {
|
||||||
|
await eventDispatcher.onChannelOrThreadUpdate(client, message.d, false)
|
||||||
|
|
||||||
|
} else if (message.t === "CHANNEL_PINS_UPDATE") {
|
||||||
|
await eventDispatcher.onChannelPinsUpdate(client, message.d)
|
||||||
|
|
||||||
|
} else if (message.t === "CHANNEL_DELETE") {
|
||||||
|
await eventDispatcher.onChannelDelete(client, message.d)
|
||||||
|
|
||||||
|
} else if (message.t === "THREAD_CREATE") {
|
||||||
|
// @ts-ignore
|
||||||
|
await eventDispatcher.onThreadCreate(client, message.d)
|
||||||
|
|
||||||
|
} else if (message.t === "THREAD_UPDATE") {
|
||||||
|
await eventDispatcher.onChannelOrThreadUpdate(client, message.d, true)
|
||||||
|
|
||||||
|
} else if (message.t === "MESSAGE_CREATE") {
|
||||||
|
await eventDispatcher.onMessageCreate(client, message.d)
|
||||||
|
|
||||||
|
} else if (message.t === "MESSAGE_UPDATE") {
|
||||||
|
await eventDispatcher.onMessageUpdate(client, message.d)
|
||||||
|
|
||||||
|
} else if (message.t === "MESSAGE_DELETE") {
|
||||||
|
await eventDispatcher.onMessageDelete(client, message.d)
|
||||||
|
|
||||||
|
} else if (message.t === "MESSAGE_DELETE_BULK") {
|
||||||
|
await eventDispatcher.onMessageDeleteBulk(client, message.d)
|
||||||
|
|
||||||
|
} else if (message.t === "TYPING_START") {
|
||||||
|
await eventDispatcher.onTypingStart(client, message.d)
|
||||||
|
|
||||||
|
} else if (message.t === "MESSAGE_REACTION_ADD") {
|
||||||
|
await eventDispatcher.onReactionAdd(client, message.d)
|
||||||
|
|
||||||
|
} else if (message.t === "MESSAGE_REACTION_REMOVE" || message.t === "MESSAGE_REACTION_REMOVE_EMOJI" || message.t === "MESSAGE_REACTION_REMOVE_ALL") {
|
||||||
await eventDispatcher.onSomeReactionsRemoved(client, message.d)
|
await eventDispatcher.onSomeReactionsRemoved(client, message.d)
|
||||||
|
|
||||||
} else if (message.t === "INTERACTION_CREATE") {
|
} else if (message.t === "INTERACTION_CREATE") {
|
||||||
await interactions.dispatchInteraction(message.d)
|
await interactions.dispatchInteraction(message.d)
|
||||||
|
|
||||||
} else if (message.t in eventDispatcher) {
|
|
||||||
await eventDispatcher[message.t](client, message.d)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// Let OOYE try to handle errors too
|
// Let OOYE try to handle errors too
|
||||||
await eventDispatcher.onError(client, e, message)
|
await eventDispatcher.onError(client, e, message)
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
const assert = require("assert").strict
|
const assert = require("assert").strict
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
const DiscordTypes = require("discord-api-types/v10")
|
||||||
|
const util = require("util")
|
||||||
const {sync, db, select, from} = require("../passthrough")
|
const {sync, db, select, from} = require("../passthrough")
|
||||||
|
|
||||||
/** @type {import("./actions/send-message")}) */
|
/** @type {import("./actions/send-message")}) */
|
||||||
|
|
@ -26,22 +27,19 @@ const updatePins = sync.require("./actions/update-pins")
|
||||||
const api = sync.require("../matrix/api")
|
const api = sync.require("../matrix/api")
|
||||||
/** @type {import("../discord/utils")} */
|
/** @type {import("../discord/utils")} */
|
||||||
const dUtils = sync.require("../discord/utils")
|
const dUtils = sync.require("../discord/utils")
|
||||||
|
/** @type {import("../m2d/converters/utils")} */
|
||||||
|
const mxUtils = require("../m2d/converters/utils")
|
||||||
/** @type {import("./actions/speedbump")} */
|
/** @type {import("./actions/speedbump")} */
|
||||||
const speedbump = sync.require("./actions/speedbump")
|
const speedbump = sync.require("./actions/speedbump")
|
||||||
/** @type {import("./actions/retrigger")} */
|
/** @type {import("./actions/retrigger")} */
|
||||||
const retrigger = sync.require("./actions/retrigger")
|
const retrigger = sync.require("./actions/retrigger")
|
||||||
/** @type {import("./actions/set-presence")} */
|
|
||||||
const setPresence = sync.require("./actions/set-presence")
|
|
||||||
/** @type {import("./actions/poll-vote")} */
|
|
||||||
const vote = sync.require("./actions/poll-vote")
|
|
||||||
/** @type {import("../m2d/event-dispatcher")} */
|
|
||||||
const matrixEventDispatcher = sync.require("../m2d/event-dispatcher")
|
|
||||||
/** @type {import("../discord/interactions/matrix-info")} */
|
|
||||||
const matrixInfoInteraction = sync.require("../discord/interactions/matrix-info")
|
|
||||||
|
|
||||||
const {Semaphore} = require("@chriscdn/promise-semaphore")
|
/** @type {any} */ // @ts-ignore bad types from semaphore
|
||||||
|
const Semaphore = require("@chriscdn/promise-semaphore")
|
||||||
const checkMissedPinsSema = new Semaphore()
|
const checkMissedPinsSema = new Semaphore()
|
||||||
|
|
||||||
|
let lastReportedEvent = 0
|
||||||
|
|
||||||
// Grab Discord events we care about for the bridge, check them, and pass them on
|
// Grab Discord events we care about for the bridge, check them, and pass them on
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|
@ -51,16 +49,48 @@ module.exports = {
|
||||||
* @param {import("cloudstorm").IGatewayMessage} gatewayMessage
|
* @param {import("cloudstorm").IGatewayMessage} gatewayMessage
|
||||||
*/
|
*/
|
||||||
async onError(client, e, gatewayMessage) {
|
async onError(client, e, gatewayMessage) {
|
||||||
|
console.error("hit event-dispatcher's error handler with this exception:")
|
||||||
|
console.error(e) // TODO: also log errors into a file or into the database, maybe use a library for this? or just wing it? definitely need to be able to store the formatted event body to load back in later
|
||||||
|
console.error(`while handling this ${gatewayMessage.t} gateway event:`)
|
||||||
|
console.dir(gatewayMessage.d, {depth: null})
|
||||||
|
|
||||||
if (gatewayMessage.t === "TYPING_START") return
|
if (gatewayMessage.t === "TYPING_START") return
|
||||||
|
|
||||||
matrixEventDispatcher.printError(gatewayMessage.t, "Discord", e, gatewayMessage)
|
if (Date.now() - lastReportedEvent < 5000) return
|
||||||
|
lastReportedEvent = Date.now()
|
||||||
|
|
||||||
const channelID = gatewayMessage.d["channel_id"]
|
const channelID = gatewayMessage.d["channel_id"]
|
||||||
if (!channelID) return
|
if (!channelID) return
|
||||||
const roomID = select("channel_room", "room_id", {channel_id: channelID}).pluck().get()
|
const roomID = select("channel_room", "room_id", {channel_id: channelID}).pluck().get()
|
||||||
if (!roomID) return
|
if (!roomID) return
|
||||||
|
|
||||||
await matrixEventDispatcher.sendError(roomID, "Discord", gatewayMessage.t, e, gatewayMessage)
|
let stackLines = null
|
||||||
|
if (e.stack) {
|
||||||
|
stackLines = e.stack.split("\n")
|
||||||
|
let cloudstormLine = stackLines.findIndex(l => l.includes("/node_modules/cloudstorm/"))
|
||||||
|
if (cloudstormLine !== -1) {
|
||||||
|
stackLines = stackLines.slice(0, cloudstormLine - 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const builder = new mxUtils.MatrixStringBuilder()
|
||||||
|
builder.addLine("\u26a0 Bridged event from Discord not delivered", "\u26a0 <strong>Bridged event from Discord not delivered</strong>")
|
||||||
|
builder.addLine(`Gateway event: ${gatewayMessage.t}`)
|
||||||
|
builder.addLine(e.toString())
|
||||||
|
if (stackLines) {
|
||||||
|
builder.addLine(`Error trace:\n${stackLines.join("\n")}`, `<details><summary>Error trace</summary><pre>${stackLines.join("\n")}</pre></details>`)
|
||||||
|
}
|
||||||
|
builder.addLine("", `<details><summary>Original payload</summary><pre>${util.inspect(gatewayMessage.d, false, 4, false)}</pre></details>`)
|
||||||
|
await api.sendEvent(roomID, "m.room.message", {
|
||||||
|
...builder.get(),
|
||||||
|
"moe.cadence.ooye.error": {
|
||||||
|
source: "discord",
|
||||||
|
payload: gatewayMessage
|
||||||
|
},
|
||||||
|
"m.mentions": {
|
||||||
|
user_ids: ["@cadence:cadence.moe"]
|
||||||
|
}
|
||||||
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -73,27 +103,18 @@ module.exports = {
|
||||||
async checkMissedMessages(client, guild) {
|
async checkMissedMessages(client, guild) {
|
||||||
if (guild.unavailable) return
|
if (guild.unavailable) return
|
||||||
const bridgedChannels = select("channel_room", "channel_id").pluck().all()
|
const bridgedChannels = select("channel_room", "channel_id").pluck().all()
|
||||||
const preparedExists = from("message_room").join("historical_channel_room", "historical_room_index").pluck("message_id").and("WHERE reference_channel_id = ? LIMIT 1").prepare()
|
const prepared = select("event_message", "event_id", {}, "WHERE message_id = ?").pluck()
|
||||||
const preparedGet = select("event_message", "event_id", {}, "WHERE message_id = ?").pluck()
|
for (const channel of guild.channels.concat(guild.threads)) {
|
||||||
/** @type {(DiscordTypes.APIChannel & {type: DiscordTypes.GuildChannelType})[]} */
|
|
||||||
let channels = []
|
|
||||||
channels = channels.concat(guild.channels, guild.threads)
|
|
||||||
for (const channel of channels) {
|
|
||||||
if (!bridgedChannels.includes(channel.id)) continue
|
if (!bridgedChannels.includes(channel.id)) continue
|
||||||
if (!("last_message_id" in channel) || !channel.last_message_id) continue
|
if (!("last_message_id" in channel) || !channel.last_message_id) continue
|
||||||
|
const latestWasBridged = prepared.get(channel.last_message_id)
|
||||||
// Skip if channel is already up-to-date
|
|
||||||
const latestWasBridged = preparedGet.get(channel.last_message_id)
|
|
||||||
if (latestWasBridged) continue
|
if (latestWasBridged) continue
|
||||||
|
|
||||||
// Skip if channel was just added to the bridge (there's no place to resume from if it's brand new)
|
|
||||||
if (!preparedExists.get(channel.id)) continue
|
|
||||||
|
|
||||||
// Permissions check
|
// Permissions check
|
||||||
const member = guild.members.find(m => m.user?.id === client.user.id)
|
const member = guild.members.find(m => m.user?.id === client.user.id)
|
||||||
if (!member) return
|
if (!member) return
|
||||||
if (!("permission_overwrites" in channel)) continue
|
if (!("permission_overwrites" in channel)) continue
|
||||||
const permissions = dUtils.getPermissions(guild.id, member.roles, guild.roles, client.user.id, channel.permission_overwrites)
|
const permissions = dUtils.getPermissions(member.roles, guild.roles, client.user.id, channel.permission_overwrites)
|
||||||
if (!dUtils.hasAllPermissions(permissions, ["ViewChannel", "ReadMessageHistory"])) continue // We don't have permission to look back in this channel
|
if (!dUtils.hasAllPermissions(permissions, ["ViewChannel", "ReadMessageHistory"])) continue // We don't have permission to look back in this channel
|
||||||
|
|
||||||
/** More recent messages come first. */
|
/** More recent messages come first. */
|
||||||
|
|
@ -110,28 +131,17 @@ module.exports = {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let latestBridgedMessageIndex = messages.findIndex(m => {
|
let latestBridgedMessageIndex = messages.findIndex(m => {
|
||||||
return preparedGet.get(m.id)
|
return prepared.get(m.id)
|
||||||
})
|
})
|
||||||
// console.log(`[check missed messages] got ${messages.length} messages; last message that IS bridged is at position ${latestBridgedMessageIndex} in the channel`)
|
// console.log(`[check missed messages] got ${messages.length} messages; last message that IS bridged is at position ${latestBridgedMessageIndex} in the channel`)
|
||||||
if (latestBridgedMessageIndex === -1) latestBridgedMessageIndex = 1 // rather than crawling the ENTIRE channel history, let's just bridge the most recent 1 message to make it up to date.
|
if (latestBridgedMessageIndex === -1) latestBridgedMessageIndex = 1 // rather than crawling the ENTIRE channel history, let's just bridge the most recent 1 message to make it up to date.
|
||||||
|
|
||||||
// We get member data so that we can accurately update any changes to nickname or permissions that have occurred in the meantime
|
|
||||||
// The rate limit is lax enough that the backlog will still be pretty quick (at time of writing, 5 per 1 second per guild)
|
|
||||||
/** @type {Map<string, DiscordTypes.APIGuildMember | undefined>} id -> member: cache members for the run because people talk to each other */
|
|
||||||
const members = new Map()
|
|
||||||
|
|
||||||
// Send in order
|
|
||||||
for (let i = Math.min(messages.length, latestBridgedMessageIndex)-1; i >= 0; i--) {
|
for (let i = Math.min(messages.length, latestBridgedMessageIndex)-1; i >= 0; i--) {
|
||||||
const message = messages[i]
|
const simulatedGatewayDispatchData = {
|
||||||
|
|
||||||
if (!members.has(message.author.id)) members.set(message.author.id, await client.snow.guild.getGuildMember(guild.id, message.author.id).catch(() => undefined))
|
|
||||||
await module.exports.MESSAGE_CREATE(client, {
|
|
||||||
guild_id: guild.id,
|
guild_id: guild.id,
|
||||||
member: members.get(message.author.id),
|
|
||||||
// @ts-ignore
|
|
||||||
backfill: true,
|
backfill: true,
|
||||||
...message
|
...messages[i]
|
||||||
})
|
}
|
||||||
|
await module.exports.onMessageCreate(client, simulatedGatewayDispatchData)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
@ -152,7 +162,7 @@ module.exports = {
|
||||||
const lastPin = updatePins.convertTimestamp(channel.last_pin_timestamp)
|
const lastPin = updatePins.convertTimestamp(channel.last_pin_timestamp)
|
||||||
|
|
||||||
// Permissions check
|
// Permissions check
|
||||||
const permissions = dUtils.getPermissions(guild.id, member.roles, guild.roles, client.user.id, channel.permission_overwrites)
|
const permissions = dUtils.getPermissions(member.roles, guild.roles, client.user.id, channel.permission_overwrites)
|
||||||
if (!dUtils.hasAllPermissions(permissions, ["ViewChannel", "ReadMessageHistory"])) continue // We don't have permission to look up the pins in this channel
|
if (!dUtils.hasAllPermissions(permissions, ["ViewChannel", "ReadMessageHistory"])) continue // We don't have permission to look up the pins in this channel
|
||||||
|
|
||||||
const row = select("channel_room", ["room_id", "last_bridged_pin_timestamp"], {channel_id: channel.id}).get()
|
const row = select("channel_room", ["room_id", "last_bridged_pin_timestamp"], {channel_id: channel.id}).get()
|
||||||
|
|
@ -169,7 +179,7 @@ module.exports = {
|
||||||
*/
|
*/
|
||||||
async checkMissedExpressions(guild) {
|
async checkMissedExpressions(guild) {
|
||||||
const data = {guild_id: guild.id, ...guild}
|
const data = {guild_id: guild.id, ...guild}
|
||||||
await createSpace.syncSpaceExpressions(data, true)
|
createSpace.syncSpaceExpressions(data, true)
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -178,10 +188,10 @@ module.exports = {
|
||||||
* @param {import("./discord-client")} client
|
* @param {import("./discord-client")} client
|
||||||
* @param {DiscordTypes.APIThreadChannel} thread
|
* @param {DiscordTypes.APIThreadChannel} thread
|
||||||
*/
|
*/
|
||||||
async THREAD_CREATE(client, thread) {
|
async onThreadCreate(client, thread) {
|
||||||
const channelID = thread.parent_id || undefined
|
const channelID = thread.parent_id || undefined
|
||||||
const parentRoomID = select("channel_room", "room_id", {channel_id: channelID}).pluck().get()
|
const parentRoomID = select("channel_room", "room_id", {channel_id: channelID}).pluck().get()
|
||||||
if (!parentRoomID) return // Not interested in a thread if we aren't interested in its wider channel (won't autocreate)
|
if (!parentRoomID) return // Not interested in a thread if we aren't interested in its wider channel
|
||||||
const threadRoomID = await createRoom.syncRoom(thread.id) // Create room (will share the same inflight as the initial message to the thread)
|
const threadRoomID = await createRoom.syncRoom(thread.id) // Create room (will share the same inflight as the initial message to the thread)
|
||||||
await announceThread.announceThread(parentRoomID, threadRoomID, thread)
|
await announceThread.announceThread(parentRoomID, threadRoomID, thread)
|
||||||
},
|
},
|
||||||
|
|
@ -190,50 +200,28 @@ module.exports = {
|
||||||
* @param {import("./discord-client")} client
|
* @param {import("./discord-client")} client
|
||||||
* @param {DiscordTypes.GatewayGuildUpdateDispatchData} guild
|
* @param {DiscordTypes.GatewayGuildUpdateDispatchData} guild
|
||||||
*/
|
*/
|
||||||
async GUILD_UPDATE(client, guild) {
|
async onGuildUpdate(client, guild) {
|
||||||
const spaceID = select("guild_space", "space_id", {guild_id: guild.id}).pluck().get()
|
const spaceID = select("guild_space", "space_id", {guild_id: guild.id}).pluck().get()
|
||||||
if (!spaceID) return
|
if (!spaceID) return
|
||||||
await createSpace.syncSpace(guild)
|
await createSpace.syncSpace(guild)
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {import("./discord-client")} client
|
|
||||||
* @param {DiscordTypes.GatewayGuildRoleUpdateDispatchData} data
|
|
||||||
*/
|
|
||||||
async GUILD_ROLE_UPDATE(client, data) {
|
|
||||||
const guild = client.guilds.get(data.guild_id)
|
|
||||||
if (!guild) return
|
|
||||||
const spaceID = select("guild_space", "space_id", {guild_id: data.guild_id}).pluck().get()
|
|
||||||
if (!spaceID) return
|
|
||||||
|
|
||||||
if (data.role.id === data.guild_id) { // @everyone role changed - find a way to do this more efficiently in the future to handle many role updates
|
|
||||||
await createSpace.syncSpaceFully(guild)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {import("./discord-client")} client
|
* @param {import("./discord-client")} client
|
||||||
* @param {DiscordTypes.GatewayChannelUpdateDispatchData} channelOrThread
|
* @param {DiscordTypes.GatewayChannelUpdateDispatchData} channelOrThread
|
||||||
|
* @param {boolean} isThread
|
||||||
*/
|
*/
|
||||||
async CHANNEL_UPDATE(client, channelOrThread) {
|
async onChannelOrThreadUpdate(client, channelOrThread, isThread) {
|
||||||
const roomID = select("channel_room", "room_id", {channel_id: channelOrThread.id}).pluck().get()
|
const roomID = select("channel_room", "room_id", {channel_id: channelOrThread.id}).pluck().get()
|
||||||
if (!roomID) return // No target room to update the data on
|
if (!roomID) return // No target room to update the data on
|
||||||
await createRoom.syncRoom(channelOrThread.id)
|
await createRoom.syncRoom(channelOrThread.id)
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {import("./discord-client")} client
|
|
||||||
* @param {DiscordTypes.GatewayChannelUpdateDispatchData} thread
|
|
||||||
*/
|
|
||||||
async THREAD_UPDATE(client, thread) {
|
|
||||||
await module.exports.CHANNEL_UPDATE(client, thread)
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {import("./discord-client")} client
|
* @param {import("./discord-client")} client
|
||||||
* @param {DiscordTypes.GatewayChannelPinsUpdateDispatchData} data
|
* @param {DiscordTypes.GatewayChannelPinsUpdateDispatchData} data
|
||||||
*/
|
*/
|
||||||
async CHANNEL_PINS_UPDATE(client, data) {
|
async onChannelPinsUpdate(client, data) {
|
||||||
const roomID = select("channel_room", "room_id", {channel_id: data.channel_id}).pluck().get()
|
const roomID = select("channel_room", "room_id", {channel_id: data.channel_id}).pluck().get()
|
||||||
if (!roomID) return // No target room to update pins in
|
if (!roomID) return // No target room to update pins in
|
||||||
const convertedTimestamp = updatePins.convertTimestamp(data.last_pin_timestamp)
|
const convertedTimestamp = updatePins.convertTimestamp(data.last_pin_timestamp)
|
||||||
|
|
@ -244,24 +232,23 @@ module.exports = {
|
||||||
* @param {import("./discord-client")} client
|
* @param {import("./discord-client")} client
|
||||||
* @param {DiscordTypes.GatewayChannelDeleteDispatchData} channel
|
* @param {DiscordTypes.GatewayChannelDeleteDispatchData} channel
|
||||||
*/
|
*/
|
||||||
async CHANNEL_DELETE(client, channel) {
|
async onChannelDelete(client, channel) {
|
||||||
const guildID = channel["guild_id"]
|
const guildID = channel["guild_id"]
|
||||||
if (!guildID) return // channel must have been a DM channel or something
|
if (!guildID) return // channel must have been a DM channel or something
|
||||||
const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get()
|
const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get()
|
||||||
if (!roomID) return // channel wasn't being bridged in the first place
|
if (!roomID) return // channel wasn't being bridged in the first place
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
await createRoom.unbridgeChannel(channel, guildID)
|
await createRoom.unbridgeDeletedChannel(channel, guildID)
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {import("./discord-client")} client
|
* @param {import("./discord-client")} client
|
||||||
* @param {DiscordTypes.GatewayMessageCreateDispatchData} message
|
* @param {DiscordTypes.GatewayMessageCreateDispatchData} message
|
||||||
*/
|
*/
|
||||||
async MESSAGE_CREATE(client, message) {
|
async onMessageCreate(client, message) {
|
||||||
if (message.author.username === "Deleted User") return // Nothing we can do for deleted users.
|
if (message.author.username === "Deleted User") return // Nothing we can do for deleted users.
|
||||||
const channel = client.channels.get(message.channel_id)
|
const channel = client.channels.get(message.channel_id)
|
||||||
if (!channel || !("guild_id" in channel) || !channel.guild_id) return // Nothing we can do in direct messages.
|
if (!channel || !("guild_id" in channel) || !channel.guild_id) return // Nothing we can do in direct messages.
|
||||||
|
|
||||||
const guild = client.guilds.get(channel.guild_id)
|
const guild = client.guilds.get(channel.guild_id)
|
||||||
assert(guild)
|
assert(guild)
|
||||||
|
|
||||||
|
|
@ -272,13 +259,11 @@ module.exports = {
|
||||||
|
|
||||||
if (dUtils.isEphemeralMessage(message)) return // Ephemeral messages are for the eyes of the receiver only!
|
if (dUtils.isEphemeralMessage(message)) return // Ephemeral messages are for the eyes of the receiver only!
|
||||||
|
|
||||||
if (!createRoom.existsOrAutocreatable(channel, guild.id)) return // Check that the sending-to room exists or is autocreatable
|
|
||||||
|
|
||||||
const {affected, row} = await speedbump.maybeDoSpeedbump(message.channel_id, message.id)
|
const {affected, row} = await speedbump.maybeDoSpeedbump(message.channel_id, message.id)
|
||||||
if (affected) return
|
if (affected) return
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
await sendMessage.sendMessage(message, channel, guild, row)
|
await sendMessage.sendMessage(message, channel, guild, row),
|
||||||
|
|
||||||
retrigger.messageFinishedBridging(message.id)
|
retrigger.messageFinishedBridging(message.id)
|
||||||
},
|
},
|
||||||
|
|
@ -287,11 +272,19 @@ module.exports = {
|
||||||
* @param {import("./discord-client")} client
|
* @param {import("./discord-client")} client
|
||||||
* @param {DiscordTypes.GatewayMessageUpdateDispatchData} data
|
* @param {DiscordTypes.GatewayMessageUpdateDispatchData} data
|
||||||
*/
|
*/
|
||||||
async MESSAGE_UPDATE(client, data) {
|
async 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.
|
// 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 the message content is a string then it includes all interesting fields and is meaningful.
|
||||||
// Otherwise, if there are embeds, then the system generated URL preview embeds.
|
// Otherwise, if there are embeds, then the system generated URL preview embeds.
|
||||||
if (!(typeof data.content === "string" || "embeds" in data || "components" in data)) return
|
if (!(typeof data.content === "string" || "embeds" in data)) return
|
||||||
|
|
||||||
|
// Deal with Eventual Consistency(TM)
|
||||||
|
if (retrigger.eventNotFoundThenRetrigger(data.id, module.exports.onMessageUpdate, client, data)) return
|
||||||
|
|
||||||
|
if (data.webhook_id) {
|
||||||
|
const row = select("webhook", "webhook_id", {webhook_id: data.webhook_id}).pluck().get()
|
||||||
|
if (row) return // The message was sent by the bridge's own webhook on discord. We don't want to reflect this back, so just drop it.
|
||||||
|
}
|
||||||
|
|
||||||
if (dUtils.isEphemeralMessage(data)) return // Ephemeral messages are for the eyes of the receiver only!
|
if (dUtils.isEphemeralMessage(data)) return // Ephemeral messages are for the eyes of the receiver only!
|
||||||
|
|
||||||
|
|
@ -299,39 +292,25 @@ module.exports = {
|
||||||
const {affected, row} = await speedbump.maybeDoSpeedbump(data.channel_id, data.id)
|
const {affected, row} = await speedbump.maybeDoSpeedbump(data.channel_id, data.id)
|
||||||
if (affected) return
|
if (affected) return
|
||||||
|
|
||||||
if (!row) {
|
|
||||||
// Check that the sending-to room exists, and deal with Eventual Consistency(TM)
|
|
||||||
if (retrigger.eventNotFoundThenRetrigger(data.id, module.exports.MESSAGE_UPDATE, client, data)) return
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @type {DiscordTypes.GatewayMessageCreateDispatchData} */
|
/** @type {DiscordTypes.GatewayMessageCreateDispatchData} */
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const message = data
|
const message = data
|
||||||
|
|
||||||
const channel = client.channels.get(message.channel_id)
|
const channel = client.channels.get(message.channel_id)
|
||||||
if (!channel || !("guild_id" in channel) || !channel.guild_id) return // Nothing we can do in direct messages.
|
if (!channel || !("guild_id" in channel) || !channel.guild_id) return // Nothing we can do in direct messages.
|
||||||
const guild = client.guilds.get(channel.guild_id)
|
const guild = client.guilds.get(channel.guild_id)
|
||||||
assert(guild)
|
assert(guild)
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
await retrigger.pauseChanges(message.id, editMessage.editMessage(message, guild, row))
|
await editMessage.editMessage(message, guild, row)
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {import("./discord-client")} client
|
* @param {import("./discord-client")} client
|
||||||
* @param {DiscordTypes.GatewayMessageReactionAddDispatchData} data
|
* @param {DiscordTypes.GatewayMessageReactionAddDispatchData} data
|
||||||
*/
|
*/
|
||||||
async MESSAGE_REACTION_ADD(client, data) {
|
async onReactionAdd(client, data) {
|
||||||
if (data.user_id === client.user.id) return // m2d reactions are added by the discord bot user - do not reflect them back to matrix.
|
if (data.user_id === client.user.id) return // m2d reactions are added by the discord bot user - do not reflect them back to matrix.
|
||||||
if (data.emoji.name === "❓" && select("event_message", "message_id", {message_id: data.message_id, source: 0, part: 0}).get()) { // source 0 = matrix
|
|
||||||
const guild_id = data.guild_id ?? client.channels.get(data.channel_id)?.["guild_id"]
|
|
||||||
await Promise.all([
|
|
||||||
client.snow.channel.deleteReaction(data.channel_id, data.message_id, data.emoji.name).catch(() => {}),
|
|
||||||
// @ts-ignore - this is all you need for it to do a matrix-side lookup
|
|
||||||
matrixInfoInteraction.dm({guild_id, data: {target_id: data.message_id}, member: {user: {id: data.user_id}}})
|
|
||||||
])
|
|
||||||
} else {
|
|
||||||
await addReaction.addReaction(data)
|
await addReaction.addReaction(data)
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -346,9 +325,9 @@ module.exports = {
|
||||||
* @param {import("./discord-client")} client
|
* @param {import("./discord-client")} client
|
||||||
* @param {DiscordTypes.GatewayMessageDeleteDispatchData} data
|
* @param {DiscordTypes.GatewayMessageDeleteDispatchData} data
|
||||||
*/
|
*/
|
||||||
async MESSAGE_DELETE(client, data) {
|
async onMessageDelete(client, data) {
|
||||||
speedbump.onMessageDelete(data.id)
|
speedbump.onMessageDelete(data.id)
|
||||||
if (retrigger.eventNotFoundThenRetrigger(data.id, module.exports.MESSAGE_DELETE, client, data)) return
|
if (retrigger.eventNotFoundThenRetrigger(data.id, module.exports.onMessageDelete, client, data)) return
|
||||||
await deleteMessage.deleteMessage(data)
|
await deleteMessage.deleteMessage(data)
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
@ -356,7 +335,7 @@ module.exports = {
|
||||||
* @param {import("./discord-client")} client
|
* @param {import("./discord-client")} client
|
||||||
* @param {DiscordTypes.GatewayMessageDeleteBulkDispatchData} data
|
* @param {DiscordTypes.GatewayMessageDeleteBulkDispatchData} data
|
||||||
*/
|
*/
|
||||||
async MESSAGE_DELETE_BULK(client, data) {
|
async onMessageDeleteBulk(client, data) {
|
||||||
await deleteMessage.deleteMessageBulk(data)
|
await deleteMessage.deleteMessageBulk(data)
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
@ -364,7 +343,7 @@ module.exports = {
|
||||||
* @param {import("./discord-client")} client
|
* @param {import("./discord-client")} client
|
||||||
* @param {DiscordTypes.GatewayTypingStartDispatchData} data
|
* @param {DiscordTypes.GatewayTypingStartDispatchData} data
|
||||||
*/
|
*/
|
||||||
async TYPING_START(client, data) {
|
async onTypingStart(client, data) {
|
||||||
const roomID = select("channel_room", "room_id", {channel_id: data.channel_id}).pluck().get()
|
const roomID = select("channel_room", "room_id", {channel_id: data.channel_id}).pluck().get()
|
||||||
if (!roomID) return
|
if (!roomID) return
|
||||||
const mxid = from("sim").join("sim_member", "mxid").where({user_id: data.user_id, room_id: roomID}).pluck("mxid").get()
|
const mxid = from("sim").join("sim_member", "mxid").where({user_id: data.user_id, room_id: roomID}).pluck("mxid").get()
|
||||||
|
|
@ -377,41 +356,9 @@ module.exports = {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {import("./discord-client")} client
|
* @param {import("./discord-client")} client
|
||||||
* @param {DiscordTypes.GatewayGuildEmojisUpdateDispatchData} data
|
* @param {DiscordTypes.GatewayGuildEmojisUpdateDispatchData | DiscordTypes.GatewayGuildStickersUpdateDispatchData} data
|
||||||
*/
|
*/
|
||||||
async GUILD_EMOJIS_UPDATE(client, data) {
|
async onExpressionsUpdate(client, data) {
|
||||||
await createSpace.syncSpaceExpressions(data, false)
|
await createSpace.syncSpaceExpressions(data, false)
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {import("./discord-client")} client
|
|
||||||
* @param {DiscordTypes.GatewayGuildStickersUpdateDispatchData} data
|
|
||||||
*/
|
|
||||||
async GUILD_STICKERS_UPDATE(client, data) {
|
|
||||||
await createSpace.syncSpaceExpressions(data, false)
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {import("./discord-client")} client
|
|
||||||
* @param {DiscordTypes.GatewayMessagePollVoteDispatchData} data
|
|
||||||
*/
|
|
||||||
async MESSAGE_POLL_VOTE_ADD(client, data) {
|
|
||||||
if (retrigger.eventNotFoundThenRetrigger(data.message_id, module.exports.MESSAGE_POLL_VOTE_ADD, client, data)) return
|
|
||||||
await vote.addVote(data)
|
|
||||||
},
|
|
||||||
|
|
||||||
async MESSAGE_POLL_VOTE_REMOVE(client, data) {
|
|
||||||
if (retrigger.eventNotFoundThenRetrigger(data.message_id, module.exports.MESSAGE_POLL_VOTE_REMOVE, client, data)) return
|
|
||||||
await vote.removeVote(data)
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {import("./discord-client")} client
|
|
||||||
* @param {DiscordTypes.GatewayPresenceUpdateDispatchData} data
|
|
||||||
*/
|
|
||||||
PRESENCE_UPDATE(client, data) {
|
|
||||||
const status = data.status
|
|
||||||
if (!status) return
|
|
||||||
setPresence.presenceTracker.incomingPresence(data.user.id, data.guild_id, status)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,7 @@ const {join} = require("path")
|
||||||
async function migrate(db) {
|
async function migrate(db) {
|
||||||
let files = fs.readdirSync(join(__dirname, "migrations"))
|
let files = fs.readdirSync(join(__dirname, "migrations"))
|
||||||
files = files.sort()
|
files = files.sort()
|
||||||
db.prepare("CREATE TABLE IF NOT EXISTS migration (filename TEXT NOT NULL, PRIMARY KEY (filename)) WITHOUT ROWID").run()
|
db.prepare("CREATE TABLE IF NOT EXISTS migration (filename TEXT NOT NULL)").run()
|
||||||
/** @type {string} */
|
|
||||||
let progress = db.prepare("SELECT * FROM migration").pluck().get()
|
let progress = db.prepare("SELECT * FROM migration").pluck().get()
|
||||||
if (!progress) {
|
if (!progress) {
|
||||||
progress = ""
|
progress = ""
|
||||||
|
|
@ -38,8 +37,6 @@ async function migrate(db) {
|
||||||
if (migrationRan) {
|
if (migrationRan) {
|
||||||
console.log("Database migrations all done.")
|
console.log("Database migrations all done.")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.pragma("foreign_keys = on")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.migrate = migrate
|
module.exports.migrate = migrate
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ module.exports = async function(db) {
|
||||||
const contents = db.prepare("SELECT distinct hashed_profile_content FROM sim_member WHERE hashed_profile_content IS NOT NULL").pluck().all()
|
const contents = db.prepare("SELECT distinct hashed_profile_content FROM sim_member WHERE hashed_profile_content IS NOT NULL").pluck().all()
|
||||||
const stmt = db.prepare("UPDATE sim_member SET hashed_profile_content = ? WHERE hashed_profile_content = ?")
|
const stmt = db.prepare("UPDATE sim_member SET hashed_profile_content = ? WHERE hashed_profile_content = ?")
|
||||||
db.transaction(() => {
|
db.transaction(() => {
|
||||||
/* c8 ignore next 6 */
|
|
||||||
for (let s of contents) {
|
for (let s of contents) {
|
||||||
let b = Buffer.isBuffer(s) ? Uint8Array.from(s) : Uint8Array.from(Buffer.from(s))
|
let b = Buffer.isBuffer(s) ? Uint8Array.from(s) : Uint8Array.from(Buffer.from(s))
|
||||||
const unsignedHash = hasher.h64Raw(b)
|
const unsignedHash = hasher.h64Raw(b)
|
||||||
|
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
ALTER TABLE channel_room ADD COLUMN guild_id TEXT;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,147 +0,0 @@
|
||||||
-- /docs/foreign-keys.md
|
|
||||||
|
|
||||||
-- 2
|
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
-- *** channel_room ***
|
|
||||||
|
|
||||||
-- 4
|
|
||||||
-- adding UNIQUE to room_id here will auto-generate the usable index we wanted
|
|
||||||
CREATE TABLE "new_channel_room" (
|
|
||||||
"channel_id" TEXT NOT NULL,
|
|
||||||
"room_id" TEXT NOT NULL UNIQUE,
|
|
||||||
"name" TEXT NOT NULL,
|
|
||||||
"nick" TEXT,
|
|
||||||
"thread_parent" TEXT,
|
|
||||||
"custom_avatar" TEXT,
|
|
||||||
"last_bridged_pin_timestamp" INTEGER,
|
|
||||||
"speedbump_id" TEXT,
|
|
||||||
"speedbump_checked" INTEGER,
|
|
||||||
"speedbump_webhook_id" TEXT,
|
|
||||||
"guild_id" TEXT,
|
|
||||||
PRIMARY KEY("channel_id"),
|
|
||||||
FOREIGN KEY("guild_id") REFERENCES "guild_active"("guild_id") ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
-- 5
|
|
||||||
INSERT INTO new_channel_room (channel_id, room_id, name, nick, thread_parent, custom_avatar, last_bridged_pin_timestamp, speedbump_id, speedbump_checked, speedbump_webhook_id, guild_id) SELECT channel_id, room_id, name, nick, thread_parent, custom_avatar, last_bridged_pin_timestamp, speedbump_id, speedbump_checked, speedbump_webhook_id, guild_id FROM channel_room;
|
|
||||||
-- 6
|
|
||||||
DROP TABLE channel_room;
|
|
||||||
-- 7
|
|
||||||
ALTER TABLE new_channel_room RENAME TO channel_room;
|
|
||||||
|
|
||||||
-- *** message_channel ***
|
|
||||||
|
|
||||||
-- 4
|
|
||||||
CREATE TABLE "new_message_channel" (
|
|
||||||
"message_id" TEXT NOT NULL,
|
|
||||||
"channel_id" TEXT NOT NULL,
|
|
||||||
PRIMARY KEY("message_id"),
|
|
||||||
FOREIGN KEY("channel_id") REFERENCES "channel_room"("channel_id") ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
-- 5
|
|
||||||
-- don't copy any orphaned messages
|
|
||||||
INSERT INTO new_message_channel (message_id, channel_id) SELECT message_id, channel_id FROM message_channel WHERE channel_id IN (SELECT channel_id FROM channel_room);
|
|
||||||
-- 6
|
|
||||||
DROP TABLE message_channel;
|
|
||||||
-- 7
|
|
||||||
ALTER TABLE new_message_channel RENAME TO message_channel;
|
|
||||||
|
|
||||||
-- *** event_message ***
|
|
||||||
|
|
||||||
-- clean up any orphaned events
|
|
||||||
DELETE FROM event_message WHERE message_id NOT IN (SELECT message_id FROM message_channel);
|
|
||||||
-- 4
|
|
||||||
CREATE TABLE "new_event_message" (
|
|
||||||
"event_id" TEXT NOT NULL,
|
|
||||||
"event_type" TEXT,
|
|
||||||
"event_subtype" TEXT,
|
|
||||||
"message_id" TEXT NOT NULL,
|
|
||||||
"part" INTEGER NOT NULL,
|
|
||||||
"reaction_part" INTEGER NOT NULL,
|
|
||||||
"source" INTEGER NOT NULL,
|
|
||||||
PRIMARY KEY("message_id","event_id"),
|
|
||||||
FOREIGN KEY("message_id") REFERENCES "message_channel"("message_id") ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
-- 5
|
|
||||||
INSERT INTO new_event_message (event_id, event_type, event_subtype, message_id, part, reaction_part, source) SELECT event_id, event_type, event_subtype, message_id, part, reaction_part, source FROM event_message;
|
|
||||||
-- 6
|
|
||||||
DROP TABLE event_message;
|
|
||||||
-- 7
|
|
||||||
ALTER TABLE new_event_message RENAME TO event_message;
|
|
||||||
|
|
||||||
-- *** guild_space ***
|
|
||||||
|
|
||||||
-- 4
|
|
||||||
CREATE TABLE "new_guild_space" (
|
|
||||||
"guild_id" TEXT NOT NULL,
|
|
||||||
"space_id" TEXT NOT NULL,
|
|
||||||
"privacy_level" INTEGER NOT NULL DEFAULT 0,
|
|
||||||
PRIMARY KEY("guild_id"),
|
|
||||||
FOREIGN KEY("guild_id") REFERENCES "guild_active"("guild_id") ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
-- 5
|
|
||||||
INSERT INTO new_guild_space (guild_id, space_id, privacy_level) SELECT guild_id, space_id, privacy_level FROM guild_space;
|
|
||||||
-- 6
|
|
||||||
DROP TABLE guild_space;
|
|
||||||
-- 7
|
|
||||||
ALTER TABLE new_guild_space RENAME TO guild_space;
|
|
||||||
|
|
||||||
-- *** reaction ***
|
|
||||||
|
|
||||||
-- 4
|
|
||||||
CREATE TABLE "new_reaction" (
|
|
||||||
"hashed_event_id" INTEGER NOT NULL,
|
|
||||||
"message_id" TEXT NOT NULL,
|
|
||||||
"encoded_emoji" TEXT NOT NULL,
|
|
||||||
PRIMARY KEY("hashed_event_id"),
|
|
||||||
FOREIGN KEY("message_id") REFERENCES "message_channel"("message_id") ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
-- 5
|
|
||||||
INSERT INTO new_reaction (hashed_event_id, message_id, encoded_emoji) SELECT hashed_event_id, message_id, encoded_emoji FROM reaction WHERE message_id IN (SELECT message_id FROM message_channel);
|
|
||||||
-- 6
|
|
||||||
DROP TABLE reaction;
|
|
||||||
-- 7
|
|
||||||
ALTER TABLE new_reaction RENAME TO reaction;
|
|
||||||
|
|
||||||
-- *** webhook ***
|
|
||||||
|
|
||||||
-- 4
|
|
||||||
-- using RESTRICT instead of CASCADE as a reminder that the webhooks also need to be deleted using the Discord API, it can't just be entirely automatic
|
|
||||||
CREATE TABLE "new_webhook" (
|
|
||||||
"channel_id" TEXT NOT NULL,
|
|
||||||
"webhook_id" TEXT NOT NULL,
|
|
||||||
"webhook_token" TEXT NOT NULL,
|
|
||||||
PRIMARY KEY("channel_id"),
|
|
||||||
FOREIGN KEY("channel_id") REFERENCES "channel_room"("channel_id") ON DELETE RESTRICT
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
-- 5
|
|
||||||
INSERT INTO new_webhook (channel_id, webhook_id, webhook_token) SELECT channel_id, webhook_id, webhook_token FROM webhook WHERE channel_id IN (SELECT channel_id FROM channel_room);
|
|
||||||
-- 6
|
|
||||||
DROP TABLE webhook;
|
|
||||||
-- 7
|
|
||||||
ALTER TABLE new_webhook RENAME TO webhook;
|
|
||||||
|
|
||||||
-- *** sim ***
|
|
||||||
|
|
||||||
-- 4
|
|
||||||
-- while we're at it, rebuild this table to give it WITHOUT ROWID, remove UNIQUE, and replace the localpart column with username. no foreign keys needed
|
|
||||||
CREATE TABLE "new_sim" (
|
|
||||||
"user_id" TEXT NOT NULL,
|
|
||||||
"username" TEXT NOT NULL,
|
|
||||||
"sim_name" TEXT NOT NULL,
|
|
||||||
"mxid" TEXT NOT NULL,
|
|
||||||
PRIMARY KEY("user_id")
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
-- 5
|
|
||||||
INSERT INTO new_sim (user_id, username, sim_name, mxid) SELECT user_id, sim_name, sim_name, mxid FROM sim;
|
|
||||||
-- 6
|
|
||||||
DROP TABLE sim;
|
|
||||||
-- 7
|
|
||||||
ALTER TABLE new_sim RENAME TO sim;
|
|
||||||
|
|
||||||
-- *** end ***
|
|
||||||
|
|
||||||
-- 10
|
|
||||||
PRAGMA foreign_key_check;
|
|
||||||
-- 11
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
ALTER TABLE channel_room ADD COLUMN custom_topic INTEGER DEFAULT 0;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
CREATE TABLE "invite" (
|
|
||||||
"mxid" TEXT NOT NULL,
|
|
||||||
"room_id" TEXT NOT NULL,
|
|
||||||
"type" TEXT,
|
|
||||||
"name" TEXT,
|
|
||||||
"topic" TEXT,
|
|
||||||
"avatar" TEXT,
|
|
||||||
PRIMARY KEY("mxid","room_id")
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
ALTER TABLE guild_space ADD COLUMN presence INTEGER NOT NULL DEFAULT 1;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
ALTER TABLE guild_space ADD COLUMN url_preview INTEGER NOT NULL DEFAULT 1;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
DROP TABLE auto_emoji;
|
|
||||||
|
|
||||||
CREATE TABLE auto_emoji (
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
emoji_id TEXT NOT NULL,
|
|
||||||
PRIMARY KEY (name)
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
ALTER TABLE reaction ADD COLUMN original_encoding TEXT;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
CREATE TABLE direct (
|
|
||||||
mxid TEXT NOT NULL,
|
|
||||||
room_id TEXT NOT NULL,
|
|
||||||
PRIMARY KEY (mxid)
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
ALTER TABLE guild_space ADD COLUMN webhook_profile INTEGER NOT NULL DEFAULT 0;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,63 +0,0 @@
|
||||||
PRAGMA foreign_keys=OFF;
|
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
-- *** historical_channel_room ***
|
|
||||||
|
|
||||||
CREATE TABLE "historical_channel_room" (
|
|
||||||
"historical_room_index" INTEGER NOT NULL,
|
|
||||||
"reference_channel_id" TEXT NOT NULL,
|
|
||||||
"room_id" TEXT NOT NULL UNIQUE,
|
|
||||||
"upgraded_timestamp" INTEGER NOT NULL,
|
|
||||||
PRIMARY KEY("historical_room_index" AUTOINCREMENT),
|
|
||||||
FOREIGN KEY("reference_channel_id") REFERENCES "channel_room"("channel_id") ON DELETE CASCADE
|
|
||||||
);
|
|
||||||
|
|
||||||
INSERT INTO historical_channel_room (reference_channel_id, room_id, upgraded_timestamp) SELECT channel_id, room_id, 0 FROM channel_room;
|
|
||||||
|
|
||||||
-- *** message_channel -> message_room ***
|
|
||||||
|
|
||||||
CREATE TABLE "message_room" (
|
|
||||||
"message_id" TEXT NOT NULL,
|
|
||||||
"historical_room_index" INTEGER NOT NULL,
|
|
||||||
PRIMARY KEY("message_id"),
|
|
||||||
FOREIGN KEY("historical_room_index") REFERENCES "historical_channel_room"("historical_room_index") ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
INSERT INTO message_room (message_id, historical_room_index) SELECT message_id, max(historical_room_index) as historical_room_index FROM message_channel INNER JOIN historical_channel_room ON historical_channel_room.reference_channel_id = message_channel.channel_id GROUP BY message_id;
|
|
||||||
|
|
||||||
-- *** event_message ***
|
|
||||||
|
|
||||||
CREATE TABLE "new_event_message" (
|
|
||||||
"event_id" TEXT NOT NULL,
|
|
||||||
"event_type" TEXT,
|
|
||||||
"event_subtype" TEXT,
|
|
||||||
"message_id" TEXT NOT NULL,
|
|
||||||
"part" INTEGER NOT NULL,
|
|
||||||
"reaction_part" INTEGER NOT NULL,
|
|
||||||
"source" INTEGER NOT NULL,
|
|
||||||
PRIMARY KEY("message_id","event_id"),
|
|
||||||
FOREIGN KEY("message_id") REFERENCES "message_room"("message_id") ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
INSERT INTO new_event_message (event_id, event_type, event_subtype, message_id, part, reaction_part, source) SELECT event_id, event_type, event_subtype, message_id, part, reaction_part, source from event_message;
|
|
||||||
DROP TABLE event_message;
|
|
||||||
ALTER TABLE new_event_message RENAME TO event_message;
|
|
||||||
|
|
||||||
-- *** reaction ***
|
|
||||||
|
|
||||||
CREATE TABLE "new_reaction" (
|
|
||||||
"hashed_event_id" INTEGER NOT NULL,
|
|
||||||
"message_id" TEXT NOT NULL,
|
|
||||||
"encoded_emoji" TEXT NOT NULL, original_encoding TEXT,
|
|
||||||
PRIMARY KEY("hashed_event_id"),
|
|
||||||
FOREIGN KEY("message_id") REFERENCES "message_room"("message_id") ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
INSERT INTO new_reaction (hashed_event_id, message_id, encoded_emoji) SELECT hashed_event_id, message_id, encoded_emoji FROM reaction;
|
|
||||||
DROP TABLE reaction;
|
|
||||||
ALTER TABLE new_reaction RENAME TO reaction;
|
|
||||||
|
|
||||||
-- ***
|
|
||||||
|
|
||||||
DROP TABLE message_channel;
|
|
||||||
PRAGMA foreign_key_check;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
PRAGMA foreign_keys=ON;
|
|
||||||
|
|
@ -1,250 +0,0 @@
|
||||||
-- https://www.sqlite.org/lang_analyze.html
|
|
||||||
|
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
ANALYZE sqlite_schema;
|
|
||||||
|
|
||||||
DELETE FROM "sqlite_stat1";
|
|
||||||
INSERT INTO "sqlite_stat1" ("tbl","idx","stat") VALUES ('reaction','reaction','4741 1'),
|
|
||||||
('event_message','event_message','537386 1 1'),
|
|
||||||
('message_room','message_room','510262 1'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','991 1'),
|
|
||||||
('auto_emoji','auto_emoji','2 1'),
|
|
||||||
('sim','sim','1075 1'),
|
|
||||||
('webhook','webhook','205 1'),
|
|
||||||
('channel_room','channel_room','992 1'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','992 1'),
|
|
||||||
('guild_active','guild_active','45 1'),
|
|
||||||
('media_proxy','media_proxy','19794 1'),
|
|
||||||
('sim_member','sim_member','5504 6 1'),
|
|
||||||
('emoji','emoji','3472 1'),
|
|
||||||
('guild_space','guild_space','43 1'),
|
|
||||||
('member_power','member_power','1 1 1'),
|
|
||||||
('sim_proxy','sim_proxy','213 1'),
|
|
||||||
('migration',NULL,'1'),
|
|
||||||
('member_cache','member_cache','1117 3 1'),
|
|
||||||
('file','file','36489 1'),
|
|
||||||
('lottie','lottie','22 1');
|
|
||||||
|
|
||||||
DELETE FROM "sqlite_stat4";
|
|
||||||
INSERT INTO "sqlite_stat4" ("tbl","idx","neq","nlt","ndlt","sample") VALUES ('reaction','reaction','1','526','526',X'02069c21bd28f26ae025'),
|
|
||||||
('reaction','reaction','1','1053','1053',X'0206b8866f4c30c2e1aa'),
|
|
||||||
('reaction','reaction','1','1580','1580',X'0206d43fceca129b040e'),
|
|
||||||
('reaction','reaction','1','2107','2107',X'0206f121f9a4fe54b557'),
|
|
||||||
('reaction','reaction','1','2634','2634',X'020610299199abbd0e9c'),
|
|
||||||
('reaction','reaction','1','3161','3161',X'02062be99961e7716037'),
|
|
||||||
('reaction','reaction','1','3688','3688',X'020647b48fa5ee5a415c'),
|
|
||||||
('reaction','reaction','1','4215','4215',X'020664fdc2d88c77dda3'),
|
|
||||||
('event_message','event_message','11 1','14790 14792','14356 14792',X'03336531313532303033373639343137303839303434244a616d4c6d732d4b77454c6b47766866344d524f385576535536336a574a5a4c4474524c4c57664f775873'),
|
|
||||||
('event_message','event_message','11 1','33809 33816','32914 33816',X'0333653131353736303336383730353738363637363224544b7141734f58566c6e67506f546f4a427565514e664444756d494a6d38384f486a76766f7949496e7130'),
|
|
||||||
('event_message','event_message','1 1','59709 59709','57896 59709',X'033365313136363930353332323132303637353336392442794756564f6767326a416845624267463941755056486178377a34314459514e4459316e34435a4a4455'),
|
|
||||||
('event_message','event_message','11 1','116172 116182','111525 116182',X'0333653131393336383733373036313733323736353624786a385f70696e784f624f4349666c70556832305542345973664a547642694b4164675f473168562d5334'),
|
|
||||||
('event_message','event_message','1 1','119419 119419','114559 119419',X'03336531313935323132333038393839383730313732244f556670664d5054576c364774734943484d725459556d6464656c636232663374494a662d425769554355'),
|
|
||||||
('event_message','event_message','16 1','140286 140287','134379 140287',X'0333653132303933373536353437313834383034323524346b61796e4d68422d336d6967417571347255745f726639353454636b6f657636664c5f3675394f455030'),
|
|
||||||
('event_message','event_message','11 1','162080 162086','154932 162086',X'0333653132323434383135393033313937373537373424674c77513179796e4b6d5859496b5a597a4a55627a66557a55552d714c4b5f524f454e4250325f6e44766b'),
|
|
||||||
('event_message','event_message','11 1','178659 178659','170672 178659',X'03336531323333353238303533323338333337353537242d39304668552d36455373594b6435484d7237666d6a414a5f6a576149616e356c4776384e655436564959'),
|
|
||||||
('event_message','event_message','1 1','179129 179129','171083 179129',X'03336531323333393533373032373637383836343636245a446e5f42385a6b41674c645939495649767445516e47373369706a555a55447943634768697851673859'),
|
|
||||||
('event_message','event_message','10 1','180049 180052','171954 180052',X'03336531323334363237303030393333383130323637245171504b7357795254734a49695449744646716a686e506d48764a6e5932584a6c595a506b424e372d766f'),
|
|
||||||
('event_message','event_message','11 1','215266 215271','205302 215271',X'03336531323533373435373636373337313231333632244b4936672d57724f5a5757533463534c4c4f353950555176425066754b5f5446504b443233583130504759'),
|
|
||||||
('event_message','event_message','11 1','224498 224499','213831 224499',X'0333653132353932393835383232333036303137353824356a573361764d37626d643661756c7367635650506f5257417552476e30503477324939786b5675326f6b'),
|
|
||||||
('event_message','event_message','10 1','224519 224523','213833 224523',X'033365313235393239383739353234323635353839352452696c715a6862347a32526b594c596958504375445975546f6b6430544e365a784638737842745670346b'),
|
|
||||||
('event_message','event_message','10 1','224615 224616','213843 224616',X'0333653132353933303036363636373831383139323024425a69396d4c73323034344c674a6e56673761557a614467484b4b5545787334587a467954474245585573'),
|
|
||||||
('event_message','event_message','1 1','238839 238839','227061 238839',X'0333653132363839343934383836303535393336343224374d3633546d416c526947553847795f416164576f4d4f4e4a334b363441326235385f6e72385961652d51'),
|
|
||||||
('event_message','event_message','1 1','298549 298549','283096 298549',X'03336531333037303536353132313931303337343532245830424a3954514e544d3041687554736c7258744b5836383376723749524355747a4b47524a4374493555'),
|
|
||||||
('event_message','event_message','11 1','304605 304605','288785 304605',X'03336531333131353731333337393331363537323737242d674e75657465765a426169587949335859717437325743695438396549573269514761416266384f6455'),
|
|
||||||
('event_message','event_message','11 1','327028 327037','309699 327037',X'0333653133323736353831313733343439323336383024715055786a61394c36694e756548683046335962304b524b67665730414356394769367a4147464b714973'),
|
|
||||||
('event_message','event_message','10 1','329549 329550','312055 329550',X'033365313332393331373735303931323435303537322430325a4779526f33656133786e5356706b52487047325459415464373971684834536632506f4e7a614773'),
|
|
||||||
('event_message','event_message','1 1','358259 358259','339179 358259',X'03336531333436303136333531313138313634303539243364757343667558596a506f715a3642774851755a48496e5163504f4e70766c64387476654a4d45685a38'),
|
|
||||||
('event_message','event_message','1 1','417969 417969','395237 417969',X'0333653133363831333832343230383333393336363724537a7775656948304b696130376d67304e51322d58627751352d6a7653507649464e645053396464416655'),
|
|
||||||
('event_message','event_message','11 1','422263 422270','399248 422270',X'033365313336393833343930353236313034373831382456754f5872464d593547734350377467425f6a763348486f426264666b3859464c4b4f6e48583732497677'),
|
|
||||||
('event_message','event_message','10 1','424260 424266','401135 424266',X'03336531333730353132353138353938303939303637246c7268447950715458362d45497a3637552d616a75453839614655394c4151556f5a356d7363725072466f'),
|
|
||||||
('event_message','event_message','1 1','477679 477679','451062 477679',X'0333653134303434353430323035313234383133333324524f454b6b5f726b3373344b7451337a75344552774c4b5069484964757676575f514d4b4e66306c385630'),
|
|
||||||
('message_room','message_room','1','56695','56695',X'023331313636313031373337333834343630333739'),
|
|
||||||
('message_room','message_room','1','113391','113391',X'023331313932353935303036363435363132353434'),
|
|
||||||
('message_room','message_room','1','170087','170087',X'023331323331393439393133373937393535363335'),
|
|
||||||
('message_room','message_room','1','226783','226783',X'023331323636313430343634333733383239373532'),
|
|
||||||
('message_room','message_room','1','283479','283479',X'023331333034303933383132373833373130323539'),
|
|
||||||
('message_room','message_room','1','340175','340175',X'023331333434383431363637333537393730343332'),
|
|
||||||
('message_room','message_room','1','396871','396871',X'023331333637353035313132313333363638393134'),
|
|
||||||
('message_room','message_room','1','453567','453567',X'023331343032363934353234333439373134343833'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','0 0','0 0',X'034b0221414355774c616c64303030303030303030303a636164656e63652e6d6f650288'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','24 24','24 24',X'034b02214255635a694c7a57303030303030303030303a636164656e63652e6d6f6501ab'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','110 110','110 110',X'034b022147486e4d47697875303030303030303030303a636164656e63652e6d6f6500c6'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','193 193','193 193',X'034b02214b4b535575717666303030303030303030303a636164656e63652e6d6f650350'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','221 221','221 221',X'034b02214c51715351594b73303030303030303030303a636164656e63652e6d6f6503af'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','319 319','319 319',X'034b02215170676c734e587a303030303030303030303a636164656e63652e6d6f650366'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','332 332','332 332',X'034b0221525a585a7064554f303030303030303030303a636164656e63652e6d6f65009f'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','351 351','351 351',X'034b0221534b6f6c6f636b77303030303030303030303a636164656e63652e6d6f65035f'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','443 443','443 443',X'034b0221576374435a494d73303030303030303030303a636164656e63652e6d6f650084'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','551 551','551 551',X'034b0221637779454c6c6b55303030303030303030303a636164656e63652e6d6f6501b0'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','554 554','554 554',X'034b0221644965496d615167303030303030303030303a636164656e63652e6d6f6503a0'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','560 560','560 560',X'034b0221645568456f756a71303030303030303030303a636164656e63652e6d6f650090'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','573 573','573 573',X'034b02216552517465644b67303030303030303030303a636164656e63652e6d6f650099'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','593 593','593 593',X'034b0221666764594e526d4e303030303030303030303a636164656e63652e6d6f65016b'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','624 624','624 624',X'034b0221687078416c4c6f71303030303030303030303a636164656e63652e6d6f650297'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','625 625','625 625',X'034b02216873414570464e47303030303030303030303a636164656e63652e6d6f6500be'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','665 665','665 665',X'034b01216a71484b51424476303030303030303030303a636164656e63652e6d6f653b'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','758 758','758 758',X'034b02216f6251554d424b75303030303030303030303a636164656e63652e6d6f6500f7'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','776 776','776 776',X'034b022170566e596b5a4f46303030303030303030303a636164656e63652e6d6f650232'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','781 781','781 781',X'034b01217065766e6542516e303030303030303030303a636164656e63652e6d6f6518'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','857 857','857 857',X'034b02217446564c65724b78303030303030303030303a636164656e63652e6d6f65024e'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','866 866','866 866',X'034b0221745a61474145557a303030303030303030303a636164656e63652e6d6f6501f8'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','887 887','887 887',X'034b022175727a464b754d61303030303030303030303a636164656e63652e6d6f65033b'),
|
|
||||||
('historical_channel_room','sqlite_autoindex_historical_channel_room_1','1 1','921 921','921 921',X'034b022177574a5548445a74303030303030303030303a636164656e63652e6d6f65025c'),
|
|
||||||
('auto_emoji','auto_emoji','1','0','0',X'02114c31'),
|
|
||||||
('auto_emoji','auto_emoji','1','1','1',X'02114c32'),
|
|
||||||
('sim','sim','1','119','119',X'025531316564343731342d636635652d346333372d393331382d376136353266383732636634'),
|
|
||||||
('sim','sim','1','239','239',X'0231313439363932303632313634333230323536'),
|
|
||||||
('sim','sim','1','359','359',X'025532323533323035312d633335332d346638662d383835362d653137383831323435303763'),
|
|
||||||
('sim','sim','1','479','479',X'0231333036373839323436333237353836383136'),
|
|
||||||
('sim','sim','1','599','599',X'0231343132383438323830343635313738363235'),
|
|
||||||
('sim','sim','1','719','719',X'0231353638323430303837363238373735343234'),
|
|
||||||
('sim','sim','1','839','839',X'0231373234383037393132373233313835373534'),
|
|
||||||
('sim','sim','1','959','959',X'0231393431303333313033353936353835303630'),
|
|
||||||
('webhook','webhook','1','22','22',X'023331313630383933333337303239353836393536'),
|
|
||||||
('webhook','webhook','1','45','45',X'023331323139343938393236343636363632343330'),
|
|
||||||
('webhook','webhook','1','68','68',X'023331323432383939363632343734373131303630'),
|
|
||||||
('webhook','webhook','1','91','91',X'023331323937323836383730393534323833313533'),
|
|
||||||
('webhook','webhook','1','114','114',X'023331333430353438363133363931393332373133'),
|
|
||||||
('webhook','webhook','1','137','137',X'023331343034313334383236303530383436393331'),
|
|
||||||
('webhook','webhook','1','160','160',X'0231333639373535303430343638303431373238'),
|
|
||||||
('webhook','webhook','1','183','183',X'0231363035353930343336333230333738383930'),
|
|
||||||
('channel_room','channel_room','1','110','110',X'023331313939353030313137393834363733393133'),
|
|
||||||
('channel_room','channel_room','1','221','221',X'023331323734313935333432323131393430353434'),
|
|
||||||
('channel_room','channel_room','1','332','332',X'023331333437303036333637393639343433383430'),
|
|
||||||
('channel_room','channel_room','1','443','443',X'023331343035323432323838343138303632333636'),
|
|
||||||
('channel_room','channel_room','1','554','554',X'023331343036373736363630393936333935323830'),
|
|
||||||
('channel_room','channel_room','1','665','665',X'023331343039363536363537383835323635393830'),
|
|
||||||
('channel_room','channel_room','1','776','776',X'023331343139353132333134363234383638343632'),
|
|
||||||
('channel_room','channel_room','1','887','887',X'0231333734383732393736313738343133353639'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','23 23','23 23',X'034b3121425167434a4d4c78303030303030303030303a636164656e63652e6d6f65393631373335333036303032393732373432'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','96 96','96 96',X'034b332146514f654f667747303030303030303030303a636164656e63652e6d6f6531323137393638383531303939313839323738'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','110 110','110 110',X'034b332147486e4d47697875303030303030303030303a636164656e63652e6d6f6531323432323436333730303938363739383838'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','138 138','138 138',X'034b3321484a79705a6b6863303030303030303030303a636164656e63652e6d6f6531303237323933303239313633333335373130'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','161 161','161 161',X'034b33214962646466626172303030303030303030303a636164656e63652e6d6f6531323937373538303931373331303039353536'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','221 221','221 221',X'034b31214c51715351594b73303030303030303030303a636164656e63652e6d6f65373039303431393733353332363838343235'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','240 240','240 240',X'034b33214d5071594e414a62303030303030303030303a636164656e63652e6d6f6531323139303338323638323835323539393037'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','250 250','250 250',X'034b33214e414f484c4e444c303030303030303030303a636164656e63652e6d6f6531343037323332343832313338333934363634'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','325 325','325 325',X'034b33215178576669464359303030303030303030303a636164656e63652e6d6f6531343034353739343736363837323934363434'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','332 332','332 332',X'034b33215254735654767542303030303030303030303a636164656e63652e6d6f6531343037323235393932313935333432343237'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','430 430','430 430',X'034b33215673656a6b6b5a71303030303030303030303a636164656e63652e6d6f6531323235323636343030363838333431303833'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','443 443','443 443',X'034b3321576241744a736c6b303030303030303030303a636164656e63652e6d6f6531343230323635333433363931313332393339'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','552 552','552 552',X'034b3321637779454c6c6b55303030303030303030303a636164656e63652e6d6f6531343034393538363332363830303939393931'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','554 554','554 554',X'034b332164484e5378484a47303030303030303030303a636164656e63652e6d6f6531343035363439333331343335393939323932'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','565 565','565 565',X'034b3321646c584f50766944303030303030303030303a636164656e63652e6d6f6531323735353037363433323231343039393033'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','579 579','579 579',X'034b332165656c6c7a6a5370303030303030303030303a636164656e63652e6d6f6531343036373736363630393936333935323830'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','619 619','619 619',X'034b332168525179596e6d4e303030303030303030303a636164656e63652e6d6f6531343237323832333338303035353136343233'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','664 664','664 664',X'034b33216a6c566e54585747303030303030303030303a636164656e63652e6d6f6531323139353034373636333137373536343238'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','665 665','665 665',X'034b33216a6c6c4479666d76303030303030303030303a636164656e63652e6d6f6531303835303935353736383731333837313936'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','776 776','776 776',X'034b332170555653686b7978303030303030303030303a636164656e63652e6d6f6531323139343939353736363137303738383735'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','813 813','813 813',X'034b33217179416246555961303030303030303030303a636164656e63652e6d6f6531343035393130313436363731393732333833'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','887 887','887 887',X'034b33217571697357484575303030303030303030303a636164656e63652e6d6f6531323331383036353337373032353736313938'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','924 924','924 924',X'034b332177585242634d4851303030303030303030303a636164656e63652e6d6f6531343233373338343430363833363232353332'),
|
|
||||||
('channel_room','sqlite_autoindex_channel_room_1','1 1','953 953','953 953',X'034b33217954757a6749556f303030303030303030303a636164656e63652e6d6f6531333338353537373531373232323530333130'),
|
|
||||||
('guild_active','guild_active','1','5','5',X'023331313433333336323438373631363437313534'),
|
|
||||||
('guild_active','guild_active','1','11','11',X'023331313630383933333336333234393331353834'),
|
|
||||||
('guild_active','guild_active','1','17','17',X'023331323839353936343835343631323137333430'),
|
|
||||||
('guild_active','guild_active','1','23','23',X'023331333338363530383035363233393834333030'),
|
|
||||||
('guild_active','guild_active','1','29','29',X'023331343338363132393630393137353836313233'),
|
|
||||||
('guild_active','guild_active','1','35','35',X'0231343937313539373236343535343535373534'),
|
|
||||||
('guild_active','guild_active','1','41','41',X'0231383730313138363530373638363730373530'),
|
|
||||||
('media_proxy','media_proxy','1','2199','2199',X'02069cb7709d83b92e22'),
|
|
||||||
('media_proxy','media_proxy','1','4399','4399',X'0206b953cc685f0b68d2'),
|
|
||||||
('media_proxy','media_proxy','1','6599','6599',X'0206d546a2d00310b6cc'),
|
|
||||||
('media_proxy','media_proxy','1','8799','8799',X'0206f0d029ff71e1dae5'),
|
|
||||||
('media_proxy','media_proxy','1','10999','10999',X'02060e4626697605710f'),
|
|
||||||
('media_proxy','media_proxy','1','13199','13199',X'02062adc53c43825bc39'),
|
|
||||||
('media_proxy','media_proxy','1','15399','15399',X'02064704c4b0f76fa5ff'),
|
|
||||||
('media_proxy','media_proxy','1','17599','17599',X'02066338ce2423770613'),
|
|
||||||
('sim_member','sim_member','225 1','14 80','4 80',X'034b4721414956694e775a64303030303030303030303a636164656e63652e6d6f65405f6f6f79655f66726f73745f313139323a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','32 1','483 488','68 488',X'034b3b21455450534d664d69303030303030303030303a636164656e63652e6d6f65405f6f6f79655f653372613a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','125 1','598 611','85 611',X'034b4921457a54624a496c49303030303030303030303a636164656e63652e6d6f65405f6f6f79655f61726a756e3034323236393a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','35 1','818 851','107 851',X'034b472147486e4d47697875303030303030303030303a636164656e63652e6d6f65405f6f6f79655f76616e746164656c69613a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','63 1','945 1005','141 1005',X'034b412148725979716b6f79303030303030303030303a636164656e63652e6d6f65405f6f6f79655f7669686f776c733a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','48 1','1024 1025','149 1025',X'034b47214943566475566c64303030303030303030303a636164656e63652e6d6f65405f6f6f79655f5f706b5f6172656866723a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','39 1','1205 1223','175 1223',X'034b41214a48614a71425870303030303030303030303a636164656e63652e6d6f65405f6f6f79655f6c6f6f6e656c613a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','48 1','1734 1768','289 1768',X'034b47215074796952785161303030303030303030303a636164656e63652e6d6f65405f6f6f79655f6d6f6d6f7473756b692e3a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','5 1','1832 1835','299 1835',X'034b4b2151544372636e6953303030303030303030303a636164656e63652e6d6f65405f6f6f79655f72616e646f6d6974796775793a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','64 1','2097 2100','353 2100',X'034b4521536c7664497a734f303030303030303030303a636164656e63652e6d6f65405f6f6f79655f5f706b5f626369736c3a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','81 1','2213 2240','361 2240',X'034b4721544f61794476734c303030303030303030303a636164656e63652e6d6f65405f6f6f79655f5f706b5f6f7a707a79633a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','42 1','2368 2409','373 2409',X'034b49215468436b4b585743303030303030303030303a636164656e63652e6d6f65405f6f6f79655f776172736d6974686c69763a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','36 1','2422 2447','380 2447',X'034b4b2154716c79516d6966303030303030303030303a636164656e63652e6d6f65405f6f6f79655f6a6f6b65726765726d616e793a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','65 1','2689 2721','438 2721',X'034b472157755a5549494e74303030303030303030303a636164656e63652e6d6f65405f6f6f79655f5f706b5f77797a63686a3a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','2 1','3058 3059','497 3059',X'034b3921616f764c6d776a67303030303030303030303a636164656e63652e6d6f65405f6f6f79655f726e6c3a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','8 1','3666 3671','630 3671',X'034b39216966636d75794e6e303030303030303030303a636164656e63652e6d6f65405f6f6f79655f726e6c3a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','43 1','3849 3874','668 3874',X'034b4f216b6b4b714249664c303030303030303030303a636164656e63652e6d6f65405f6f6f79655f656c656374726f6e6963353339313a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','8 1','4280 4283','746 4283',X'034b3f216f705748554e6b46303030303030303030303a636164656e63652e6d6f65405f6f6f79655f636f6f6b69653a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','158 1','4424 4465','770 4465',X'034b452170757146464b5948303030303030303030303a636164656e63652e6d6f65405f6f6f79655f5f706b5f6a666e747a3a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','44 1','4810 4810','824 4810',X'034b4121734b4c6f784a4e62303030303030303030303a636164656e63652e6d6f65405f6f6f79655f313030626563733a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','11 1','4892 4895','841 4895',X'034b45217443744769524448303030303030303030303a636164656e63652e6d6f65405f6f6f79655f646f6f74736b7972653a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','73 1','5072 5089','888 5089',X'034b47217665764462756174303030303030303030303a636164656e63652e6d6f65405f6f6f79655f5f706b5f6b73706a75653a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','59 1','5182 5236','903 5236',X'034b43217750454472596b77303030303030303030303a636164656e63652e6d6f65405f6f6f79655f74656368323334613a636164656e63652e6d6f65'),
|
|
||||||
('sim_member','sim_member','52 1','5441 5469','968 5469',X'034b41217a66654e574d744b303030303030303030303a636164656e63652e6d6f65405f6f6f79655f6e6f766574746f3a636164656e63652e6d6f65'),
|
|
||||||
('emoji','emoji','1','385','385',X'023331313035373039393137313237353737363733'),
|
|
||||||
('emoji','emoji','1','771','771',X'023331323230353735323436303531303533353638'),
|
|
||||||
('emoji','emoji','1','1157','1157',X'023331333530383339313335363836313033303730'),
|
|
||||||
('emoji','emoji','1','1543','1543',X'0231333439373232393637383636393938373834'),
|
|
||||||
('emoji','emoji','1','1929','1929',X'0231343933383437383237313138353535313436'),
|
|
||||||
('emoji','emoji','1','2315','2315',X'0231363432353731303038313337373536373032'),
|
|
||||||
('emoji','emoji','1','2701','2701',X'0231373738313036343330333034393434313238'),
|
|
||||||
('emoji','emoji','1','3087','3087',X'0231393030383733373535343037303336343738'),
|
|
||||||
('guild_space','guild_space','1','4','4',X'023331313333333135333632353636343535333336'),
|
|
||||||
('guild_space','guild_space','1','9','9',X'023331313534383638343234373234343633363837'),
|
|
||||||
('guild_space','guild_space','1','14','14',X'023331323139303338323637383430393235383138'),
|
|
||||||
('guild_space','guild_space','1','19','19',X'023331323839363030383537323437303535383733'),
|
|
||||||
('guild_space','guild_space','1','24','24',X'023331333435363431323031393032323838393837'),
|
|
||||||
('guild_space','guild_space','1','29','29',X'0231323733383737363437323234393935383431'),
|
|
||||||
('guild_space','guild_space','1','34','34',X'0231353239313736313536333938363832313135'),
|
|
||||||
('guild_space','guild_space','1','39','39',X'0231383730313138363530373638363730373530'),
|
|
||||||
('member_power','member_power','1 1','0 0','0 0',X'03350f40636164656e63653a636164656e63652e6d6f652a'),
|
|
||||||
('sim_proxy','sim_proxy','1','23','23',X'025531363733363165392d656137652d343530392d623533302d356531613863613735336237'),
|
|
||||||
('sim_proxy','sim_proxy','1','47','47',X'025532653561626332312d326332622d346133352d386237642d366432383162363036653932'),
|
|
||||||
('sim_proxy','sim_proxy','1','71','71',X'025534383131393165322d393462302d346534632d623934352d336330323932623135356238'),
|
|
||||||
('sim_proxy','sim_proxy','1','95','95',X'025536346331346631642d663834342d346535622d386665332d336162336163363239616230'),
|
|
||||||
('sim_proxy','sim_proxy','1','119','119',X'025538376562363463322d363763352d346432352d383161642d666664333235663266303639'),
|
|
||||||
('sim_proxy','sim_proxy','1','143','143',X'025561616630313539652d623165312d343231342d396266652d313334613536303738323231'),
|
|
||||||
('sim_proxy','sim_proxy','1','167','167',X'025563396534393633372d663061352d343566352d383234382d366436393565643861316434'),
|
|
||||||
('sim_proxy','sim_proxy','1','191','191',X'025565333734613634362d386231332d343365392d393635392d653233326366653866626265'),
|
|
||||||
('member_cache','member_cache','4 1','98 99','66 99',X'034b35214a48614a71425870303030303030303030303a636164656e63652e6d6f6540657a7261637574653a6d61747269782e6f7267'),
|
|
||||||
('member_cache','member_cache','4 1','119 122','80 122',X'034b43214c684978654c4d54303030303030303030303a636164656e63652e6d6f6540737461727368696e656c756e6163793a6d61747269782e6f7267'),
|
|
||||||
('member_cache','member_cache','1 1','124 124','82 124',X'034b2d214d5071594e414a62303030303030303030303a636164656e63652e6d6f6540726e6c3a636164656e63652e6d6f65'),
|
|
||||||
('member_cache','member_cache','5 1','128 131','85 131',X'034b3b214e446249714e704a303030303030303030303a636164656e63652e6d6f65406761627269656c766f6e643a6d61747269782e6f7267'),
|
|
||||||
('member_cache','member_cache','4 1','138 139','90 139',X'034b3d214f48584445737062303030303030303030303a636164656e63652e6d6f6540616d693a7468652d61706f746865636172792e636c7562'),
|
|
||||||
('member_cache','member_cache','5 1','207 209','135 209',X'034b51215450616f6a545444303030303030303030303a636164656e63652e6d6f65406a61636b736f6e6368656e3636363a6a61636b736f6e6368656e3636362e636f6d'),
|
|
||||||
('member_cache','member_cache','76 1','216 249','140 249',X'034b2d2154716c79516d6966303030303030303030303a636164656e63652e6d6f65406963656d616e3a656e76732e6e6574'),
|
|
||||||
('member_cache','member_cache','4 1','345 345','171 345',X'034b3521586f4c466b65786a303030303030303030303a636164656e63652e6d6f6540636164656e63653a636164656e63652e6d6f65'),
|
|
||||||
('member_cache','member_cache','10 1','351 354','174 354',X'034b3521594b46454e797166303030303030303030303a636164656e63652e6d6f654066617269656c6c653a6d61747269782e6f7267'),
|
|
||||||
('member_cache','member_cache','1 1','374 374','183 374',X'034b2d21596f54644f55766a303030303030303030303a636164656e63652e6d6f6540726e6c3a636164656e63652e6d6f65'),
|
|
||||||
('member_cache','member_cache','152 1','405 499','205 499',X'034b45216342787456527844303030303030303030303a636164656e63652e6d6f65406d61726975733835313030303a6d617269757364617669642e6672'),
|
|
||||||
('member_cache','member_cache','4 1','562 563','209 563',X'034b35216356514d45455158303030303030303030303a636164656e63652e6d6f6540657a7261637574653a6d61747269782e6f7267'),
|
|
||||||
('member_cache','member_cache','8 1','582 586','223 586',X'034b3721654856655270706e303030303030303030303a636164656e63652e6d6f65406563686f3a66757272797265667567652e636f6d'),
|
|
||||||
('member_cache','member_cache','7 1','594 600','227 600',X'034b3b2165724f7079584e46303030303030303030303a636164656e63652e6d6f6540766962656973766572796f3a6d61747269782e6f7267'),
|
|
||||||
('member_cache','member_cache','165 1','613 624','235 624',X'034b4921676865544b5a7451303030303030303030303a636164656e63652e6d6f6540616d70666c6f7765723a7468652d61706f746865636172792e636c7562'),
|
|
||||||
('member_cache','member_cache','165 1','613 749','235 749',X'034b4521676865544b5a7451303030303030303030303a636164656e63652e6d6f654073706c617473756e653a636861742e6e6575726172696f2e636f6d'),
|
|
||||||
('member_cache','member_cache','6 1','778 782','236 782',X'034b3321676b6b686f756d42303030303030303030303a636164656e63652e6d6f65406b6162693a6361746769726c2e776f726b73'),
|
|
||||||
('member_cache','member_cache','10 1','786 794','239 794',X'034b332168424a766e654e4f303030303030303030303a636164656e63652e6d6f65406d65636879613a636164656e63652e6d6f65'),
|
|
||||||
('member_cache','member_cache','13 1','809 819','249 819',X'034b2b2169537958674e7851303030303030303030303a636164656e63652e6d6f65406d69646f753a656e76732e6e6574'),
|
|
||||||
('member_cache','member_cache','4 1','856 858','273 858',X'034b3b216b73724f45554666303030303030303030303a636164656e63652e6d6f65406761627269656c766f6e643a6d61747269782e6f7267'),
|
|
||||||
('member_cache','member_cache','12 1','865 874','279 874',X'034b35216c7570486a715444303030303030303030303a636164656e63652e6d6f654068656c6c63703a6f70656e737573652e6f7267'),
|
|
||||||
('member_cache','member_cache','4 1','886 887','285 887',X'034b2d216d61676745536775303030303030303030303a636164656e63652e6d6f65406361743a6d61756e69756d2e6e6574'),
|
|
||||||
('member_cache','member_cache','71 1','999 999','357 999',X'034b2d2177574f6673767573303030303030303030303a636164656e63652e6d6f654061613a6361747669626572732e6d65'),
|
|
||||||
('member_cache','member_cache','14 1','1074 1085','361 1085',X'034b3721776c534544496a44303030303030303030303a636164656e63652e6d6f654073646f6d693a6861636b657273706163652e706c'),
|
|
||||||
('file','file','1','4054','4054',X'03816568747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f3131323736303636393137383234313032342f313135313733303032323332383035373930372f53637265656e73686f745f32303233303931345f3036303333352e6a7067'),
|
|
||||||
('file','file','1','8109','8109',X'03814168747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f3131393239333936393731353639313532322f313231383430393538323539343838373638302f494d475f343738322e6a7067'),
|
|
||||||
('file','file','1','12164','12164',X'03813b68747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f3133343037373735333438353033333437322f313139393131323831343931373333333133332f696d6167652e706e67'),
|
|
||||||
('file','file','1','16219','16219',X'03814168747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f313337363732343737393830353034383838322f313339323938363435323538343936303032312f707265766965772e706e67'),
|
|
||||||
('file','file','1','20274','20274',X'03816568747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f3135393136353731343139343735393638302f313236353735383536303531323338313030392f53637265656e73686f745f32303234303732342d3135353232382e706e67'),
|
|
||||||
('file','file','1','24329','24329',X'03813b68747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f3238383838323935333331343839333832352f313134373538383535363839343738313539332f696d6167652e706e67'),
|
|
||||||
('file','file','1','28384','28384',X'03817168747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f3635353231363137333639363238363734362f313330383239363937343136333737353530392f31373331393932363837323838343136383737323137393036333831303733392e6a7067'),
|
|
||||||
('file','file','1','32439','32439',X'027f68747470733a2f2f63646e2e646973636f72646170702e636f6d2f656d6f6a69732f313034323532383239323539363632313434322e706e67'),
|
|
||||||
('lottie','lottie','1','2','2',X'0231373439303532393434363832353832303336'),
|
|
||||||
('lottie','lottie','1','5','5',X'0231373531363036333739333430333635383634'),
|
|
||||||
('lottie','lottie','1','8','8',X'0231373534313038373731383532323232353634'),
|
|
||||||
('lottie','lottie','1','11','11',X'0231373936313430363338303933343433303932'),
|
|
||||||
('lottie','lottie','1','14','14',X'0231373936313431373032363935343835353030'),
|
|
||||||
('lottie','lottie','1','17','17',X'0231383136303837373932323931323832393434'),
|
|
||||||
('lottie','lottie','1','20','20',X'0231383233393736313032393736323930383636');
|
|
||||||
|
|
||||||
ANALYZE sqlite_schema;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
CREATE TABLE room_upgrade_pending (
|
|
||||||
new_room_id TEXT NOT NULL,
|
|
||||||
old_room_id TEXT NOT NULL UNIQUE,
|
|
||||||
PRIMARY KEY (new_room_id),
|
|
||||||
FOREIGN KEY (old_room_id) REFERENCES channel_room (room_id) ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,61 +0,0 @@
|
||||||
/*
|
|
||||||
a. If the bridge bot sim already has the correct ID:
|
|
||||||
- No rows updated.
|
|
||||||
|
|
||||||
b. If the bridge bot sim has the wrong ID but there's no duplicate:
|
|
||||||
- One row updated.
|
|
||||||
|
|
||||||
c. If the bridge bot sim has the wrong ID and there's a duplicate:
|
|
||||||
- One row updated (replaces an existing row).
|
|
||||||
*/
|
|
||||||
|
|
||||||
const {discord} = require("../../passthrough")
|
|
||||||
|
|
||||||
const ones = "₀₁₂₃₄₅₆₇₈₉"
|
|
||||||
const tens = "0123456789"
|
|
||||||
|
|
||||||
/* c8 ignore start */
|
|
||||||
|
|
||||||
module.exports = async function(db) {
|
|
||||||
/** @type {{name: string, channel_id: string, thread_parent: string | null}[]} */
|
|
||||||
const rows = db.prepare("SELECT name, channel_id, thread_parent FROM channel_room WHERE guild_id IS NULL").all()
|
|
||||||
|
|
||||||
/** @type {Map<string, string>} channel or thread ID -> guild ID */
|
|
||||||
const cache = new Map()
|
|
||||||
|
|
||||||
// Process channels
|
|
||||||
process.stdout.write(` loading metadata for ${rows.length} channels/threads... `)
|
|
||||||
for (let counter = 1; counter <= rows.length; counter++) {
|
|
||||||
process.stdout.write(String(counter).at(-1) === "0" ? tens[(counter/10)%10] : ones[counter%10])
|
|
||||||
const row = rows[counter-1]
|
|
||||||
const id = row.thread_parent || row.channel_id
|
|
||||||
if (cache.has(id)) continue
|
|
||||||
|
|
||||||
try {
|
|
||||||
var channel = await discord.snow.channel.getChannel(id)
|
|
||||||
} catch (e) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
const guildID = channel.guild_id
|
|
||||||
const channels = await discord.snow.guild.getGuildChannels(guildID)
|
|
||||||
for (const channel of channels) {
|
|
||||||
cache.set(channel.id, guildID)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update channels and threads
|
|
||||||
process.stdout.write("\n")
|
|
||||||
db.transaction(() => {
|
|
||||||
// Fill in missing data
|
|
||||||
for (const row of rows) {
|
|
||||||
const guildID = cache.get(row.thread_parent) || cache.get(row.channel_id)
|
|
||||||
if (guildID) {
|
|
||||||
db.prepare("UPDATE channel_room SET guild_id = ? WHERE channel_id = ?").run(guildID, row.channel_id)
|
|
||||||
} else {
|
|
||||||
db.prepare("DELETE FROM webhook WHERE channel_id = ?").run(row.channel_id)
|
|
||||||
db.prepare("DELETE FROM channel_room WHERE channel_id = ?").run(row.channel_id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})()
|
|
||||||
}
|
|
||||||
|
|
@ -1,44 +0,0 @@
|
||||||
-- https://sqlite.org/lang_altertable.html
|
|
||||||
|
|
||||||
-- 1
|
|
||||||
PRAGMA foreign_keys=OFF;
|
|
||||||
-- 2
|
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
-- 4
|
|
||||||
CREATE TABLE "new_channel_room" (
|
|
||||||
"channel_id" TEXT NOT NULL,
|
|
||||||
"room_id" TEXT NOT NULL UNIQUE,
|
|
||||||
"name" TEXT NOT NULL,
|
|
||||||
"nick" TEXT,
|
|
||||||
"thread_parent" TEXT,
|
|
||||||
"custom_avatar" TEXT,
|
|
||||||
"last_bridged_pin_timestamp" INTEGER,
|
|
||||||
"speedbump_id" TEXT,
|
|
||||||
"speedbump_checked" INTEGER,
|
|
||||||
"speedbump_webhook_id" TEXT,
|
|
||||||
"guild_id" TEXT NOT NULL,
|
|
||||||
"custom_topic" INTEGER DEFAULT 0,
|
|
||||||
PRIMARY KEY("channel_id"),
|
|
||||||
FOREIGN KEY("guild_id") REFERENCES "guild_active"("guild_id") ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
|
|
||||||
-- 5
|
|
||||||
INSERT INTO new_channel_room
|
|
||||||
(channel_id, room_id, name, nick, thread_parent, custom_avatar, last_bridged_pin_timestamp, speedbump_id, speedbump_checked, speedbump_webhook_id, guild_id, custom_topic)
|
|
||||||
SELECT channel_id, room_id, name, nick, thread_parent, custom_avatar, last_bridged_pin_timestamp, speedbump_id, speedbump_checked, speedbump_webhook_id, guild_id, custom_topic
|
|
||||||
FROM channel_room;
|
|
||||||
|
|
||||||
-- 6
|
|
||||||
DROP TABLE channel_room;
|
|
||||||
|
|
||||||
-- 7
|
|
||||||
ALTER TABLE new_channel_room RENAME TO channel_room;
|
|
||||||
|
|
||||||
-- 10
|
|
||||||
PRAGMA foreign_key_check;
|
|
||||||
|
|
||||||
-- 11
|
|
||||||
COMMIT;
|
|
||||||
-- 12
|
|
||||||
PRAGMA foreign_keys=ON;
|
|
||||||
|
|
@ -1,34 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
DROP TABLE IF EXISTS "poll";
|
|
||||||
DROP TABLE IF EXISTS "poll_option";
|
|
||||||
DROP TABLE IF EXISTS "poll_vote";
|
|
||||||
|
|
||||||
CREATE TABLE "poll" (
|
|
||||||
"message_id" TEXT NOT NULL,
|
|
||||||
"max_selections" INTEGER NOT NULL,
|
|
||||||
"question_text" TEXT NOT NULL,
|
|
||||||
"is_closed" INTEGER NOT NULL,
|
|
||||||
PRIMARY KEY ("message_id"),
|
|
||||||
FOREIGN KEY ("message_id") REFERENCES "message_room" ("message_id") ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
|
|
||||||
CREATE TABLE "poll_option" (
|
|
||||||
"message_id" TEXT NOT NULL,
|
|
||||||
"matrix_option" TEXT NOT NULL,
|
|
||||||
"discord_option" TEXT,
|
|
||||||
"option_text" TEXT NOT NULL,
|
|
||||||
"seq" INTEGER NOT NULL,
|
|
||||||
PRIMARY KEY ("message_id", "matrix_option"),
|
|
||||||
FOREIGN KEY ("message_id") REFERENCES "poll" ("message_id") ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
|
|
||||||
CREATE TABLE "poll_vote" (
|
|
||||||
"message_id" TEXT NOT NULL,
|
|
||||||
"matrix_option" TEXT NOT NULL,
|
|
||||||
"discord_or_matrix_user_id" TEXT NOT NULL,
|
|
||||||
PRIMARY KEY ("message_id", "matrix_option", "discord_or_matrix_user_id"),
|
|
||||||
FOREIGN KEY ("message_id", "matrix_option") REFERENCES "poll_option" ("message_id", "matrix_option") ON DELETE CASCADE
|
|
||||||
) WITHOUT ROWID;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
ALTER TABLE member_cache ADD COLUMN missing_profile INTEGER;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
DELETE FROM sim WHERE sim_name like '%/%';
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
87
src/db/orm-defs.d.ts
vendored
87
src/db/orm-defs.d.ts
vendored
|
|
@ -1,9 +1,4 @@
|
||||||
export type Models = {
|
export type Models = {
|
||||||
auto_emoji: {
|
|
||||||
name: string
|
|
||||||
emoji_id: string
|
|
||||||
}
|
|
||||||
|
|
||||||
channel_room: {
|
channel_room: {
|
||||||
channel_id: string
|
channel_id: string
|
||||||
room_id: string
|
room_id: string
|
||||||
|
|
@ -15,20 +10,6 @@ export type Models = {
|
||||||
speedbump_id: string | null
|
speedbump_id: string | null
|
||||||
speedbump_webhook_id: string | null
|
speedbump_webhook_id: string | null
|
||||||
speedbump_checked: number | null
|
speedbump_checked: number | null
|
||||||
guild_id: string | null
|
|
||||||
custom_topic: number
|
|
||||||
}
|
|
||||||
|
|
||||||
direct: {
|
|
||||||
mxid: string
|
|
||||||
room_id: string
|
|
||||||
}
|
|
||||||
|
|
||||||
emoji: {
|
|
||||||
emoji_id: string
|
|
||||||
name: string
|
|
||||||
animated: number
|
|
||||||
mxc_url: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
event_message: {
|
event_message: {
|
||||||
|
|
@ -50,29 +31,11 @@ export type Models = {
|
||||||
guild_id: string
|
guild_id: string
|
||||||
space_id: string
|
space_id: string
|
||||||
privacy_level: number
|
privacy_level: number
|
||||||
presence: 0 | 1
|
|
||||||
url_preview: 0 | 1
|
|
||||||
webhook_profile: 0 | 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
guild_active: {
|
guild_active: {
|
||||||
guild_id: string
|
guild_id: string
|
||||||
autocreate: 0 | 1
|
autocreate: number
|
||||||
}
|
|
||||||
|
|
||||||
historical_channel_room: {
|
|
||||||
historical_room_index: number
|
|
||||||
reference_channel_id: string
|
|
||||||
room_id: string
|
|
||||||
upgraded_timestamp: number
|
|
||||||
}
|
|
||||||
|
|
||||||
invite: {
|
|
||||||
mxid: string
|
|
||||||
room_id: string
|
|
||||||
type: string | null
|
|
||||||
name: string | null
|
|
||||||
avatar: string | null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
lottie: {
|
lottie: {
|
||||||
|
|
@ -80,17 +43,12 @@ export type Models = {
|
||||||
mxc_url: string
|
mxc_url: string
|
||||||
}
|
}
|
||||||
|
|
||||||
media_proxy: {
|
|
||||||
permitted_hash: number
|
|
||||||
}
|
|
||||||
|
|
||||||
member_cache: {
|
member_cache: {
|
||||||
room_id: string
|
room_id: string
|
||||||
mxid: string
|
mxid: string
|
||||||
displayname: string | null
|
displayname: string | null
|
||||||
avatar_url: string | null,
|
avatar_url: string | null,
|
||||||
power_level: number
|
power_level: number
|
||||||
missing_profile: number | null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
member_power: {
|
member_power: {
|
||||||
|
|
@ -99,20 +57,15 @@ export type Models = {
|
||||||
power_level: number
|
power_level: number
|
||||||
}
|
}
|
||||||
|
|
||||||
message_room: {
|
message_channel: {
|
||||||
message_id: string
|
message_id: string
|
||||||
historical_room_index: number
|
channel_id: string
|
||||||
}
|
|
||||||
|
|
||||||
room_upgrade_pending: {
|
|
||||||
new_room_id: string
|
|
||||||
old_room_id: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sim: {
|
sim: {
|
||||||
user_id: string
|
user_id: string
|
||||||
username: string
|
|
||||||
sim_name: string
|
sim_name: string
|
||||||
|
localpart: string
|
||||||
mxid: string
|
mxid: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -134,32 +87,27 @@ export type Models = {
|
||||||
webhook_token: string
|
webhook_token: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
emoji: {
|
||||||
|
emoji_id: string
|
||||||
|
name: string
|
||||||
|
animated: number
|
||||||
|
mxc_url: string
|
||||||
|
}
|
||||||
|
|
||||||
reaction: {
|
reaction: {
|
||||||
hashed_event_id: number
|
hashed_event_id: number
|
||||||
message_id: string
|
message_id: string
|
||||||
encoded_emoji: string
|
encoded_emoji: string
|
||||||
original_encoding: string | null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
poll: { // not actually in database yet
|
auto_emoji: {
|
||||||
message_id: string
|
name: string
|
||||||
max_selections: number
|
emoji_id: string
|
||||||
question_text: string
|
guild_id: string
|
||||||
is_closed: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
poll_option: {
|
media_proxy: {
|
||||||
message_id: string
|
permitted_hash: number
|
||||||
matrix_option: string
|
|
||||||
discord_option: string | null
|
|
||||||
option_text: string // not actually in database yet
|
|
||||||
seq: number // not actually in database yet
|
|
||||||
}
|
|
||||||
|
|
||||||
poll_vote: {
|
|
||||||
message_id: string
|
|
||||||
matrix_option: string
|
|
||||||
discord_or_matrix_user_id: string
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -176,4 +124,3 @@ export type PickTypeOf<T, K extends AllKeys<T>> = T extends { [k in K]?: any } ?
|
||||||
export type Merge<U> = {[x in AllKeys<U>]: PickTypeOf<U, x>}
|
export type Merge<U> = {[x in AllKeys<U>]: PickTypeOf<U, x>}
|
||||||
export type Nullable<T> = {[k in keyof T]: T[k] | null}
|
export type Nullable<T> = {[k in keyof T]: T[k] | null}
|
||||||
export type Numberish<T> = {[k in keyof T]: T[k] extends number ? (number | bigint) : T[k]}
|
export type Numberish<T> = {[k in keyof T]: T[k] extends number ? (number | bigint) : T[k]}
|
||||||
export type ValueOrArray<T> = {[k in keyof T]: T[k][] | T[k]}
|
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ const U = require("./orm-defs")
|
||||||
* @template {keyof U.Models[Table]} Col
|
* @template {keyof U.Models[Table]} Col
|
||||||
* @param {Table} table
|
* @param {Table} table
|
||||||
* @param {Col[] | Col} cols
|
* @param {Col[] | Col} cols
|
||||||
* @param {Partial<U.ValueOrArray<U.Numberish<U.Models[Table]>>>} where
|
* @param {Partial<U.Numberish<U.Models[Table]>>} where
|
||||||
* @param {string} [e]
|
* @param {string} [e]
|
||||||
*/
|
*/
|
||||||
function select(table, cols, where = {}, e = "") {
|
function select(table, cols, where = {}, e = "") {
|
||||||
|
|
|
||||||
|
|
@ -6,23 +6,23 @@ const data = require("../../test/data")
|
||||||
const {db, select, from} = require("../passthrough")
|
const {db, select, from} = require("../passthrough")
|
||||||
|
|
||||||
test("orm: select: get works", t => {
|
test("orm: select: get works", t => {
|
||||||
const row = select("guild_space", "guild_id", {}, "WHERE space_id = ?").get("!jjmvBegULiLucuWEHU:cadence.moe")
|
const row = select("guild_space", "guild_id", {}, "WHERE space_id = ?").get("!jjWAGMeQdNrVZSSfvz:cadence.moe")
|
||||||
t.equal(row?.guild_id, data.guild.general.id)
|
t.equal(row?.guild_id, data.guild.general.id)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("orm: from: get works", t => {
|
test("orm: from: get works", t => {
|
||||||
const row = from("guild_space").select("guild_id").and("WHERE space_id = ?").get("!jjmvBegULiLucuWEHU:cadence.moe")
|
const row = from("guild_space").select("guild_id").and("WHERE space_id = ?").get("!jjWAGMeQdNrVZSSfvz:cadence.moe")
|
||||||
t.equal(row?.guild_id, data.guild.general.id)
|
t.equal(row?.guild_id, data.guild.general.id)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("orm: select: get pluck works", t => {
|
test("orm: select: get pluck works", t => {
|
||||||
const guildID = select("guild_space", "guild_id", {}, "WHERE space_id = ?").pluck().get("!jjmvBegULiLucuWEHU:cadence.moe")
|
const guildID = select("guild_space", "guild_id", {}, "WHERE space_id = ?").pluck().get("!jjWAGMeQdNrVZSSfvz:cadence.moe")
|
||||||
t.equal(guildID, data.guild.general.id)
|
t.equal(guildID, data.guild.general.id)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("orm: select: get, where and pluck works", t => {
|
test("orm: select: get, where and pluck works", t => {
|
||||||
const emojiName = select("emoji", "name", {emoji_id: "230201364309868544"}).pluck().get()
|
const channelID = select("message_channel", "channel_id", {message_id: "1128118177155526666"}).pluck().get()
|
||||||
t.equal(emojiName, "hippo")
|
t.equal(channelID, "112760669178241024")
|
||||||
})
|
})
|
||||||
|
|
||||||
test("orm: select: all, where and pluck works on multiple columns", t => {
|
test("orm: select: all, where and pluck works on multiple columns", t => {
|
||||||
|
|
@ -30,13 +30,8 @@ test("orm: select: all, where and pluck works on multiple columns", t => {
|
||||||
t.deepEqual(names, ["cadence [they]"])
|
t.deepEqual(names, ["cadence [they]"])
|
||||||
})
|
})
|
||||||
|
|
||||||
test("orm: select: in array works", t => {
|
|
||||||
const ids = select("emoji", "emoji_id", {name: ["online", "upstinky"]}).pluck().all()
|
|
||||||
t.deepEqual(ids, ["288858540888686602", "606664341298872324"])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("orm: from: get pluck works", t => {
|
test("orm: from: get pluck works", t => {
|
||||||
const guildID = from("guild_space").pluck("guild_id").and("WHERE space_id = ?").get("!jjmvBegULiLucuWEHU:cadence.moe")
|
const guildID = from("guild_space").pluck("guild_id").and("WHERE space_id = ?").get("!jjWAGMeQdNrVZSSfvz:cadence.moe")
|
||||||
t.equal(guildID, data.guild.general.id)
|
t.equal(guildID, data.guild.general.id)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -58,13 +53,3 @@ test("orm: from: join direction works", t => {
|
||||||
const hasNoOwnerInner = from("sim").join("sim_proxy", "user_id", "inner").select("user_id", "proxy_owner_id").where({sim_name: "crunch_god"}).get()
|
const hasNoOwnerInner = from("sim").join("sim_proxy", "user_id", "inner").select("user_id", "proxy_owner_id").where({sim_name: "crunch_god"}).get()
|
||||||
t.deepEqual(hasNoOwnerInner, undefined)
|
t.deepEqual(hasNoOwnerInner, undefined)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("orm: select unsafe works (to select complex column names that can't be type verified)", t => {
|
|
||||||
const results = from("member_cache")
|
|
||||||
.join("member_power", "mxid")
|
|
||||||
.join("channel_room", "room_id") // only include rooms that are bridged
|
|
||||||
.and("where member_power.room_id = '*' and member_cache.power_level != member_power.power_level")
|
|
||||||
.selectUnsafe("mxid", "member_cache.room_id", "member_power.power_level")
|
|
||||||
.all()
|
|
||||||
t.equal(results[0].power_level, 150)
|
|
||||||
})
|
|
||||||
|
|
|
||||||
115
src/discord/interactions/bridge.js
Normal file
115
src/discord/interactions/bridge.js
Normal file
|
|
@ -0,0 +1,115 @@
|
||||||
|
// @ts-check
|
||||||
|
|
||||||
|
const DiscordTypes = require("discord-api-types/v10")
|
||||||
|
const Ty = require("../../types")
|
||||||
|
const {discord, sync, db, select, from, as} = require("../../passthrough")
|
||||||
|
const assert = require("assert/strict")
|
||||||
|
|
||||||
|
/** @type {import("../../matrix/api")} */
|
||||||
|
const api = sync.require("../../matrix/api")
|
||||||
|
|
||||||
|
/** @type {Map<string, Promise<{name: string, value: string}[]>>} spaceID -> list of rooms */
|
||||||
|
const cache = new Map()
|
||||||
|
/** @type {Map<string, string>} roomID -> spaceID */
|
||||||
|
const reverseCache = new Map()
|
||||||
|
|
||||||
|
// Manage clearing the cache
|
||||||
|
sync.addTemporaryListener(as, "type:m.room.name", /** @param {Ty.Event.StateOuter<Ty.Event.M_Room_Name>} event */ async event => {
|
||||||
|
if (event.state_key !== "") return
|
||||||
|
const roomID = event.room_id
|
||||||
|
const spaceID = reverseCache.get(roomID)
|
||||||
|
if (!spaceID) return
|
||||||
|
const childRooms = await cache.get(spaceID)
|
||||||
|
if (!childRooms) return
|
||||||
|
if (event.content.name) {
|
||||||
|
const found = childRooms.find(r => r.value === roomID)
|
||||||
|
if (!found) return
|
||||||
|
found.name = event.content.name
|
||||||
|
} else {
|
||||||
|
cache.set(spaceID, Promise.resolve(childRooms.filter(r => r.value !== roomID)))
|
||||||
|
reverseCache.delete(roomID)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Manage adding to the cache
|
||||||
|
async function getCachedHierarchy(spaceID) {
|
||||||
|
return cache.get(spaceID) || (() => {
|
||||||
|
const entry = (async () => {
|
||||||
|
const result = await api.getFullHierarchy(spaceID)
|
||||||
|
/** @type {{name: string, value: string}[]} */
|
||||||
|
const childRooms = []
|
||||||
|
for (const room of result) {
|
||||||
|
if (room.name && !room.name.match(/^\[[⛓️🔊]\]/) && room.room_type !== "m.space") {
|
||||||
|
childRooms.push({name: room.name, value: room.room_id})
|
||||||
|
reverseCache.set(room.room_id, spaceID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return childRooms
|
||||||
|
})()
|
||||||
|
cache.set(spaceID, entry)
|
||||||
|
return entry
|
||||||
|
})()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {DiscordTypes.APIApplicationCommandAutocompleteGuildInteraction} interaction */
|
||||||
|
async function interactAutocomplete({id, token, data, guild_id}) {
|
||||||
|
const spaceID = select("guild_space", "space_id", {guild_id}).pluck().get()
|
||||||
|
if (!spaceID) {
|
||||||
|
return discord.snow.interaction.createInteractionResponse(id, token, {
|
||||||
|
type: DiscordTypes.InteractionResponseType.ApplicationCommandAutocompleteResult,
|
||||||
|
data: {
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
name: `Error: This server needs to be bridged somewhere first...`,
|
||||||
|
value: "baby"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
let rooms = await getCachedHierarchy(spaceID)
|
||||||
|
// @ts-ignore
|
||||||
|
rooms = rooms.filter(r => r.name.includes(data.options[0].value))
|
||||||
|
|
||||||
|
await discord.snow.interaction.createInteractionResponse(id, token, {
|
||||||
|
type: DiscordTypes.InteractionResponseType.ApplicationCommandAutocompleteResult,
|
||||||
|
data: {
|
||||||
|
choices: rooms
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction} interaction */
|
||||||
|
async function interactSubmit({id, token, data, guild_id}) {
|
||||||
|
const spaceID = select("guild_space", "space_id", {guild_id}).pluck().get()
|
||||||
|
if (!spaceID) {
|
||||||
|
return discord.snow.interaction.createInteractionResponse(id, token, {
|
||||||
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
|
data: {
|
||||||
|
content: "Error: This server needs to be bridged somewhere first...",
|
||||||
|
flags: DiscordTypes.MessageFlags.Ephemeral
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return discord.snow.interaction.createInteractionResponse(id, token, {
|
||||||
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
|
data: {
|
||||||
|
content: "Valid input. This would do something but it isn't implemented yet.",
|
||||||
|
flags: DiscordTypes.MessageFlags.Ephemeral
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {DiscordTypes.APIGuildInteraction} interaction */
|
||||||
|
async function interact(interaction) {
|
||||||
|
if (interaction.type === DiscordTypes.InteractionType.ApplicationCommandAutocomplete) {
|
||||||
|
return interactAutocomplete(interaction)
|
||||||
|
} else if (interaction.type === DiscordTypes.InteractionType.ApplicationCommand) {
|
||||||
|
// @ts-ignore
|
||||||
|
return interactSubmit(interaction)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports.interact = interact
|
||||||
|
|
@ -2,69 +2,39 @@
|
||||||
|
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
const DiscordTypes = require("discord-api-types/v10")
|
||||||
const assert = require("assert/strict")
|
const assert = require("assert/strict")
|
||||||
const {InteractionMethods} = require("snowtransfer")
|
const {discord, sync, db, select, from} = require("../../passthrough")
|
||||||
const {id: botID} = require("../../../addbot")
|
|
||||||
const {discord, sync, db, select} = require("../../passthrough")
|
|
||||||
|
|
||||||
/** @type {import("../../d2m/actions/create-room")} */
|
|
||||||
const createRoom = sync.require("../../d2m/actions/create-room")
|
|
||||||
/** @type {import("../../d2m/actions/create-space")} */
|
|
||||||
const createSpace = sync.require("../../d2m/actions/create-space")
|
|
||||||
/** @type {import("../../matrix/api")} */
|
/** @type {import("../../matrix/api")} */
|
||||||
const api = sync.require("../../matrix/api")
|
const api = sync.require("../../matrix/api")
|
||||||
/** @type {import("../../matrix/read-registration")} */
|
|
||||||
const {reg} = sync.require("../../matrix/read-registration")
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction & {channel: DiscordTypes.APIGuildTextChannel}} interaction
|
* @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction} interaction
|
||||||
* @param {{api: typeof api}} di
|
* @returns {Promise<DiscordTypes.APIInteractionResponse>}
|
||||||
* @returns {AsyncGenerator<{[k in keyof InteractionMethods]?: Parameters<InteractionMethods[k]>[2]}>}
|
|
||||||
*/
|
*/
|
||||||
async function* _interact({data, channel, guild_id}, {api}) {
|
async function _interact({data, channel, guild_id}) {
|
||||||
// Check guild exists - it might not exist if the application was added with applications.commands scope and not bot scope
|
// Check guild is bridged
|
||||||
const guild = discord.guilds.get(guild_id)
|
const spaceID = select("guild_space", "space_id", {guild_id}).pluck().get()
|
||||||
if (!guild) return yield {createInteractionResponse: {
|
const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get()
|
||||||
|
if (!spaceID || !roomID) return {
|
||||||
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
data: {
|
data: {
|
||||||
content: `I can't perform actions in this server because there is no bot presence in the server. You should try re-adding this bot to the server, making sure that it has bot scope (not just commands).\nIf you add the bot from ${reg.ooye.bridge_origin} this should work automatically.`,
|
content: "This server isn't bridged to Matrix, so you can't invite Matrix users.",
|
||||||
flags: DiscordTypes.MessageFlags.Ephemeral
|
flags: DiscordTypes.MessageFlags.Ephemeral
|
||||||
}
|
}
|
||||||
}}
|
}
|
||||||
|
|
||||||
// Get named MXID
|
// Get named MXID
|
||||||
/** @type {DiscordTypes.APIApplicationCommandInteractionDataStringOption[] | undefined} */ // @ts-ignore
|
/** @type {DiscordTypes.APIApplicationCommandInteractionDataStringOption[] | undefined} */ // @ts-ignore
|
||||||
const options = data.options
|
const options = data.options
|
||||||
const input = options?.[0]?.value || ""
|
const input = options?.[0].value || ""
|
||||||
const mxid = input.match(/@([^:]+):([a-z0-9:-]+\.[a-z0-9.:-]+)/)?.[0]
|
const mxid = input.match(/@([^:]+):([a-z0-9:-]+\.[a-z0-9.:-]+)/)?.[0]
|
||||||
if (!mxid) return yield {createInteractionResponse: {
|
if (!mxid) return {
|
||||||
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
data: {
|
data: {
|
||||||
content: "You have to say the Matrix ID of the person you want to invite. Matrix IDs look like this: `@username:example.org`",
|
content: "You have to say the Matrix ID of the person you want to invite. Matrix IDs look like this: `@username:example.org`",
|
||||||
flags: DiscordTypes.MessageFlags.Ephemeral
|
flags: DiscordTypes.MessageFlags.Ephemeral
|
||||||
}
|
}
|
||||||
}}
|
|
||||||
|
|
||||||
// Ensure guild and room are bridged
|
|
||||||
db.prepare("INSERT OR IGNORE INTO guild_active (guild_id, autocreate) VALUES (?, 1)").run(guild_id)
|
|
||||||
const existing = createRoom.existsOrAutocreatable(channel, guild_id)
|
|
||||||
if (existing === 0) return yield {createInteractionResponse: {
|
|
||||||
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
|
||||||
data: {
|
|
||||||
content: "This channel isn't bridged, so you can't invite Matrix users yet. Try turning on automatic room-creation or link a Matrix room in the website.",
|
|
||||||
flags: DiscordTypes.MessageFlags.Ephemeral
|
|
||||||
}
|
}
|
||||||
}}
|
|
||||||
assert(existing) // can't be null or undefined as we just inserted the guild_active row
|
|
||||||
|
|
||||||
yield {createInteractionResponse: {
|
|
||||||
type: DiscordTypes.InteractionResponseType.DeferredChannelMessageWithSource,
|
|
||||||
data: {
|
|
||||||
flags: DiscordTypes.MessageFlags.Ephemeral
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
|
|
||||||
const spaceID = await createSpace.ensureSpace(guild)
|
|
||||||
const roomID = await createRoom.ensureRoom(channel.id)
|
|
||||||
|
|
||||||
// Check for existing invite to the space
|
// Check for existing invite to the space
|
||||||
let spaceMember
|
let spaceMember
|
||||||
|
|
@ -72,17 +42,24 @@ async function* _interact({data, channel, guild_id}, {api}) {
|
||||||
spaceMember = await api.getStateEvent(spaceID, "m.room.member", mxid)
|
spaceMember = await api.getStateEvent(spaceID, "m.room.member", mxid)
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
if (spaceMember && spaceMember.membership === "invite") {
|
if (spaceMember && spaceMember.membership === "invite") {
|
||||||
return yield {editOriginalInteractionResponse: {
|
return {
|
||||||
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
|
data: {
|
||||||
content: `\`${mxid}\` already has an invite, which they haven't accepted yet.`,
|
content: `\`${mxid}\` already has an invite, which they haven't accepted yet.`,
|
||||||
}}
|
flags: DiscordTypes.MessageFlags.Ephemeral
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Invite Matrix user if not in space
|
// Invite Matrix user if not in space
|
||||||
if (!spaceMember || spaceMember.membership !== "join") {
|
if (!spaceMember || spaceMember.membership !== "join") {
|
||||||
await api.inviteToRoom(spaceID, mxid)
|
await api.inviteToRoom(spaceID, mxid)
|
||||||
return yield {editOriginalInteractionResponse: {
|
return {
|
||||||
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
|
data: {
|
||||||
content: `You invited \`${mxid}\` to the server.`
|
content: `You invited \`${mxid}\` to the server.`
|
||||||
}}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Matrix user *is* in the space, maybe we want to invite them to this channel?
|
// The Matrix user *is* in the space, maybe we want to invite them to this channel?
|
||||||
|
|
@ -91,8 +68,11 @@ async function* _interact({data, channel, guild_id}, {api}) {
|
||||||
roomMember = await api.getStateEvent(roomID, "m.room.member", mxid)
|
roomMember = await api.getStateEvent(roomID, "m.room.member", mxid)
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
if (!roomMember || (roomMember.membership !== "join" && roomMember.membership !== "invite")) {
|
if (!roomMember || (roomMember.membership !== "join" && roomMember.membership !== "invite")) {
|
||||||
return yield {editOriginalInteractionResponse: {
|
return {
|
||||||
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
|
data: {
|
||||||
content: `\`${mxid}\` is already in this server. Would you like to additionally invite them to this specific channel?`,
|
content: `\`${mxid}\` is already in this server. Would you like to additionally invite them to this specific channel?`,
|
||||||
|
flags: DiscordTypes.MessageFlags.Ephemeral,
|
||||||
components: [{
|
components: [{
|
||||||
type: DiscordTypes.ComponentType.ActionRow,
|
type: DiscordTypes.ComponentType.ActionRow,
|
||||||
components: [{
|
components: [{
|
||||||
|
|
@ -102,21 +82,25 @@ async function* _interact({data, channel, guild_id}, {api}) {
|
||||||
label: "Sure",
|
label: "Sure",
|
||||||
}]
|
}]
|
||||||
}]
|
}]
|
||||||
}}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Matrix user *is* in the space and in the channel.
|
// The Matrix user *is* in the space and in the channel.
|
||||||
return yield {editOriginalInteractionResponse: {
|
return {
|
||||||
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
|
data: {
|
||||||
content: `\`${mxid}\` is already in this server and this channel.`,
|
content: `\`${mxid}\` is already in this server and this channel.`,
|
||||||
}}
|
flags: DiscordTypes.MessageFlags.Ephemeral
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {DiscordTypes.APIMessageComponentGuildInteraction} interaction
|
* @param {DiscordTypes.APIMessageComponentGuildInteraction} interaction
|
||||||
* @param {{api: typeof api}} di
|
|
||||||
* @returns {Promise<DiscordTypes.APIInteractionResponse>}
|
* @returns {Promise<DiscordTypes.APIInteractionResponse>}
|
||||||
*/
|
*/
|
||||||
async function _interactButton({channel, message}, {api}) {
|
async function _interactButton({channel, message}) {
|
||||||
const mxid = message.content.match(/`(@(?:[^:]+):(?:[a-z0-9:-]+\.[a-z0-9.:-]+))`/)?.[1]
|
const mxid = message.content.match(/`(@(?:[^:]+):(?:[a-z0-9:-]+\.[a-z0-9.:-]+))`/)?.[1]
|
||||||
assert(mxid)
|
assert(mxid)
|
||||||
const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get()
|
const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get()
|
||||||
|
|
@ -131,23 +115,14 @@ async function _interactButton({channel, message}, {api}) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* c8 ignore start */
|
/** @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction} interaction */
|
||||||
|
|
||||||
/** @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction & {channel: DiscordTypes.APIGuildTextChannel}} interaction */
|
|
||||||
async function interact(interaction) {
|
async function interact(interaction) {
|
||||||
for await (const response of _interact(interaction, {api})) {
|
await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interact(interaction))
|
||||||
if (response.createInteractionResponse) {
|
|
||||||
// TODO: Test if it is reasonable to remove `await` from these calls. Or zip these calls with the next interaction iteration and use Promise.all.
|
|
||||||
await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, response.createInteractionResponse)
|
|
||||||
} else if (response.editOriginalInteractionResponse) {
|
|
||||||
await discord.snow.interaction.editOriginalInteractionResponse(botID, interaction.token, response.editOriginalInteractionResponse)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param {DiscordTypes.APIMessageComponentGuildInteraction} interaction */
|
/** @param {DiscordTypes.APIMessageComponentGuildInteraction} interaction */
|
||||||
async function interactButton(interaction) {
|
async function interactButton(interaction) {
|
||||||
await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interactButton(interaction, {api}))
|
await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interactButton(interaction))
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.interact = interact
|
module.exports.interact = interact
|
||||||
|
|
|
||||||
|
|
@ -1,256 +0,0 @@
|
||||||
const {test} = require("supertape")
|
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
|
||||||
const {db, discord} = require("../../passthrough")
|
|
||||||
const {MatrixServerError} = require("../../matrix/mreq")
|
|
||||||
const {_interact, _interactButton} = require("./invite")
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @template T
|
|
||||||
* @param {AsyncIterable<T>} ai
|
|
||||||
* @returns {Promise<T[]>}
|
|
||||||
*/
|
|
||||||
async function fromAsync(ai) {
|
|
||||||
const result = []
|
|
||||||
for await (const value of ai) {
|
|
||||||
result.push(value)
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
test("invite: checks for missing matrix ID", async t => {
|
|
||||||
const msgs = await fromAsync(_interact({
|
|
||||||
data: {
|
|
||||||
options: []
|
|
||||||
},
|
|
||||||
channel: discord.channels.get("0"),
|
|
||||||
guild_id: "112760669178241024"
|
|
||||||
}, {}))
|
|
||||||
t.equal(msgs[0].createInteractionResponse.data.content, "You have to say the Matrix ID of the person you want to invite. Matrix IDs look like this: `@username:example.org`")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("invite: checks for invalid matrix ID", async t => {
|
|
||||||
const msgs = await fromAsync(_interact({
|
|
||||||
data: {
|
|
||||||
options: [{
|
|
||||||
name: "user",
|
|
||||||
type: DiscordTypes.ApplicationCommandOptionType.String,
|
|
||||||
value: "@cadence"
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
channel: discord.channels.get("0"),
|
|
||||||
guild_id: "112760669178241024"
|
|
||||||
}, {}))
|
|
||||||
t.equal(msgs[0].createInteractionResponse.data.content, "You have to say the Matrix ID of the person you want to invite. Matrix IDs look like this: `@username:example.org`")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("invite: checks if guild exists", async t => { // it might not exist if the application was added with applications.commands scope and not bot scope
|
|
||||||
const msgs = await fromAsync(_interact({
|
|
||||||
data: {
|
|
||||||
options: [{
|
|
||||||
name: "user",
|
|
||||||
type: DiscordTypes.ApplicationCommandOptionType.String,
|
|
||||||
value: "@cadence:cadence.moe"
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
channel: discord.channels.get("0"),
|
|
||||||
guild_id: "0"
|
|
||||||
}, {}))
|
|
||||||
t.match(msgs[0].createInteractionResponse.data.content, /there is no bot presence in the server/)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("invite: checks if channel exists or is autocreatable", async t => {
|
|
||||||
db.prepare("UPDATE guild_active SET autocreate = 0 WHERE guild_id = '112760669178241024'").run()
|
|
||||||
const msgs = await fromAsync(_interact({
|
|
||||||
data: {
|
|
||||||
options: [{
|
|
||||||
name: "user",
|
|
||||||
type: DiscordTypes.ApplicationCommandOptionType.String,
|
|
||||||
value: "@cadence:cadence.moe"
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
channel: discord.channels.get("498323546729086986"),
|
|
||||||
guild_id: "112760669178241024"
|
|
||||||
}, {}))
|
|
||||||
t.equal(msgs[0].createInteractionResponse.data.content, "This channel isn't bridged, so you can't invite Matrix users yet. Try turning on automatic room-creation or link a Matrix room in the website.")
|
|
||||||
db.prepare("UPDATE guild_active SET autocreate = 1 WHERE guild_id = '112760669178241024'").run()
|
|
||||||
})
|
|
||||||
|
|
||||||
test("invite: checks if user is already invited to space", async t => {
|
|
||||||
let called = 0
|
|
||||||
const msgs = await fromAsync(_interact({
|
|
||||||
data: {
|
|
||||||
options: [{
|
|
||||||
name: "user",
|
|
||||||
type: DiscordTypes.ApplicationCommandOptionType.String,
|
|
||||||
value: "@cadence:cadence.moe"
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
channel: discord.channels.get("112760669178241024"),
|
|
||||||
guild_id: "112760669178241024"
|
|
||||||
}, {
|
|
||||||
api: {
|
|
||||||
getStateEvent: async (roomID, type, stateKey) => {
|
|
||||||
called++
|
|
||||||
t.equal(roomID, "!jjmvBegULiLucuWEHU:cadence.moe") // space ID
|
|
||||||
t.equal(type, "m.room.member")
|
|
||||||
t.equal(stateKey, "@cadence:cadence.moe")
|
|
||||||
return {
|
|
||||||
displayname: "cadence",
|
|
||||||
membership: "invite"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
t.equal(msgs[1].editOriginalInteractionResponse.content, "`@cadence:cadence.moe` already has an invite, which they haven't accepted yet.")
|
|
||||||
t.equal(called, 1)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("invite: invites if user is not in space", async t => {
|
|
||||||
let called = 0
|
|
||||||
const msgs = await fromAsync(_interact({
|
|
||||||
data: {
|
|
||||||
options: [{
|
|
||||||
name: "user",
|
|
||||||
type: DiscordTypes.ApplicationCommandOptionType.String,
|
|
||||||
value: "@cadence:cadence.moe"
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
channel: discord.channels.get("112760669178241024"),
|
|
||||||
guild_id: "112760669178241024"
|
|
||||||
}, {
|
|
||||||
api: {
|
|
||||||
getStateEvent: async (roomID, type, stateKey) => {
|
|
||||||
called++
|
|
||||||
t.equal(roomID, "!jjmvBegULiLucuWEHU:cadence.moe") // space ID
|
|
||||||
t.equal(type, "m.room.member")
|
|
||||||
t.equal(stateKey, "@cadence:cadence.moe")
|
|
||||||
throw new MatrixServerError("State event doesn't exist or something")
|
|
||||||
},
|
|
||||||
inviteToRoom: async (roomID, mxid) => {
|
|
||||||
called++
|
|
||||||
t.equal(roomID, "!jjmvBegULiLucuWEHU:cadence.moe") // space ID
|
|
||||||
t.equal(mxid, "@cadence:cadence.moe")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
t.equal(msgs[1].editOriginalInteractionResponse.content, "You invited `@cadence:cadence.moe` to the server.")
|
|
||||||
t.equal(called, 2)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("invite: prompts to invite to room (if never joined)", async t => {
|
|
||||||
let called = 0
|
|
||||||
const msgs = await fromAsync(_interact({
|
|
||||||
data: {
|
|
||||||
options: [{
|
|
||||||
name: "user",
|
|
||||||
type: DiscordTypes.ApplicationCommandOptionType.String,
|
|
||||||
value: "@cadence:cadence.moe"
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
channel: discord.channels.get("112760669178241024"),
|
|
||||||
guild_id: "112760669178241024"
|
|
||||||
}, {
|
|
||||||
api: {
|
|
||||||
getStateEvent: async (roomID, type, stateKey) => {
|
|
||||||
called++
|
|
||||||
t.equal(type, "m.room.member")
|
|
||||||
t.equal(stateKey, "@cadence:cadence.moe")
|
|
||||||
if (roomID === "!jjmvBegULiLucuWEHU:cadence.moe") { // space ID
|
|
||||||
return {
|
|
||||||
displayname: "cadence",
|
|
||||||
membership: "join"
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw new MatrixServerError("State event doesn't exist or something")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
t.equal(msgs[1].editOriginalInteractionResponse.content, "`@cadence:cadence.moe` is already in this server. Would you like to additionally invite them to this specific channel?")
|
|
||||||
t.equal(called, 2)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("invite: prompts to invite to room (if left)", async t => {
|
|
||||||
let called = 0
|
|
||||||
const msgs = await fromAsync(_interact({
|
|
||||||
data: {
|
|
||||||
options: [{
|
|
||||||
name: "user",
|
|
||||||
type: DiscordTypes.ApplicationCommandOptionType.String,
|
|
||||||
value: "@cadence:cadence.moe"
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
channel: discord.channels.get("112760669178241024"),
|
|
||||||
guild_id: "112760669178241024"
|
|
||||||
}, {
|
|
||||||
api: {
|
|
||||||
getStateEvent: async (roomID, type, stateKey) => {
|
|
||||||
called++
|
|
||||||
t.equal(type, "m.room.member")
|
|
||||||
t.equal(stateKey, "@cadence:cadence.moe")
|
|
||||||
if (roomID === "!jjmvBegULiLucuWEHU:cadence.moe") { // space ID
|
|
||||||
return {
|
|
||||||
displayname: "cadence",
|
|
||||||
membership: "join"
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return {
|
|
||||||
displayname: "cadence",
|
|
||||||
membership: "leave"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
t.equal(msgs[1].editOriginalInteractionResponse.content, "`@cadence:cadence.moe` is already in this server. Would you like to additionally invite them to this specific channel?")
|
|
||||||
t.equal(called, 2)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("invite button: invites to room when button clicked", async t => {
|
|
||||||
let called = 0
|
|
||||||
const msg = await _interactButton({
|
|
||||||
channel: discord.channels.get("112760669178241024"),
|
|
||||||
message: {
|
|
||||||
content: "`@cadence:cadence.moe` is already in this server. Would you like to additionally invite them to this specific channel?"
|
|
||||||
}
|
|
||||||
}, {
|
|
||||||
api: {
|
|
||||||
inviteToRoom: async (roomID, mxid) => {
|
|
||||||
called++
|
|
||||||
t.equal(roomID, "!kLRqKKUQXcibIMtOpl:cadence.moe") // room ID
|
|
||||||
t.equal(mxid, "@cadence:cadence.moe")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.equal(msg.data.content, "You invited `@cadence:cadence.moe` to the channel.")
|
|
||||||
t.equal(called, 1)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("invite: no-op if in room and space", async t => {
|
|
||||||
let called = 0
|
|
||||||
const msgs = await fromAsync(_interact({
|
|
||||||
data: {
|
|
||||||
options: [{
|
|
||||||
name: "user",
|
|
||||||
type: DiscordTypes.ApplicationCommandOptionType.String,
|
|
||||||
value: "@cadence:cadence.moe"
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
channel: discord.channels.get("112760669178241024"),
|
|
||||||
guild_id: "112760669178241024"
|
|
||||||
}, {
|
|
||||||
api: {
|
|
||||||
getStateEvent: async (roomID, type, stateKey) => {
|
|
||||||
called++
|
|
||||||
t.equal(type, "m.room.member")
|
|
||||||
t.equal(stateKey, "@cadence:cadence.moe")
|
|
||||||
return {
|
|
||||||
displayname: "cadence",
|
|
||||||
membership: "join"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
t.equal(msgs[1].editOriginalInteractionResponse.content, "`@cadence:cadence.moe` is already in this server and this channel.")
|
|
||||||
t.equal(called, 2)
|
|
||||||
})
|
|
||||||
|
|
@ -1,108 +1,51 @@
|
||||||
// @ts-check
|
// @ts-check
|
||||||
|
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
const DiscordTypes = require("discord-api-types/v10")
|
||||||
const {discord, sync, select, from} = require("../../passthrough")
|
const {discord, sync, db, select, from} = require("../../passthrough")
|
||||||
const assert = require("assert").strict
|
|
||||||
|
|
||||||
/** @type {import("../../matrix/api")} */
|
/** @type {import("../../matrix/api")} */
|
||||||
const api = sync.require("../../matrix/api")
|
const api = sync.require("../../matrix/api")
|
||||||
|
|
||||||
/** @type {import("../../matrix/utils")} */
|
/** @param {DiscordTypes.APIContextMenuGuildInteraction} interaction */
|
||||||
const utils = sync.require("../../matrix/utils")
|
/** @param {DiscordTypes.APIMessageApplicationCommandGuildInteraction} interaction */
|
||||||
|
async function interact({id, token, guild_id, channel, data}) {
|
||||||
/** @type {import("../../web/routes/guild")} */
|
const message = from("event_message").join("message_channel", "message_id").join("channel_room", "channel_id")
|
||||||
const webGuild = sync.require("../../web/routes/guild")
|
.select("name", "nick", "source", "room_id", "event_id").where({message_id: data.target_id}).get()
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {DiscordTypes.APIMessageApplicationCommandGuildInteraction} interaction
|
|
||||||
* @param {{api: typeof api}} di
|
|
||||||
* @returns {Promise<DiscordTypes.APIInteractionResponse>}
|
|
||||||
*/
|
|
||||||
async function _interact({guild_id, data}, {api}) {
|
|
||||||
const message = from("event_message").join("message_room", "message_id").join("historical_channel_room", "historical_room_index")
|
|
||||||
.select("source", "reference_channel_id", "room_id", "event_id").where({message_id: data.target_id}).and("ORDER BY part").get()
|
|
||||||
|
|
||||||
if (!message) {
|
if (!message) {
|
||||||
return {
|
return discord.snow.interaction.createInteractionResponse(id, token, {
|
||||||
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
data: {
|
data: {
|
||||||
content: "This message hasn't been bridged to Matrix.",
|
content: "This message hasn't been bridged to Matrix.",
|
||||||
flags: DiscordTypes.MessageFlags.Ephemeral
|
flags: DiscordTypes.MessageFlags.Ephemeral
|
||||||
}
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const channel_id = message.reference_channel_id
|
|
||||||
const room = select("channel_room", ["name", "nick"], {channel_id}).get()
|
|
||||||
assert(room)
|
|
||||||
|
|
||||||
const idInfo = `\n-# Room ID: \`${message.room_id}\`\n-# Event ID: \`${message.event_id}\``
|
const idInfo = `\n-# Room ID: \`${message.room_id}\`\n-# Event ID: \`${message.event_id}\``
|
||||||
const roomName = room.nick || room.name
|
|
||||||
|
|
||||||
if (message.source === 1) { // from Discord
|
if (message.source === 1) { // from Discord
|
||||||
const userID = data.resolved.messages[data.target_id].author.id
|
const userID = data.resolved.messages[data.target_id].author.id
|
||||||
return {
|
return discord.snow.interaction.createInteractionResponse(id, token, {
|
||||||
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
data: {
|
data: {
|
||||||
content: `Bridged <@${userID}> https://discord.com/channels/${guild_id}/${channel_id}/${data.target_id} on Discord to [${roomName}](<https://matrix.to/#/${message.room_id}/${message.event_id}>) on Matrix.`
|
content: `Bridged <@${userID}> https://discord.com/channels/${guild_id}/${channel.id}/${data.target_id} on Discord to [${message.nick || message.name}](<https://matrix.to/#/${message.room_id}/${message.event_id}>) on Matrix.`
|
||||||
+ idInfo,
|
+ idInfo,
|
||||||
flags: DiscordTypes.MessageFlags.Ephemeral
|
flags: DiscordTypes.MessageFlags.Ephemeral
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// from Matrix
|
// from Matrix
|
||||||
const event = await api.getEvent(message.room_id, message.event_id)
|
const event = await api.getEvent(message.room_id, message.event_id)
|
||||||
const via = await utils.getViaServersQuery(message.room_id, api)
|
return discord.snow.interaction.createInteractionResponse(id, token, {
|
||||||
const channelsInGuild = discord.guildChannelMap.get(guild_id)
|
|
||||||
assert(channelsInGuild)
|
|
||||||
const inChannels = channelsInGuild
|
|
||||||
// @ts-ignore
|
|
||||||
.map(/** @returns {DiscordTypes.APIGuildChannel} */ cid => discord.channels.get(cid))
|
|
||||||
.sort((a, b) => webGuild._getPosition(a, discord.channels) - webGuild._getPosition(b, discord.channels))
|
|
||||||
.filter(channel => from("channel_room").join("member_cache", "room_id").select("mxid").where({channel_id: channel.id, mxid: event.sender}).get())
|
|
||||||
const matrixMember = select("member_cache", ["displayname", "avatar_url"], {room_id: message.room_id, mxid: event.sender}).get()
|
|
||||||
const name = matrixMember?.displayname || event.sender
|
|
||||||
return {
|
|
||||||
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
data: {
|
data: {
|
||||||
embeds: [{
|
content: `Bridged [${event.sender}](<https://matrix.to/#/${event.sender}>)'s message in [${message.nick || message.name}](<https://matrix.to/#/${message.room_id}/${message.event_id}>) on Matrix to https://discord.com/channels/${guild_id}/${channel.id}/${data.target_id} on Discord.`
|
||||||
author: {
|
+ idInfo,
|
||||||
name,
|
|
||||||
url: `https://matrix.to/#/${event.sender}`,
|
|
||||||
icon_url: utils.getPublicUrlForMxc(matrixMember?.avatar_url)
|
|
||||||
},
|
|
||||||
description: `This Matrix message was delivered to Discord by **Out Of Your Element**.\n[View on Matrix →](<https://matrix.to/#/${message.room_id}/${message.event_id}?${via}>)\n\n**User ID**: [${event.sender}](<https://matrix.to/#/${event.sender}>)`,
|
|
||||||
color: 0x0dbd8b,
|
|
||||||
fields: [{
|
|
||||||
name: "In Channels",
|
|
||||||
value: inChannels.map(c => `<#${c.id}>`).join(" • ")
|
|
||||||
}, {
|
|
||||||
name: "\u200b",
|
|
||||||
value: idInfo
|
|
||||||
}]
|
|
||||||
}],
|
|
||||||
flags: DiscordTypes.MessageFlags.Ephemeral
|
flags: DiscordTypes.MessageFlags.Ephemeral
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
}
|
|
||||||
|
|
||||||
/* c8 ignore start */
|
|
||||||
|
|
||||||
/** @param {DiscordTypes.APIMessageApplicationCommandGuildInteraction} interaction */
|
|
||||||
async function interact(interaction) {
|
|
||||||
await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interact(interaction, {api}))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param {DiscordTypes.APIMessageApplicationCommandGuildInteraction} interaction */
|
|
||||||
async function dm(interaction) {
|
|
||||||
const channel = await discord.snow.user.createDirectMessageChannel(interaction.member.user.id)
|
|
||||||
const response = await _interact(interaction, {api})
|
|
||||||
assert(response.type === DiscordTypes.InteractionResponseType.ChannelMessageWithSource)
|
|
||||||
response.data.flags = 0 & 0 // not ephemeral
|
|
||||||
await discord.snow.channel.createMessage(channel.id, response.data)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.interact = interact
|
module.exports.interact = interact
|
||||||
module.exports._interact = _interact
|
|
||||||
module.exports.dm = dm
|
|
||||||
|
|
|
||||||
|
|
@ -1,87 +0,0 @@
|
||||||
const {test} = require("supertape")
|
|
||||||
const data = require("../../../test/data")
|
|
||||||
const {_interact} = require("./matrix-info")
|
|
||||||
|
|
||||||
test("matrix info: checks if message is bridged", async t => {
|
|
||||||
const msg = await _interact({
|
|
||||||
data: {
|
|
||||||
target_id: "0"
|
|
||||||
},
|
|
||||||
guild_id: "112760669178241024"
|
|
||||||
}, {})
|
|
||||||
t.equal(msg.data.content, "This message hasn't been bridged to Matrix.")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("matrix info: shows info for discord source message", async t => {
|
|
||||||
const msg = await _interact({
|
|
||||||
data: {
|
|
||||||
target_id: "1141619794500649020",
|
|
||||||
resolved: {
|
|
||||||
messages: {
|
|
||||||
"1141619794500649020": data.message_update.edit_by_webhook
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
guild_id: "497159726455455754"
|
|
||||||
}, {})
|
|
||||||
t.equal(
|
|
||||||
msg.data.content,
|
|
||||||
"Bridged <@700285844094845050> https://discord.com/channels/497159726455455754/497161350934560778/1141619794500649020 on Discord to [amanda-spam](<https://matrix.to/#/!CzvdIdUQXgUjDVKxeU:cadence.moe/$zXSlyI78DQqQwwfPUSzZ1b-nXzbUrCDljJgnGDdoI10>) on Matrix."
|
|
||||||
+ "\n-# Room ID: `!CzvdIdUQXgUjDVKxeU:cadence.moe`"
|
|
||||||
+ "\n-# Event ID: `$zXSlyI78DQqQwwfPUSzZ1b-nXzbUrCDljJgnGDdoI10`"
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("matrix info: shows info for matrix source message", async t => {
|
|
||||||
let called = 0
|
|
||||||
const msg = await _interact({
|
|
||||||
data: {
|
|
||||||
target_id: "1128118177155526666",
|
|
||||||
resolved: {
|
|
||||||
messages: {
|
|
||||||
"1141501302736695316": data.message.simple_reply_to_matrix_user
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
guild_id: "112760669178241024"
|
|
||||||
}, {
|
|
||||||
api: {
|
|
||||||
async getEvent(roomID, eventID) {
|
|
||||||
called++
|
|
||||||
t.equal(roomID, "!kLRqKKUQXcibIMtOpl:cadence.moe")
|
|
||||||
t.equal(eventID, "$Ij3qo7NxMA4VPexlAiIx2CB9JbsiGhJeyt-2OvkAUe4")
|
|
||||||
return {
|
|
||||||
event_id: eventID,
|
|
||||||
room_id: roomID,
|
|
||||||
type: "m.room.message",
|
|
||||||
content: {
|
|
||||||
msgtype: "m.text",
|
|
||||||
body: "so can you reply to my webhook uwu"
|
|
||||||
},
|
|
||||||
sender: "@cadence:cadence.moe"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async getJoinedMembers(roomID) {
|
|
||||||
return {
|
|
||||||
joined: {}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async getStateEventOuter(roomID, type, key) {
|
|
||||||
return {
|
|
||||||
content: {
|
|
||||||
room_version: "11"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async getStateEvent(roomID, type, key) {
|
|
||||||
return {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.equal(
|
|
||||||
msg.data.embeds[0].fields[1].value,
|
|
||||||
"\n-# Room ID: `!kLRqKKUQXcibIMtOpl:cadence.moe`"
|
|
||||||
+ "\n-# Event ID: `$Ij3qo7NxMA4VPexlAiIx2CB9JbsiGhJeyt-2OvkAUe4`"
|
|
||||||
)
|
|
||||||
t.equal(called, 1)
|
|
||||||
})
|
|
||||||
|
|
@ -2,44 +2,36 @@
|
||||||
|
|
||||||
const DiscordTypes = require("discord-api-types/v10")
|
const DiscordTypes = require("discord-api-types/v10")
|
||||||
const Ty = require("../../types")
|
const Ty = require("../../types")
|
||||||
const {discord, sync, select, from} = require("../../passthrough")
|
const {discord, sync, db, select, from} = require("../../passthrough")
|
||||||
const assert = require("assert/strict")
|
const assert = require("assert/strict")
|
||||||
const {id: botID} = require("../../../addbot")
|
|
||||||
const {InteractionMethods} = require("snowtransfer")
|
|
||||||
|
|
||||||
/** @type {import("../../matrix/api")} */
|
/** @type {import("../../matrix/api")} */
|
||||||
const api = sync.require("../../matrix/api")
|
const api = sync.require("../../matrix/api")
|
||||||
/** @type {import("../../matrix/utils")} */
|
|
||||||
const utils = sync.require("../../matrix/utils")
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {DiscordTypes.APIContextMenuGuildInteraction} interaction
|
* @param {DiscordTypes.APIContextMenuGuildInteraction} interaction
|
||||||
* @param {{api: typeof api, utils: typeof utils}} di
|
* @returns {Promise<DiscordTypes.APIInteractionResponse>}
|
||||||
* @returns {AsyncGenerator<{[k in keyof InteractionMethods]?: Parameters<InteractionMethods[k]>[2]}>}
|
|
||||||
*/
|
*/
|
||||||
async function* _interact({data, guild_id}, {api, utils}) {
|
async function _interact({data, channel, guild_id}) {
|
||||||
// Get message info
|
const row = select("event_message", ["event_id", "source"], {message_id: data.target_id}).get()
|
||||||
const row = from("event_message")
|
assert(row)
|
||||||
.join("message_room", "message_id").join("historical_channel_room", "historical_room_index")
|
|
||||||
.select("event_id", "source", "room_id", "reference_channel_id")
|
|
||||||
.where({message_id: data.target_id})
|
|
||||||
.get()
|
|
||||||
|
|
||||||
// Can't operate on Discord users
|
// Can't operate on Discord users
|
||||||
if (!row || row.source === 1) { // not bridged or sent by a discord user
|
if (row.source === 1) { // discord
|
||||||
return yield {createInteractionResponse: {
|
return {
|
||||||
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
data: {
|
data: {
|
||||||
content: `The permissions command can only be used on Matrix users.`,
|
content: `This command is only meaningful for Matrix users.`,
|
||||||
flags: DiscordTypes.MessageFlags.Ephemeral
|
flags: DiscordTypes.MessageFlags.Ephemeral
|
||||||
}
|
}
|
||||||
}}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the message sender, the person that will be inspected/edited
|
// Get the message sender, the person that will be inspected/edited
|
||||||
const roomID = select("channel_room", "room_id", {channel_id: row.reference_channel_id}).pluck().get()
|
const eventID = row.event_id
|
||||||
|
const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get()
|
||||||
assert(roomID)
|
assert(roomID)
|
||||||
const event = await api.getEvent(row.room_id, row.event_id)
|
const event = await api.getEvent(roomID, eventID)
|
||||||
const sender = event.sender
|
const sender = event.sender
|
||||||
|
|
||||||
// Get the space, where the power levels will be inspected/edited
|
// Get the space, where the power levels will be inspected/edited
|
||||||
|
|
@ -47,22 +39,22 @@ async function* _interact({data, guild_id}, {api, utils}) {
|
||||||
assert(spaceID)
|
assert(spaceID)
|
||||||
|
|
||||||
// Get the power level
|
// Get the power level
|
||||||
const {powers: {[event.sender]: userPower, [utils.bot]: botPower}} = await utils.getEffectivePower(spaceID, [event.sender, utils.bot], api)
|
/** @type {Ty.Event.M_Power_Levels} */
|
||||||
|
const powerLevelsContent = await api.getStateEvent(spaceID, "m.room.power_levels", "")
|
||||||
|
const userPower = powerLevelsContent.users?.[event.sender] || 0
|
||||||
|
|
||||||
// Administrators/founders equal to the bot cannot be demoted
|
// Administrators equal to the bot cannot be demoted
|
||||||
if (userPower >= botPower) {
|
if (userPower >= 100) {
|
||||||
return yield {createInteractionResponse: {
|
return {
|
||||||
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
data: {
|
data: {
|
||||||
content: `\`${sender}\` has administrator permissions. This cannot be edited.`,
|
content: `\`${sender}\` has administrator permissions. This cannot be edited.`,
|
||||||
flags: DiscordTypes.MessageFlags.Ephemeral
|
flags: DiscordTypes.MessageFlags.Ephemeral
|
||||||
}
|
}
|
||||||
}}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const adminLabel = botPower === 100 ? "Admin (you cannot undo this!)" : "Admin"
|
return {
|
||||||
|
|
||||||
yield {createInteractionResponse: {
|
|
||||||
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
|
||||||
data: {
|
data: {
|
||||||
content: `Showing permissions for \`${sender}\`. Click to edit.`,
|
content: `Showing permissions for \`${sender}\`. Click to edit.`,
|
||||||
|
|
@ -83,10 +75,6 @@ async function* _interact({data, guild_id}, {api, utils}) {
|
||||||
label: "Moderator",
|
label: "Moderator",
|
||||||
value: "moderator",
|
value: "moderator",
|
||||||
default: userPower >= 50 && userPower < 100
|
default: userPower >= 50 && userPower < 100
|
||||||
}, {
|
|
||||||
label: adminLabel,
|
|
||||||
value: "admin",
|
|
||||||
default: userPower >= 100
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
@ -94,75 +82,47 @@ async function* _interact({data, guild_id}, {api, utils}) {
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {DiscordTypes.APIMessageComponentSelectMenuInteraction} interaction
|
* @param {DiscordTypes.APIMessageComponentSelectMenuInteraction} interaction
|
||||||
* @param {{api: typeof api}} di
|
|
||||||
* @returns {AsyncGenerator<{[k in keyof InteractionMethods]?: Parameters<InteractionMethods[k]>[2]}>}
|
|
||||||
*/
|
*/
|
||||||
async function* _interactEdit({data, guild_id, message}, {api}) {
|
async function interactEdit({data, id, token, guild_id, message}) {
|
||||||
// Get the person that will be inspected/edited
|
// Get the person that will be inspected/edited
|
||||||
const mxid = message.content.match(/`(@(?:[^:]+):(?:[a-z0-9:-]+\.[a-z0-9.:-]+))`/)?.[1]
|
const mxid = message.content.match(/`(@(?:[^:]+):(?:[a-z0-9:-]+\.[a-z0-9.:-]+))`/)?.[1]
|
||||||
assert(mxid)
|
assert(mxid)
|
||||||
|
|
||||||
const permission = data.values[0]
|
const permission = data.values[0]
|
||||||
const power =
|
const power = permission === "moderator" ? 50 : 0
|
||||||
( permission === "admin" ? 100
|
|
||||||
: permission === "moderator" ? 50
|
|
||||||
: 0)
|
|
||||||
|
|
||||||
yield {createInteractionResponse: {
|
await discord.snow.interaction.createInteractionResponse(id, token, {
|
||||||
type: DiscordTypes.InteractionResponseType.UpdateMessage,
|
type: DiscordTypes.InteractionResponseType.UpdateMessage,
|
||||||
data: {
|
data: {
|
||||||
content: `Updating \`${mxid}\` to **${permission}**, please wait...`,
|
content: `Updating \`${mxid}\` to **${permission}**, please wait...`,
|
||||||
components: []
|
components: []
|
||||||
}
|
}
|
||||||
}}
|
})
|
||||||
|
|
||||||
// Get the space, where the power levels will be inspected/edited
|
// Get the space, where the power levels will be inspected/edited
|
||||||
const spaceID = select("guild_space", "space_id", {guild_id}).pluck().get()
|
const spaceID = select("guild_space", "space_id", {guild_id}).pluck().get()
|
||||||
assert(spaceID)
|
assert(spaceID)
|
||||||
|
|
||||||
// Do it
|
// Do it
|
||||||
await utils.setUserPowerCascade(spaceID, mxid, power, api)
|
await api.setUserPowerCascade(spaceID, mxid, power)
|
||||||
|
|
||||||
// ACK
|
// ACK
|
||||||
yield {editOriginalInteractionResponse: {
|
await discord.snow.interaction.editOriginalInteractionResponse(discord.application.id, token, {
|
||||||
content: `Updated \`${mxid}\` to **${permission}**.`,
|
content: `Updated \`${mxid}\` to **${permission}**.`,
|
||||||
components: []
|
components: []
|
||||||
}}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/* c8 ignore start */
|
|
||||||
|
|
||||||
/** @param {DiscordTypes.APIContextMenuGuildInteraction} interaction */
|
/** @param {DiscordTypes.APIContextMenuGuildInteraction} interaction */
|
||||||
async function interact(interaction) {
|
async function interact(interaction) {
|
||||||
for await (const response of _interact(interaction, {api, utils})) {
|
await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interact(interaction))
|
||||||
if (response.createInteractionResponse) {
|
|
||||||
// TODO: Test if it is reasonable to remove `await` from these calls. Or zip these calls with the next interaction iteration and use Promise.all.
|
|
||||||
await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, response.createInteractionResponse)
|
|
||||||
} else if (response.editOriginalInteractionResponse) {
|
|
||||||
await discord.snow.interaction.editOriginalInteractionResponse(botID, interaction.token, response.editOriginalInteractionResponse)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param {DiscordTypes.APIMessageComponentSelectMenuInteraction} interaction */
|
|
||||||
async function interactEdit(interaction) {
|
|
||||||
for await (const response of _interactEdit(interaction, {api})) {
|
|
||||||
if (response.createInteractionResponse) {
|
|
||||||
// TODO: Test if it is reasonable to remove `await` from these calls. Or zip these calls with the next interaction iteration and use Promise.all.
|
|
||||||
await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, response.createInteractionResponse)
|
|
||||||
} else if (response.editOriginalInteractionResponse) {
|
|
||||||
await discord.snow.interaction.editOriginalInteractionResponse(botID, interaction.token, response.editOriginalInteractionResponse)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.interact = interact
|
module.exports.interact = interact
|
||||||
module.exports.interactEdit = interactEdit
|
module.exports.interactEdit = interactEdit
|
||||||
module.exports._interact = _interact
|
module.exports._interact = _interact
|
||||||
module.exports._interactEdit = _interactEdit
|
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue