-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathchat.rs
1458 lines (1250 loc) · 45 KB
/
chat.rs
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::path::{Path, PathBuf};
use std::pin::{pin, Pin};
use std::sync::Arc;
use std::time;
use anyhow::{anyhow, bail, Context as _, Result};
use async_fuse::Fuse;
use async_injector::{Injector, Key, Provider};
use auth::{Auth, Role, Scope};
use common::backoff;
use common::irc::Tags;
use common::stream::{Stream, StreamExt};
use common::{tags, Channel, Cooldown};
use irc::client::{self, Client};
use irc::proto::command::Command;
use irc::proto::message::{Message, Tag};
use irc::proto::Prefix;
use notify::{recommended_watcher, RecommendedWatcher, Watcher};
use serde::Serialize;
use std::collections::HashSet;
use std::fmt;
use tokio::sync::{mpsc, Notify};
use crate::chat_log;
use crate::command;
use crate::currency_admin;
use crate::idle;
use crate::messages;
use crate::module;
use crate::reward_loop;
use crate::script;
use crate::sender;
use crate::stream_info;
use crate::task;
use crate::utils;
const SERVER: &str = "irc.chat.twitch.tv";
const TWITCH_TAGS_CAP: &str = "twitch.tv/tags";
const TWITCH_COMMANDS_CAP: &str = "twitch.tv/commands";
/// The type of a pending command.
type PendingOutput<'a> = (Result<()>, command::Context<'a>);
type HookOutput<'a> = Result<()>;
/// Helper struct to construct Chat integration.
pub struct Configuration {
user_agent: &'static str,
injector: Injector,
stream_state_tx: mpsc::Sender<stream_info::StreamState>,
restart: Arc<Notify>,
modules: Vec<Box<dyn module::Module>>,
script_dirs: Vec<PathBuf>,
}
impl Configuration {
/// Construct a new chat configuration.
pub fn new(
user_agent: &'static str,
injector: Injector,
stream_state_tx: mpsc::Sender<stream_info::StreamState>,
restart: Arc<Notify>,
) -> Self {
Self {
user_agent,
injector,
stream_state_tx,
restart,
modules: Vec::new(),
script_dirs: Vec::new(),
}
}
/// Add a script directory to watch.
pub fn script_dir<P>(&mut self, script_dir: P)
where
P: AsRef<Path>,
{
self.script_dirs.push(script_dir.as_ref().to_owned());
}
/// Add a module.
pub fn module<M>(&mut self, module: M)
where
M: module::Module,
{
self.modules.push(Box::new(module));
}
#[tracing::instrument(skip_all)]
pub async fn run(self) -> Result<()> {
tracing::trace!("Waiting for everything to be ready");
let mut provider = Setup::provider(&self.injector).await?;
let mut error_backoff = backoff::Exponential::new(time::Duration::from_millis(100));
loop {
let Some(setup) = provider.build() else {
provider.wait().await;
continue;
};
let irc_loop = ChatLoop {
setup,
provider: &mut provider,
irc: &self,
};
match irc_loop.run().await {
Ok(()) => {
error_backoff.reset();
}
Err(e) => {
let backoff = error_backoff.failed();
common::log_error!(e, "Chat component crashed, restarting in {:?}", backoff);
tokio::time::sleep(backoff).await;
continue;
}
}
}
}
}
#[derive(Provider)]
struct Setup {
#[dependency]
db: db::Database,
#[dependency(tag = tags::Twitch::Bot)]
bot: api::TwitchAndUser,
#[dependency(tag = tags::Twitch::Streamer)]
streamer: api::TwitchAndUser,
#[dependency]
auth: Auth,
#[dependency]
bad_words: db::Words,
#[dependency]
message_log: messagelog::MessageLog,
#[dependency]
command_bus: bus::Bus<bus::Command>,
#[dependency]
global_bus: bus::Bus<bus::Global>,
#[dependency]
settings: settings::Settings<::auth::Scope>,
}
struct ChatLoop<'a> {
setup: Setup,
provider: &'a mut SetupProvider,
irc: &'a Configuration,
}
impl ChatLoop<'_> {
async fn run(self) -> Result<()> {
let Self {
setup,
provider,
irc,
} = self;
let Setup {
db,
bot,
streamer,
auth,
bad_words,
message_log,
command_bus,
global_bus,
settings,
} = setup;
let Configuration {
user_agent,
injector,
stream_state_tx,
restart,
modules,
script_dirs,
..
} = irc;
tracing::info!("Starting to chat");
tracing::trace!("Streamer: {:?}", streamer.user.display_name);
tracing::trace!("Bot: {:?}", bot.user.display_name);
let chat_channel = format!("#{}", streamer.user.login);
injector
.update_key(Key::tagged(tags::Globals::Channel)?, chat_channel.clone())
.await;
let access_token = bot.client.token().read().context("missing bot token")?.0;
let irc_client_config = client::data::config::Config {
nickname: Some(bot.user.login.to_string()),
channels: vec![chat_channel.clone()],
password: Some(format!("oauth:{}", access_token.as_str())),
server: Some(String::from(SERVER)),
port: Some(6697),
use_tls: Some(true),
..client::data::config::Config::default()
};
let mut client = Client::from_config(irc_client_config).await?;
client.identify()?;
let chat_settings = settings.scoped("chat");
let url_whitelist_enabled = chat_settings.var("url-whitelist/enabled", true).await?;
let bad_words_enabled = chat_settings.var("bad-words/enabled", false).await?;
let sender_ty = chat_settings.var("sender-type", sender::Type::Chat).await?;
let threshold = chat_settings.var("idle-detection/threshold", 5).await?;
let idle = idle::Idle::new(threshold);
let nightbot = injector.var::<api::NightBot>().await;
let sender =
sender::Sender::new(sender_ty, chat_channel.clone(), client.sender(), nightbot)?;
let (stream_info, stream_info_future) =
stream_info::setup(streamer.clone(), stream_state_tx.clone());
let context_inner = Arc::new(command::ContextInner::new(
sender.clone(),
auth.scope_cooldowns(),
restart.clone(),
));
let refresh_roles_future = refresh_roles(context_inner.clone(), streamer.clone());
let mut handlers = module::Handlers::default();
let channel = Channel::from_string(&streamer.user.login);
let mut scripts = script::load_dir(channel.as_ref(), db.clone(), script_dirs).await?;
let (scripts_watch_tx, mut scripts_watch_rx) = mpsc::unbounded_channel();
let _watcher = if !script_dirs.is_empty() {
let mut watcher: RecommendedWatcher = recommended_watcher(move |e| {
let _ = scripts_watch_tx.send(e);
})?;
for d in script_dirs {
if d.is_dir() {
watcher.watch(d, notify::RecursiveMode::Recursive)?;
}
}
Some(watcher)
} else {
None
};
let mut hook_futures = Vec::new();
for module in modules {
tracing::trace!("Initializing module: {}", module.ty());
let result = module
.hook(module::HookContext {
handlers: &mut handlers,
tasks: &mut hook_futures,
stream_info: &stream_info,
idle: &idle,
streamer: &streamer,
sender: &sender,
settings: &settings,
injector,
})
.await;
result.with_context(|| anyhow!("failed to initialize module: {}", module.ty()))?;
}
let currency_handler = currency_admin::setup(injector).await?;
let reward_loop_future = reward_loop::setup(
streamer.clone(),
sender.clone(),
idle.clone(),
injector.clone(),
chat_settings.clone(),
settings.clone(),
);
let (mut whitelisted_hosts_stream, whitelisted_hosts) = chat_settings
.stream("whitelisted-hosts")
.or_default()
.await?;
let (mut moderator_cooldown_stream, moderator_cooldown) = chat_settings
.stream("moderator-cooldown")
.optional()
.await?;
let (mut api_url_stream, api_url) = settings.stream("remote/api-url").optional().await?;
let mut chat_log_builder = chat_log::Builder::new(
user_agent,
streamer.clone(),
injector,
message_log.clone(),
settings.scoped("chat-log"),
)
.await?;
let (mut commands_stream, commands) = injector.stream().await;
let (mut aliases_stream, aliases) = injector.stream().await;
let mut pong_timeout = Fuse::empty();
let (messages, messages_future) = messages::setup(&settings).await?;
// Join all local tasks we are performing.
common::local_join! {
futures =>
stream_info_future,
refresh_roles_future,
reward_loop_future,
messages_future
}
for future in &mut hook_futures {
futures.push(future.as_mut());
}
// We maintain separate collections of local futures which we add
// potentially user-defined tasks to, to allow them to .await
// concurrently with the main chat task.
let mut pending = common::Futures::default();
let mut hooks = common::Futures::default();
let mut handler = Handler {
streamer: &streamer,
sender: sender.clone(),
whitelisted_hosts,
commands,
bad_words: &bad_words,
global_bus: &global_bus,
aliases,
api_url: Arc::new(api_url),
moderator_cooldown,
handlers: &handlers,
scripts: &mut scripts,
idle: &idle,
pong_timeout: &mut pong_timeout,
bot: &bot,
handler_shutdown: false,
stream_info: &stream_info,
auth: &auth,
currency_handler: ¤cy_handler,
url_whitelist_enabled,
bad_words_enabled,
chat_log: chat_log_builder.build()?,
messages: &messages,
context_inner: &context_inner,
};
let mut outgoing = client
.outgoing()
.ok_or_else(|| anyhow!("missing outgoing future for irc client"))?;
let mut client_stream = client.stream()?;
let mut ping_interval = tokio::time::interval(time::Duration::from_secs(10));
let mut commands = command_bus.subscribe();
let mut leave = pin!(Fuse::empty());
let sender = handler.sender.clone();
// Things to do when joining.
let mut join_task = pin!(Fuse::new(async {
sender.cap_req(TWITCH_TAGS_CAP).await;
sender.cap_req(TWITCH_COMMANDS_CAP).await;
if let Some(m) = messages.try_get(messages::JOIN_CHAT).await {
sender.privmsg_immediate(m);
}
}));
while leave.is_empty() {
tokio::select! {
_ = &mut join_task => {
tracing::trace!("Done sending capabilities request and join message");
}
Some(ev) = scripts_watch_rx.recv() => {
if let Ok(ev) = ev {
if let Err(e) = handler.handle_script_filesystem_event(ev) {
common::log_error!(e, "Failed to handle script filesystem event");
}
}
}
command = commands.recv() => {
let command = command?;
match command {
bus::Command::Raw { command } => {
tracing::trace!("Raw command: {}", command);
if let Err(e) = handler.raw(command, &mut pending, &mut hooks).await {
common::log_error!(e, "Failed to handle message");
}
}
}
}
Some(future) = futures.next() => {
match future {
Ok(..) => {
tracing::warn!("Chat component exited, exiting...");
return Ok(());
}
Err(e) => {
common::log_warn!(e, "Chat component errored, restarting in 5 seconds");
tokio::time::sleep(time::Duration::from_secs(5)).await;
return Ok(());
}
}
}
_ = provider.wait_for_update() => {
// If configuration state changes, force a reconnect.
leave.set(Fuse::new(tokio::time::sleep(time::Duration::from_secs(1))));
}
commands = commands_stream.recv() => {
handler.commands = commands;
}
aliases = aliases_stream.recv() => {
handler.aliases = aliases;
}
chat_log = chat_log_builder.update() => {
handler.chat_log = chat_log?;
}
api_url = api_url_stream.recv() => {
handler.api_url = Arc::new(api_url);
}
moderator_cooldown = moderator_cooldown_stream.recv() => {
handler.moderator_cooldown = moderator_cooldown;
}
_ = ping_interval.tick() => {
handler.send_ping()?;
}
_ = &mut *handler.pong_timeout => {
bail!("Server not responding");
}
update = whitelisted_hosts_stream.recv() => {
handler.whitelisted_hosts = update;
},
message = client_stream.next() => {
if let Some(m) = message.transpose()? {
if let Err(e) = handler.handle(m, &mut pending, &mut hooks).await {
common::log_error!(e, "Failed to handle message");
}
}
if handler.handler_shutdown {
bail!("handler forcibly shut down");
}
}
Some(result) = pending.next(), if !pending.is_empty() => {
if let (Err(error), ctx) = result {
if let Some(respond) = error.downcast_ref::<crate::RespondErr>() {
if let crate::RespondErr::Message(respond) = respond {
respond!(ctx, respond);
}
} else {
respond!(ctx, "Sorry, something went wrong :(");
common::log_error!(error, "Error when processing command");
}
}
}
Some(result) = hooks.next(), if !hooks.is_empty() => {
if let Err(error) = result {
common::log_error!(error, "Hooks failed to run");
}
}
_ = &mut outgoing => {
bail!("Outgoing future ended unexpectedly");
}
_ = &mut leave => {
break;
}
}
}
if let Some(m) = handler.messages.try_get(messages::LEAVE_CHAT).await {
handler.sender.privmsg_immediate(m);
}
tokio::select! {
_ = outgoing => {
bail!("outgoing future ended unexpectedly");
}
_ = leave => {
}
}
Ok(())
}
}
/// Handler for incoming messages.
struct Handler<'a> {
/// Current Streamer.
streamer: &'a api::TwitchAndUser,
/// Queue for sending messages.
sender: sender::Sender,
/// Whitelisted hosts for links.
whitelisted_hosts: HashSet<String>,
/// All registered commands.
commands: Option<db::Commands>,
/// Bad words.
bad_words: &'a db::Words,
/// For sending notifications.
global_bus: &'a bus::Bus<bus::Global>,
/// Aliases.
aliases: Option<db::Aliases>,
/// Configured API URL.
api_url: Arc<Option<String>>,
/// Active moderator cooldown.
moderator_cooldown: Option<Cooldown>,
/// Handlers for specific commands like `!skip`.
handlers: &'a module::Handlers,
/// Dynamic handlers.
scripts: &'a mut script::Scripts,
/// Build idle detection.
idle: &'a idle::Idle,
/// Pong timeout currently running.
pong_timeout: &'a mut Fuse<Pin<Box<tokio::time::Sleep>>>,
/// OAuth 2.0 Token used to authenticate with Chat.
bot: &'a api::TwitchAndUser,
/// Force a shutdown.
handler_shutdown: bool,
/// Stream information.
stream_info: &'a stream_info::StreamInfo,
/// Information about auth.
auth: &'a Auth,
/// Handler for currencies.
currency_handler: &'a currency_admin::Handler,
bad_words_enabled: settings::Var<bool>,
url_whitelist_enabled: settings::Var<bool>,
/// Handler for chat logs.
chat_log: Option<chat_log::ChatLog>,
/// Messages.
messages: &'a messages::Messages,
/// Shared context paramters.
pub(crate) context_inner: &'a Arc<command::ContextInner>,
}
impl Handler<'_> {
/// Handle filesystem event.
fn handle_script_filesystem_event(&mut self, ev: notify::Event) -> Result<()> {
use notify::event::{CreateKind, EventKind::*, ModifyKind, RemoveKind, RenameMode};
tracing::trace!("Filesystem event: {:?}", ev);
let kind = match ev.kind {
Create(CreateKind::File) => Kind::Load,
Create(CreateKind::Any) => Kind::Load,
Modify(ModifyKind::Data(..)) => Kind::Load,
Modify(ModifyKind::Name(RenameMode::From)) => Kind::Remove,
Modify(ModifyKind::Name(RenameMode::To)) => Kind::Load,
Modify(ModifyKind::Any) => Kind::Load,
Remove(RemoveKind::File) => Kind::Remove,
Remove(RemoveKind::Any) => Kind::Remove,
_ => return Ok(()),
};
match kind {
Kind::Load => {
for p in &ev.paths {
tracing::info!("Loading script: {}", p.display());
let p = p.canonicalize()?;
if let Err(e) = self.scripts.reload(&p) {
common::log_error!(e, "Failed to reload: {}", p.display());
}
}
}
Kind::Remove => {
for p in &ev.paths {
tracing::info!("Unloading script: {}", p.display());
let p = p.canonicalize()?;
self.scripts.unload(&p);
}
}
}
return Ok(());
#[derive(Debug, Clone, Copy)]
enum Kind {
Load,
Remove,
}
}
}
/// Handle a command.
async fn process_command<'a>(
command: &str,
mut ctx: command::Context<'a>,
global_bus: &'a bus::Bus<bus::Global>,
currency_handler: &'a currency_admin::Handler,
handlers: &'a module::Handlers,
scripts: &script::Scripts,
pending: &mut common::Futures<'a, PendingOutput<'a>>,
) -> Result<()> {
match command {
"ping" => {
respond!(ctx, "What do you want?");
global_bus.send(bus::Global::Ping).await;
}
other => {
tracing::trace!("Testing command: {}", other);
// TODO: store currency name locally to match against.
let currency_command = currency_handler.command_name().await;
let handler = match (other, currency_command) {
(other, Some(name)) if other == name.as_ref() => {
Some(currency_handler as &dyn command::Handler)
}
(other, Some(..)) | (other, None) => handlers.get(other),
};
if let Some(handler) = handler {
let scope = handler.scope();
tracing::info! {
?scope,
roles = ?ctx.user.roles(),
principal = ?ctx.user.principal(),
"Testing handler scope"
};
// Test if user has the required scope to run the given
// command.
if let Some(scope) = scope {
if !ctx.user.has_scope(scope).await {
if ctx.user.is_moderator() {
let m = ctx.messages.get(messages::AUTH_FAILED).await;
ctx.respond(m).await;
} else {
let m = ctx.messages.get(messages::AUTH_FAILED_RUDE).await;
ctx.respond(m).await;
}
return Ok(());
}
}
pending.push(Box::pin(async move {
let result = handler.handle(&mut ctx).await;
(result, ctx)
}));
return Ok(());
}
if let Some(handler) = scripts.get(other) {
if let Err(e) = handler.call(ctx.clone()).await {
ctx.respond("Sorry, something went wrong :(").await;
common::log_error!(e, "Error when processing command");
}
return Ok(());
}
}
}
Ok(())
}
impl<'a> Handler<'a> {
/// Delete the given message.
fn delete_message(&self, user: &User) -> Result<()> {
let id = match &user.inner.tags.id {
Some(id) => id,
None => return Ok(()),
};
tracing::info!("Attempting to delete message: {}", id);
user.inner.sender.delete(id);
Ok(())
}
/// Test if the message should be deleted.
async fn should_be_deleted(&self, user: &User, message: &str) -> bool {
// Moderators can say whatever they want.
if user.is_moderator() {
return false;
}
if self.bad_words_enabled.load().await {
if let Some(word) = self.test_bad_words(message).await {
if let Some(why) = word.why.as_ref() {
let why = why.render_to_string(BadWordsVars {
name: user.display_name(),
target: &self.streamer.user.login,
});
match why {
Ok(why) => {
self.sender.privmsg(&why).await;
}
Err(e) => {
common::log_error!(e, "Failed to render response");
}
}
}
return true;
}
}
if !user.has_scope(Scope::ChatBypassUrlWhitelist).await
&& self.url_whitelist_enabled.load().await
&& self.has_bad_link(message)
{
return true;
}
false
}
/// Test the message for bad words.
async fn test_bad_words(&self, message: &str) -> Option<Arc<db::Word>> {
let tester = self.bad_words.tester().await;
for word in common::words::trimmed(message) {
if let Some(word) = tester.test(word) {
return Some(word);
}
}
None
}
/// Check if the given iterator has URLs that need to be
fn has_bad_link(&self, message: &str) -> bool {
for url in utils::Urls::new(message) {
if let Some(host) = url.host_str() {
if !self.whitelisted_hosts.contains(host) {
return true;
}
}
}
false
}
/// Send a ping to the remote server.
fn send_ping(&mut self) -> Result<()> {
self.sender
.send_immediate(Command::PING(String::from(SERVER), None));
self.pong_timeout
.set(Box::pin(tokio::time::sleep(time::Duration::from_secs(5))));
Ok(())
}
/// Process the given command.
pub(crate) async fn process_message(
&mut self,
user: &User,
mut message: Arc<String>,
pending: &mut common::Futures<'a, PendingOutput<'a>>,
hooks: &mut common::Futures<'a, HookOutput<'a>>,
) -> Result<()> {
// Run message hooks.
hooks.push({
let user = user.clone();
let context_inner = self.context_inner;
let message = message.clone();
Box::pin(async move {
let message_hooks = context_inner.message_hooks.read().await;
for (key, hook) in &*message_hooks {
if let Err(e) = hook.peek(&user, &message).await {
common::log_error!(e, "Hook `{}` failed", key);
}
}
Ok(())
})
});
// only non-moderators and non-streamer bumps the idle counter.
if !user.is_streamer() {
self.idle.seen();
}
// NB: declared here to be in scope.
let mut seen = HashSet::new();
let mut path = Vec::new();
if let Some(aliases) = self.aliases.as_ref() {
tracing::trace!(?message, channel = ?user.sender().channel(), "Resolving aliases");
while let Some((key, next)) = aliases
.resolve(user.sender().channel(), message.clone())
.await
{
path.push(key.to_string());
if !seen.insert(key.clone()) {
tracing::error!(?message, ?path, "Recursion found in alias expansion");
respond!(
user,
"Recursion found in alias expansion: {} :(",
path.join(" -> ")
);
return Ok(());
}
tracing::trace!(?message, ?next, "Resolved alias");
message = Arc::new(next);
}
}
let mut it = common::words::split(message.clone());
let first = it.next();
if let Some(commands) = self.commands.as_ref() {
if let Some((command, captures)) = commands
.resolve(user.sender().channel(), first.as_deref(), &it)
.await
{
if command.has_var("count") {
commands.increment(&command).await?;
}
let vars = CommandVars {
name: user.display_name(),
target: &self.streamer.user.login,
count: command.count(),
captures,
};
let response = command.render(&vars)?;
self.sender.privmsg(response).await;
}
}
if let Some(command) = first {
if let Some(command) = command.strip_prefix('!') {
let ctx = command::Context {
api_url: self.api_url.clone(),
user: user.clone(),
it,
messages: self.messages,
inner: self.context_inner,
};
let result = process_command(
command,
ctx,
self.global_bus,
self.currency_handler,
self.handlers,
self.scripts,
pending,
)
.await;
if let Err(e) = result {
common::log_error!(e, "Failed to process command");
}
}
}
if self.should_be_deleted(user, &message).await {
self.delete_message(user)?;
}
Ok(())
}
/// Run the given raw command.
pub(crate) async fn raw(
&mut self,
message: String,
pending: &mut common::Futures<'a, PendingOutput<'a>>,
hook: &mut common::Futures<'a, HookOutput<'a>>,
) -> Result<()> {
let tags = Tags::default();
let user = User {
inner: Arc::new(UserInner {
tags,
sender: self.sender.clone(),
principal: Principal::Injected,
streamer_login: self.streamer.user.login.clone(),
stream_info: self.stream_info.clone(),
auth: self.auth.clone(),
context: self.context_inner.clone(),
}),
};
self.process_message(&user, Arc::new(message), pending, hook)
.await?;
Ok(())
}
/// Handle the given command.
#[tracing::instrument(skip_all)]
pub(crate) async fn handle(
&mut self,
m: Message,
pending: &mut common::Futures<'a, PendingOutput<'a>>,
hooks: &mut common::Futures<'a, HookOutput<'a>>,
) -> Result<()> {
match m.command {
Command::PRIVMSG(_, message) => {
let message = Arc::new(message);
let tags = Tags::from_tags(m.tags.iter().flat_map(|tag| {
tag.iter().flat_map(|tag| match tag {
Tag(key, Some(value)) => Some((key, value)),
_ => None,
})
}));
let Some(Prefix::Nickname(login, _, _)) = m.prefix else {
bail!("Missing nickname");
};
let login = Box::<str>::from(login);
if let Some(chat_log) = self.chat_log.as_ref().cloned() {
let tags = tags.clone();
let user = self.streamer.user.clone();
let login = login.clone();
let message = message.clone();
task::spawn(Box::pin(async move {
chat_log.observe(&tags, &user, &login, &message).await;
Ok(())
}));
}
let user = User {
inner: Arc::new(UserInner {
tags,
sender: self.sender.clone(),
principal: Principal::User { login },
streamer_login: self.streamer.user.login.clone(),
stream_info: self.stream_info.clone(),
auth: self.auth.clone(),
context: self.context_inner.clone(),
}),
};
self.process_message(&user, message, pending, hooks).await?;
}
Command::JOIN(channel, _, _) => {
let user = match &m.prefix {
Some(Prefix::Nickname(user, _, _)) => user,
_ => "?",
};
tracing::trace!("{} joined {}", user, channel);
}
Command::PING(server, other) => {
tracing::trace!("Received PING, responding with PONG");
self.sender.send_immediate(Command::PONG(server, other));
}
Command::PONG(..) => {
tracing::trace!("Received PONG, clearing PING timeout");
self.pong_timeout.clear();
}
Command::NOTICE(_, message) => {
let tags = Tags::from_tags(m.tags.iter().flat_map(|tag| {
tag.iter().flat_map(|tag| match tag {
Tag(key, Some(value)) => Some((key, value)),
_ => None,
})
}));
match tags.msg_id.as_deref() {
_ if message == "Login authentication failed" => {
tracing::trace!("Authentication failed");
self.bot.client.token().force_refresh();
self.handler_shutdown = true;
}
msg_id => {
tracing::trace!(?msg_id, message, "Unhandled notice");
}
}
}
Command::Response(response, tail) => {
tracing::trace!(?response, ?tail, "Response");
}
Command::Raw(raw, tail) => match raw.as_str() {
"CLEARMSG" => {
if let Some(chat_log) = self.chat_log.as_ref() {