It's much easier to understand code with examples. So let's go through it together and add support for **pinned events** to Out Of Your Element.
## Gathering intel
First, we need to know what pinned events are supposed to look like. The Matrix C-S spec gives this example:
> **pinned** ... [string] ... Required: An ordered list of event IDs to pin.
> ```json
> {
> "content": {
> "pinned": [
> "$someevent:example.org"
> ]
> },
> "event_id": "$143273582443PhrSn:example.org",
> "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
> "sender": "@example:example.org",
> "state_key": "",
> "type": "m.room.pinned_events",
> }
> ```
This is part of the persistent room state. Simple enough. To update this, the state event and its list of pinned events is updated as a whole.
What does it look like on Discord-side?
> **Get Pinned Messages** \
> `GET` `/channels/{channel.id}/pins` \
> Returns all pinned messages in the channel as an array of message objects.
This is an API request to get the pinned messages. To update this, an API request will pin or unpin any specific message, adding or removing it from the list.
## What will the converter look like?
The converter will be very different in both directions.
For d2m, we will get the list of pinned messages, we will convert each message ID into the ID of an event we already have, and then we will set the entire `m.room.pinned_events` state to that list.
For m2d, we will have to diff the list of pinned messages against the previous version of the list, and for each event that was pinned or unpinned, we will send an API request to Discord to change its state.
## Missing messages
> ...we will convert each message ID into the ID of an event ***we already have***
As a couple of examples, the message might not be bridged if it was sent before OOYE was set up, or if OOYE just had a bug trying to handle that message. If a particular Discord message wasn't bridged, and then it gets pinned, we're in a bit of a pickle. We can't pin the Matrix equivalent because it doesn't exist.
In this situation we need to stop and think about the possible paths forward we could take.
* We could ignore this message and just not pin it.
* We could convert and send this message now with its original timestamp from the past, then pin this representation.
The latter method would still make the message appear at the bottom of the timeline for most Matrix clients, since for most the timestamp doesn't determine the actual _order._ It would then be confusing why an odd message suddenly appeared, because a pins change isn't that noticable in the room.
To avoid this problem, I'll just go with the former method and ignore the message, so Matrix will only have some of the pins that Discord has. We will need to watch out if a Matrix user edits this list of partial pins, because if we _only_ pinned things on Discord that were pinned on Matrix, those partial pins Discord would be lost from Discord side.
In this situation I will prefer to keep the pins list inconsistent between both sides and only bridge _changes_ to the list.
If you were implementing this for real, you might have made different decisions than me, and that's okay. It's a matter of taste. You just need to be aware of the consequences of what you choose.
## Test data for the d2m converter
Let's start writing the d2m converter. It's helpful to write unit tests for Out Of Your Element, since this lets you check if it worked without having to start up a local copy of the bridge or play around with the interface.
Normally for getting test data, I would `curl` the Discord API to grab some real data and put it into `data.js` (and possibly also `ooye-test-data.sql`. But this time, I'll fabricate some test data. Here it is:
```js
[
{id: "1126786462646550579"},
{id: "1141501302736695316"},
{id: "1106366167788044450"},
{id: "1115688611186193400"}
]
```
"These aren't message objects!" I hear you cry. Correct. I already know that my implementation is not going to care about any properties on these message object other than the IDs, so I'm just making a list of IDs to save time.
These IDs were carefully chosen. The first three are already in `ooye-test-data.sql` and are associated with event IDs. This is great, because in our test case, the Discord IDs will be converted to those event IDs. The fourth ID doesn't exist on Matrix-side. This is to test that partial pins are handled as expected, like I wrote in the previous section.
Now that I've got my list, I will make my first change to the code. I will add these IDs to `test/data.js`:
```diff
diff --git a/test/data.js b/test/data.js
index c36f252..4919beb 100644
--- a/test/data.js
+++ b/test/data.js
@@ -221,6 +221,14 @@ module.exports = {
deaf: false
}
},
+ pins: {
+ faked: [
+ {id: "1126786462646550579"},
+ {id: "1141501302736695316"},
+ {id: "1106366167788044450"},
+ {id: "1115688611186193400"}
+ ]
+ },
message: {
// Display order is text content, attachments, then stickers
simple_plaintext: {
```
## Writing the d2m converter
We can write a function that operates on this data to convert it to events. This is a _converter,_ not an _action._ it won't _do_ anything by itself. So it goes in the converters folder. The actual function is pretty simple since I've already planned what to do:
There's not much room for bugs in this function. A single manual test that it works would be good enough for me. But since this is an example of how you can add your own, let's add a test case for this. We'll take the data we just prepared and process it through the function we just wrote:
Oh no! (I promise I didn't make it fail for demonstration purposes, this was actually an accident!) Let's see what this bug is. It's returning the right number of IDs, but 2 out of the 3 are incorrect. The green `-` lines are "expected" and the red `+` lines are "actual". The wrong ID `$51f...` must have been taken from _somewhere_ in the test data, so I'll first search the codebase and find where it came from:
Explanation: This Discord message `1141501302736695316` is actually part of 2 different Matrix events, `$mtR...` and `$51f...`. This often happens when a Discord user uploads an image with a caption. Matrix doesn't support combined image+text events, so the image and the text have to be bridged to separate events. We should consider the text to be the primary part, and pin that, and consider the image to be the secondary part, and not pin that.
We already have a column `part` in the `event_message` table for this reason! When `part = 0`, that's the primary part. I'll edit the converter to actually use that column:
Actions call converters to do the thing, but actions have to receive their input event from somewhere. Let's wire it up so we receive a "pins changed" event from Discord and do the whole flow from there. Checking the documentation again, Discord will trigger this gateway event when the pins change:
> **Channel Pins Update** \
> Sent when a message is pinned or unpinned in a text channel. This is not sent when a pinned message is deleted. \
> **guild_id?** ... snowflake ... ID of the guild \
> **channel_id** ... snowflake ... ID of the channel \
> **last_pin_timestamp?** ... ?ISO8601 timestamp ... Time at which the most recent pinned message was pinned
Notably, the event doesn't deliver the actual list of pinned messages to us. We'll have to listen for this event, then trigger an API request to `GET` the pins list. Alright, enough preparation, time to code.
All packets are delivered to `discord-packets.js` which manages the internal state of the Discord object and then passes it on to a function in `event-dispatcher.js`:
`event-dispatcher.js` will now check if the event seems reasonable and is allowed in this context. For example, we can only update pins if the channel is actually bridged somewhere. After the check, we'll call the action:
I try to keep as much logic as possible out of the actions and in the converters. This should mean I *never have to unit test the actions themselves.* The actions will be tested manually with the real bot.
We can try these things and see if they are bridged to Matrix:
- Pin a recent message on Discord-side
- Pin an old message on Discord-side
- Unpin a message on Discord-side
It works like I'd expect!
## Order of pinned messages
I expected that to be the end of the guide, but after some time, I noticed a new problem: The pins are in reverse order. How could this happen?
[After some investigation,](https://gitdab.com/cadence/out-of-your-element/issues/16) it turns out Discord puts the most recently pinned message at the start of the array and displays the array in forwards order, while Matrix puts the most recently pinned message at the end of the array and displays the array in reverse order.
We'll fix this by reversing the order of the list of pins before we store it. I'll do this in the converter.
Note that this will only sync pins _when the pins change._ Existing pins from Discord will not be backfilled to Matrix rooms. If I wanted, there's a couple of ways I could address this:
* I could create a one-shot script in `scripts/update-pins.js` which will sync pins for _all_ Discord channels right away. I can run this after finishing the feature, or if the bot has been offline for some time.
* I could create a database table that holds the timestamp of the most recently detected pin for each channel - the `last_pin_timestamp` field from the gateway. Every time the bot starts, it would automatically compare the database table against every channel, and if the pins have changed since it last looked, it could automatically update them.
I already have code to backfill missed messages when the bridge starts up. The second option above would add a similar feature for backfilling missed pins. It would be worth considering.