summary refs log tree commit diff
path: root/src/d2m/actions/expression.js
blob: c7ab27a0ce3d7cb72e6887b487a4972ffb0556ef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// @ts-check

const DiscordTypes = require("discord-api-types/v10")

const passthrough = require("../../passthrough")
const {sync, db} = passthrough
/** @type {import("../../matrix/file")} */
const file = sync.require("../../matrix/file")

/**
 * @param {DiscordTypes.APIEmoji[]} emojis
 * @param {DiscordTypes.APIGuild} guild
 */
async function emojisToState(emojis, guild) {
	const result = {
		pack: {
			display_name: `${guild.name} (Discord Emojis)`,
			usage: ["emoticon"] // we'll see...
		},
		images: {
		}
	}
	await Promise.all(emojis.map(emoji =>
		// the homeserver can probably cope with doing this in parallel
		file.uploadDiscordFileToMxc(file.emoji(emoji.id, emoji.animated)).then(url => {
			result.images[emoji.name] = {
				info: {
					mimetype: "image/webp"
				},
				url
			}
			db.prepare("INSERT OR IGNORE INTO emoji (emoji_id, name, animated, mxc_url) VALUES (?, ?, ?, ?)").run(emoji.id, emoji.name, +!!emoji.animated, url)
		}).catch(e => {
			if (e.data?.errcode === "M_TOO_LARGE") { // Very unlikely to happen. Only possible for 3x-series emojis uploaded shortly after animated emojis were introduced, when there was no 256 KB size limit.
				return
			}
			console.error(`Trying to handle emoji ${emoji.name} (${emoji.id}), but...`)
			throw e
		})
	))
	return result
}

/**
 * @param {DiscordTypes.APISticker[]} stickers
 * @param {DiscordTypes.APIGuild} guild
 */
async function stickersToState(stickers, guild) {
	const result = {
		pack: {
			display_name: `${guild.name} (Discord Stickers)`,
			usage: ["sticker"] // we'll see...
		},
		images: {
		}
	}
	const shortcodes = []
	await Promise.all(stickers.map(sticker =>
		// the homeserver can probably cope with doing this in parallel
		file.uploadDiscordFileToMxc(file.sticker(sticker)).then(url => {

			/** @type {string | undefined} */
			let body = sticker.name
			if (sticker && sticker.description) body += ` - ${sticker.description}`
			if (!body) body = undefined

			let shortcode = sticker.name.toLowerCase().replace(/[^a-zA-Z0-9_-]/g, "-").replace(/^-|-$/g, "").replace(/--+/g, "-")
			while (shortcodes.includes(shortcode)) shortcode = shortcode + "~"
			shortcodes.push(shortcode)

			result.images[shortcode] = {
				info: {
					mimetype: file.stickerFormat.get(sticker.format_type)?.mime || "image/png"
				},
				body,
				url
			}
		})
	))
	return result
}

module.exports.emojisToState = emojisToState
module.exports.stickersToState = stickersToState