out-of-your-element/m2d/converters/emoji.js

58 lines
1.8 KiB
JavaScript
Raw Normal View History

2023-09-25 10:15:36 +00:00
// @ts-check
const assert = require("assert").strict
const Ty = require("../../types")
const passthrough = require("../../passthrough")
const {sync, select} = passthrough
/**
2023-10-05 23:31:10 +00:00
* @param {string} input
2023-09-25 10:15:36 +00:00
* @param {string | null | undefined} shortcode
* @returns {string?}
*/
2023-10-05 23:31:10 +00:00
function encodeEmoji(input, shortcode) {
2023-09-25 10:15:36 +00:00
let discordPreferredEncoding
2023-10-05 23:31:10 +00:00
if (input.startsWith("mxc://")) {
2023-09-25 10:15:36 +00:00
// Custom emoji
2023-10-05 23:31:10 +00:00
let row = select("emoji", ["emoji_id", "name"], {mxc_url: input}).get()
2023-09-25 10:15:36 +00:00
if (!row && shortcode) {
// Use the name to try to find a known emoji with the same name.
const name = shortcode.replace(/^:|:$/g, "")
2023-10-05 23:31:10 +00:00
row = select("emoji", ["emoji_id", "name"], {name: name}).get()
2023-09-25 10:15:36 +00:00
}
if (!row) {
// We don't have this emoji and there's no realistic way to just-in-time upload a new emoji somewhere.
// Sucks!
return null
}
// Cool, we got an exact or a candidate emoji.
2023-10-05 23:31:10 +00:00
discordPreferredEncoding = encodeURIComponent(`${row.name}:${row.emoji_id}`)
2023-09-25 10:15:36 +00:00
} else {
// Default emoji
// https://github.com/discord/discord-api-docs/issues/2723#issuecomment-807022205 ????????????
2023-10-05 23:31:10 +00:00
const encoded = encodeURIComponent(input)
2023-09-25 10:15:36 +00:00
const encodedTrimmed = encoded.replace(/%EF%B8%8F/g, "")
const forceTrimmedList = [
"%F0%9F%91%8D", // 👍
"%F0%9F%91%8E", // 👎️
2023-09-25 10:15:36 +00:00
"%E2%AD%90", // ⭐
"%F0%9F%90%88", // 🐈
"%E2%9D%93", // ❓
2023-10-27 11:24:42 +00:00
"%F0%9F%8F%86", // 🏆️
"%F0%9F%93%9A", // 📚️
2023-09-25 10:15:36 +00:00
]
discordPreferredEncoding =
( forceTrimmedList.includes(encodedTrimmed) ? encodedTrimmed
2023-10-05 23:31:10 +00:00
: encodedTrimmed !== encoded && [...input].length === 2 ? encoded
2023-09-25 10:15:36 +00:00
: encodedTrimmed)
2023-10-05 23:31:10 +00:00
console.log("add reaction from matrix:", input, encoded, encodedTrimmed, "chosen:", discordPreferredEncoding)
2023-09-25 10:15:36 +00:00
}
return discordPreferredEncoding
}
module.exports.encodeEmoji = encodeEmoji