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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

//! This module contains the [`Discord`] sink

use std::num::TryFromIntError;

use async_trait::async_trait;
use serenity::{
	builder::CreateMessage,
	http::Http as Bot,
	model::{
		channel::Message as DcMessage,
		id::{ChannelId, MessageId as DcMessageId, UserId},
	},
};

use super::{
	error::SinkError,
	message::{length_limiter::MessageLengthLimiter, Media, Message, MessageId},
	Sink,
};
use crate::utils::OptionExt;

// https://discord.com/developers/docs/resources/channel#create-message
const MAX_MSG_LEN: usize = 2000;
const MAX_EMBED_DESCIPTION_LEN: usize = 2000;

/// Discord sink. Supports both text channels and DMs with a user
#[derive(Debug)]
pub struct Discord {
	bot: Bot,
	target: TargetInner,
}

/// Target for the [`Discord`] sink where it sends message to
#[derive(Clone, Copy, Debug)]
pub enum Target {
	/// A text channel ID
	Channel(u64),

	/// A user ID, whose DMs to send messages into
	User(u64),
}

#[derive(Debug)]
enum TargetInner {
	Channel(ChannelId),
	User(UserId),
}

impl Discord {
	/// Create a new [`Discord`] sink. Needs a valid Discord bot `token` and a `target` where to send messages to
	#[must_use]
	pub fn new(token: &str, target: Target) -> Self {
		Self {
			bot: Bot::new(token),
			target: match target {
				Target::Channel(i) => TargetInner::Channel(i.into()),
				Target::User(i) => TargetInner::User(i.into()),
			},
		}
	}
}

#[async_trait]
impl Sink for Discord {
	async fn send(
		&self,
		msg: Message,
		reply_to: Option<&MessageId>,
		tag: Option<&str>,
	) -> Result<Option<MessageId>, SinkError> {
		let mut last_message = reply_to.try_map(|msgid| {
			let dc_msgid = DcMessageId::from(u64::try_from(msgid.0)?);

			Ok::<_, TryFromIntError>(dc_msgid)
		})?;

		let Message {
			title,
			body,
			link,
			media,
		} = msg.clone(); // clone is to be able to include the message if an error happens. TODO: Maybe there's a better solution?

		// if the body of the message won't fit into an embed, then just send as regular messages
		if body.as_ref().map_or(0, |s| s.chars().count()) > MAX_EMBED_DESCIPTION_LEN {
			let mut head = title;

			// add tag as a hashtag on top of the message
			if let Some(tag) = tag {
				let tag = tag.replace(
					|c| match c {
						'_' => false,
						c if c.is_alphabetic() || c.is_ascii_digit() => false,
						_ => true,
					},
					"_",
				);

				head = Some({
					let mut head = head
						// add more padding between tag and title if both are present
						.map(|mut s| {
							s.insert(0, '\n');
							s
						})
						.unwrap_or_default();

					head.insert_str(0, &format!("#{tag}\n"));
					head
				});
			}

			let link = link.map(|s| s.to_string());

			let mut composed_msg = MessageLengthLimiter {
				head: head.as_deref(),
				body: body.as_deref(),
				tail: link.as_deref(),
			};

			while let Some(text) = composed_msg.split_at(MAX_MSG_LEN) {
				let msg = self
					.target
					.send_message(&self.bot, |msg| msg.content(&text))
					.await
					.map_err(|e| SinkError::Discord {
						source: e,
						msg: Box::new(text),
					})?;

				last_message = Some(msg.id);
			}
		}
		// send as an embed (much pretty, so wow!)
		else {
			let msg = self
				.target
				.send_message(&self.bot, |msg| {
					msg.embed(|embed| {
						if let Some(title) = title {
							embed.title(title);
						}

						if let Some(body) = body {
							embed.description(body);
						}

						if let Some(link) = link {
							embed.url(link);
						}

						if let Some(tag) = tag {
							embed.footer(|footer| footer.text(tag));
						}

						if let Some(media) = media {
							for media in media {
								if let Media::Photo(image) = media {
									embed.image(image);
								}
							}
						}

						embed
					})
				})
				.await
				.map_err(|e| SinkError::Discord {
					source: e,
					msg: Box::new(msg),
				})?;

			last_message = Some(msg.id);
		}

		// If it does, we should crash and think of a new solution anyways
		let msgid = last_message.map(|id| i64::try_from(id.0).expect("not sure if Discord will ever return an ID that doesn't fit into MessageId. It shouldn't do that, probably...").into());
		Ok(msgid)
	}
}

impl TargetInner {
	async fn send_message<'a, F>(&self, bot: &Bot, f: F) -> Result<DcMessage, serenity::Error>
	where
		F: for<'b> FnOnce(&'b mut CreateMessage<'a>) -> &'b mut CreateMessage<'a>,
	{
		let msg = match self {
			TargetInner::Channel(chan) => chan.send_message(bot, f).await?,
			TargetInner::User(user) => {
				user.create_dm_channel(bot)
					.await?
					.send_message(bot, f)
					.await?
			}
		};

		Ok(msg)
	}
}