-
-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathcapabilities.rs
More file actions
472 lines (403 loc) · 13.7 KB
/
capabilities.rs
File metadata and controls
472 lines (403 loc) · 13.7 KB
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use std::string::ToString;
use std::sync::LazyLock;
use irc::proto::{self, Tags, command, format};
use crate::message::formatting::{Modifier, update_formatting_with_modifier};
use crate::{Target, User, config, message};
pub static DEFAULT: LazyLock<Capabilities> =
LazyLock::new(Capabilities::default);
// This is not an exhaustive list of IRCv3 capabilities, just the ones that
// Halloy will request when available. When adding new IRCv3 capabilities to
// Halloy they should be added to this enum (Capability), Capability::from_str,
// and Capabilities::create_requested.
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum Capability {
AccountNotify,
AwayNotify,
Batch,
BouncerNetworks,
Chathistory,
Chghost,
EchoMessage,
EventPlayback,
ExtendedJoin,
ExtendedMonitor,
InviteNotify,
LabeledResponse,
MessageTags,
Multiline,
MultiPrefix,
Metadata,
ReadMarker,
Sasl,
ServerTime,
Setname,
UserhostInNames,
}
impl FromStr for Capability {
type Err = &'static str;
fn from_str(cap: &str) -> Result<Self, Self::Err> {
match cap {
"account-notify" => Ok(Self::AccountNotify),
"away-notify" => Ok(Self::AwayNotify),
"batch" => Ok(Self::Batch),
"chghost" => Ok(Self::Chghost),
"draft/chathistory" => Ok(Self::Chathistory),
"draft/event-playback" => Ok(Self::EventPlayback),
"draft/multiline" => Ok(Self::Multiline),
"draft/read-marker" => Ok(Self::ReadMarker),
"echo-message" => Ok(Self::EchoMessage),
"extended-join" => Ok(Self::ExtendedJoin),
"extended-monitor" => Ok(Self::ExtendedMonitor),
"invite-notify" => Ok(Self::InviteNotify),
"labeled-response" => Ok(Self::LabeledResponse),
"message-tags" => Ok(Self::MessageTags),
"multi-prefix" => Ok(Self::MultiPrefix),
"draft/metadata-2" => Ok(Self::Metadata),
"server-time" => Ok(Self::ServerTime),
"setname" => Ok(Self::Setname),
"soju.im/bouncer-networks" => Ok(Self::BouncerNetworks),
"userhost-in-names" => Ok(Self::UserhostInNames),
_ if cap.starts_with("sasl") => Ok(Self::Sasl),
_ => Err("unknown capability"),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct MultilineLimits {
pub max_bytes: usize,
pub max_lines: Option<usize>,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum CapParseError {
#[error(transparent)]
ParseInt(#[from] std::num::ParseIntError),
#[error("Missing key `{0}` in dictionary: {1}")]
MissingKey(String, String),
}
impl FromStr for MultilineLimits {
type Err = CapParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let dictionary = s
.split(',')
.flat_map(|s| s.split_once('='))
.collect::<HashMap<_, _>>();
Ok(MultilineLimits {
max_bytes: dictionary
.get("max-bytes")
.ok_or_else(|| {
CapParseError::MissingKey(
"max-bytes".to_owned(),
s.to_owned(),
)
})?
.parse::<usize>()?,
max_lines: dictionary
.get("max-lines")
.map(|s| s.parse::<usize>())
.transpose()?,
})
}
}
#[derive(Debug, Clone, Copy)]
pub struct MetadataLimits {
pub max_subs: usize,
}
impl FromStr for MetadataLimits {
type Err = CapParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let dictionary = s
.split(',')
.flat_map(|s| s.split_once('='))
.collect::<HashMap<_, _>>();
Ok(MetadataLimits {
max_subs: dictionary
.get("max-subs")
.ok_or_else(|| {
CapParseError::MissingKey(
"max-subs".to_owned(),
s.to_owned(),
)
})?
.parse::<usize>()?,
})
}
}
impl MultilineLimits {
pub fn concat_bytes(
&self,
relay_bytes: usize,
batch_kind: MultilineBatchKind,
target: &str,
) -> usize {
// Message byte limit - relay bytes - space - command - space - target - message separator - crlf
format::BYTE_LIMIT.saturating_sub(
match batch_kind {
MultilineBatchKind::PRIVMSG => 7,
MultilineBatchKind::NOTICE => 6,
} + target.len()
+ relay_bytes
+ 6,
)
}
}
// Forbid splitting inside formatting sequences and attempt to split at spaces
// for better compatibility with clients that don't support multiline.
pub fn multiline_concat_lines(concat_bytes: usize, text: &str) -> Vec<&str> {
let mut lines = Vec::new();
let mut line_start = 0;
let mut last_space = 0;
let mut line_bytes = 0;
let mut modifiers = HashSet::new();
let mut fg = None;
let mut bg = None;
let mut iter = text.chars().peekable();
while let Some(c) = iter.next() {
let sequence_bytes = if let Ok(modifier) = Modifier::try_from(c) {
let (sequence_bytes, comma) = update_formatting_with_modifier(
&mut modifiers,
&mut fg,
&mut bg,
modifier,
&mut iter,
);
// This will prevent breaking a color modifier away from a
// non-modifier, trailing comma; behaves that way solely for
// simplicity's sake
sequence_bytes + comma.map_or(0, char::len_utf8)
} else {
c.len_utf8()
};
if (line_bytes + sequence_bytes) > concat_bytes {
if last_space > line_start {
lines.push(&text[line_start..last_space + ' '.len_utf8()]);
line_bytes -= last_space + ' '.len_utf8() - line_start;
line_start = last_space + ' '.len_utf8();
if line_bytes > concat_bytes {
lines.push(&text[line_start..line_start + line_bytes]);
line_start += line_bytes;
line_bytes = 0;
}
} else {
lines.push(&text[line_start..line_start + line_bytes]);
line_start += line_bytes;
line_bytes = 0;
}
}
if c == ' ' {
last_space = line_start + line_bytes;
}
line_bytes += sequence_bytes;
}
lines.push(&text[line_start..]);
lines
}
pub fn multiline_encoded(
user: Option<&User>,
batch_kind: MultilineBatchKind,
target: &Target,
text: &str,
tags: Tags,
) -> message::Encoded {
let mut encoded = command!(
match batch_kind {
MultilineBatchKind::PRIVMSG => "PRIVMSG",
MultilineBatchKind::NOTICE => "NOTICE",
},
target.as_str(),
text,
);
if let Some(user) = user {
encoded.source = Some(proto::Source::User(proto::User {
nickname: user.nickname().to_string(),
username: user.username().map(ToString::to_string),
hostname: user.hostname().map(ToString::to_string),
}));
}
encoded.tags = tags;
message::Encoded(encoded)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MultilineBatchKind {
PRIVMSG,
NOTICE,
}
#[derive(Debug, Default)]
pub struct Capabilities {
listed: HashMap<String, String>,
pending: HashMap<String, String>,
acknowledged: HashSet<Capability>,
}
impl Capabilities {
pub fn acknowledge(&mut self, caps: impl Iterator<Item = String>) {
for cap in caps {
if let Ok(cap) = Capability::from_str(cap.as_str()) {
self.acknowledged.insert(cap);
}
}
}
pub fn acknowledged(&self, cap: Capability) -> bool {
self.acknowledged.contains(&cap)
}
pub fn create_requested(
&mut self,
config: &config::Server,
) -> Vec<&'static str> {
let mut requested = vec![];
if self.pending.contains_key("invite-notify")
&& !self.acknowledged(Capability::InviteNotify)
{
requested.push("invite-notify");
}
if self.pending.contains_key("userhost-in-names")
&& !self.acknowledged(Capability::UserhostInNames)
{
requested.push("userhost-in-names");
}
if self.pending.contains_key("away-notify")
&& !self.acknowledged(Capability::AwayNotify)
{
requested.push("away-notify");
}
if self.pending.contains_key("message-tags")
&& !self.acknowledged(Capability::MessageTags)
{
requested.push("message-tags");
}
if self.pending.contains_key("server-time")
&& !self.acknowledged(Capability::ServerTime)
{
requested.push("server-time");
}
if self.pending.contains_key("chghost")
&& !self.acknowledged(Capability::Chghost)
{
requested.push("chghost");
}
if self.pending.contains_key("extended-monitor")
&& !self.acknowledged(Capability::ExtendedMonitor)
{
requested.push("extended-monitor");
}
if self.pending.contains_key("account-notify")
|| self.acknowledged(Capability::AccountNotify)
{
if !self.acknowledged(Capability::AccountNotify) {
requested.push("account-notify");
}
if self.pending.contains_key("extended-join")
&& !self.acknowledged(Capability::ExtendedJoin)
{
requested.push("extended-join");
}
}
if self.pending.contains_key("batch")
|| self.acknowledged(Capability::Batch)
{
if !self.acknowledged(Capability::Batch) {
requested.push("batch");
}
// We require batch for chathistory support
if (self.pending.contains_key("draft/chathistory")
&& config.chathistory)
|| self.acknowledged(Capability::Chathistory)
{
if !self.acknowledged(Capability::Chathistory) {
requested.push("draft/chathistory");
}
if self.pending.contains_key("draft/event-playback")
&& !self.acknowledged(Capability::EventPlayback)
{
requested.push("draft/event-playback");
}
}
}
if self.pending.contains_key("labeled-response")
&& !self.acknowledged(Capability::LabeledResponse)
{
requested.push("labeled-response");
}
if self.pending.contains_key("echo-message")
&& !self.acknowledged(Capability::EchoMessage)
{
requested.push("echo-message");
}
if self.pending.contains_key("multi-prefix")
&& !self.acknowledged(Capability::MultiPrefix)
{
requested.push("multi-prefix");
}
if self.pending.contains_key("draft/read-marker")
&& !self.acknowledged(Capability::ReadMarker)
{
requested.push("draft/read-marker");
}
if self.pending.contains_key("setname")
&& !self.acknowledged(Capability::Setname)
{
requested.push("setname");
}
if self.pending.contains_key("soju.im/bouncer-networks")
&& !self.acknowledged(Capability::BouncerNetworks)
{
requested.push("soju.im/bouncer-networks");
}
if self.pending.iter().any(|(cap, _)| cap.starts_with("sasl"))
&& !self.acknowledged(Capability::Sasl)
{
requested.push("sasl");
}
if let Some(multiline) = self.pending.get("draft/multiline")
&& !self.acknowledged(Capability::Multiline)
&& MultilineLimits::from_str(multiline).is_ok()
{
requested.push("draft/multiline");
}
if self.pending.contains_key("draft/metadata-2")
&& !self.acknowledged(Capability::Metadata)
{
requested.push("draft/metadata-2");
}
for (cap, val) in self.pending.drain() {
self.listed.insert(cap, val);
}
requested
}
pub fn delete(&mut self, caps: impl Iterator<Item = String>) {
for cap in caps {
if let Ok(cap) = Capability::from_str(cap.as_str()) {
self.acknowledged.remove(&cap);
}
self.listed.remove(&cap);
}
}
pub fn extend_list<'a>(&mut self, caps: impl Iterator<Item = &'a str>) {
for cap in caps {
if let Some((left, right)) = cap.split_once('=') {
self.pending.insert(left.to_string(), right.to_string());
} else {
self.pending.insert(cap.to_string(), String::new());
}
}
}
pub fn multiline_limits(&self) -> Option<MultilineLimits> {
self.acknowledged(Capability::Multiline)
.then(|| {
MultilineLimits::from_str(self.listed.get("draft/multiline")?)
.ok()
})
.flatten()
}
pub fn metadata_limits(&self) -> Option<MetadataLimits> {
self.acknowledged(Capability::Metadata)
.then(|| {
MetadataLimits::from_str(self.listed.get("draft/metadata-2")?)
.ok()
})
.flatten()
}
pub fn contains_multiline_limits(&self) -> bool {
self.multiline_limits().is_some()
}
}