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
|
use async_trait::async_trait;
use serde::Serialize;
use slog::{debug, info, Logger};
use structopt::StructOpt;
use tsclientlib::{data, ChannelId, ClientId, Connection, Identity, Invoker, MessageTarget};
use xtra::{spawn::Tokio, Actor, Address, Context, Handler, Message, WeakAddress};
use crate::audio_player::{AudioPlayer, AudioPlayerError};
use crate::bot::{BotDisonnected, Connect, MasterBot, Quit};
use crate::command::Command;
use crate::command::VolumeChange;
use crate::playlist::Playlist;
use crate::teamspeak as ts;
use crate::youtube_dl::{self, AudioMetadata};
use ts::TeamSpeakConnection;
#[derive(Debug)]
pub struct ChatMessage {
pub target: MessageTarget,
pub invoker: Invoker,
pub text: String,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize)]
pub enum State {
Playing,
Paused,
Stopped,
EndOfStream,
}
impl Message for State {
type Result = ();
}
impl std::fmt::Display for State {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
State::Playing => write!(fmt, "Playing"),
State::Paused => write!(fmt, "Paused"),
State::Stopped | State::EndOfStream => write!(fmt, "Stopped"),
}?;
Ok(())
}
}
#[derive(Debug)]
pub enum MusicBotMessage {
TextMessage(ChatMessage),
ClientChannel {
client: ClientId,
old_channel: ChannelId,
},
ChannelAdded(ChannelId),
ClientAdded(ClientId),
ClientDisconnected {
id: ClientId,
client: Box<data::Client>,
},
StateChange(State),
}
impl Message for MusicBotMessage {
type Result = Result<(), AudioPlayerError>;
}
pub struct MusicBot {
name: String,
identity: Identity,
player: AudioPlayer,
teamspeak: Option<TeamSpeakConnection>,
master: Option<WeakAddress<MasterBot>>,
playlist: Playlist,
state: State,
logger: Logger,
}
pub struct MusicBotArgs {
pub name: String,
pub master: Option<WeakAddress<MasterBot>>,
pub local: bool,
pub address: String,
pub identity: Identity,
pub channel: String,
pub verbose: u8,
pub logger: Logger,
}
impl MusicBot {
pub async fn spawn(args: MusicBotArgs) -> Address<Self> {
let mut player = AudioPlayer::new(args.logger.clone()).unwrap();
player.change_volume(VolumeChange::Absolute(0.5)).unwrap();
let playlist = Playlist::new(args.logger.clone());
let teamspeak = if args.local {
info!(args.logger, "Starting in CLI mode");
player.setup_with_audio_callback(None).unwrap();
None
} else {
Some(TeamSpeakConnection::new(args.logger.clone()).await.unwrap())
};
let bot = Self {
name: args.name.clone(),
master: args.master,
identity: args.identity.clone(),
player,
teamspeak,
playlist,
state: State::EndOfStream,
logger: args.logger.clone(),
};
let bot_addr = bot.create(None).spawn(&mut Tokio::Global);
info!(
args.logger,
"Connecting";
"name" => &args.name,
"channel" => &args.channel,
"address" => &args.address,
);
let opt = Connection::build(args.address)
.logger(args.logger.clone())
.version(tsclientlib::Version::Linux_3_3_2)
.name(format!("🎵 {}", args.name))
.identity(args.identity)
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3)
.channel(args.channel);
bot_addr.send(Connect(opt)).await.unwrap().unwrap();
bot_addr
.send(MusicBotMessage::StateChange(State::EndOfStream))
.await
.unwrap()
.unwrap();
if args.local {
debug!(args.logger, "Spawning stdin reader thread");
spawn_stdin_reader(bot_addr.downgrade());
}
bot_addr
}
async fn start_playing_audio(&mut self, metadata: AudioMetadata) {
let duration = if let Some(duration) = metadata.duration {
format!("({})", ts::bold(&humantime::format_duration(duration)))
} else {
format!("")
};
self.send_message(format!(
"Playing {} {}",
ts::underline(&metadata.title),
duration
))
.await;
self.set_description(format!("Currently playing '{}'", metadata.title))
.await;
self.player.reset().unwrap();
self.player.set_metadata(metadata).unwrap();
self.player.play().unwrap();
}
pub async fn add_audio(&mut self, url: String, user: String) {
match youtube_dl::get_audio_download_from_url(url, &self.logger).await {
Ok(mut metadata) => {
metadata.added_by = user;
info!(self.logger, "Found source"; "url" => &metadata.url);
self.playlist.push(metadata.clone());
if !self.player.is_started() {
let entry = self.playlist.pop();
if let Some(request) = entry {
self.start_playing_audio(request).await;
}
} else {
let duration = if let Some(duration) = metadata.duration {
format!(" ({})", ts::bold(&humantime::format_duration(duration)))
} else {
format!("")
};
self.send_message(format!(
"Added {}{} to playlist",
ts::underline(&metadata.title),
duration
))
.await;
}
}
Err(e) => {
info!(self.logger, "Failed to find audio url"; "error" => &e);
self.send_message(format!("Failed to find url: {}", e))
.await;
}
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn state(&self) -> State {
self.state
}
pub async fn volume(&self) -> f64 {
self.player.volume()
}
pub async fn current_channel(&mut self) -> Option<ChannelId> {
let ts = self.teamspeak.as_mut().expect("current_channel needs ts");
ts.current_channel().await
}
async fn user_count(&mut self, channel: ChannelId) -> u32 {
let ts = self.teamspeak.as_mut().expect("user_count needs ts");
ts.user_count(channel).await
}
async fn send_message(&mut self, text: String) {
debug!(self.logger, "Sending message to TeamSpeak"; "message" => &text);
if let Some(ts) = &mut self.teamspeak {
ts.send_message_to_channel(text).await;
}
}
async fn set_nickname(&mut self, name: String) {
info!(self.logger, "Setting TeamSpeak nickname"; "name" => &name);
if let Some(ts) = &mut self.teamspeak {
ts.set_nickname(name).await;
}
}
async fn set_description(&mut self, desc: String) {
info!(self.logger, "Setting TeamSpeak description"; "description" => &desc);
if let Some(ts) = &mut self.teamspeak {
ts.set_description(desc).await;
}
}
async fn on_text(&mut self, message: ChatMessage) -> Result<(), AudioPlayerError> {
let msg = message.text;
if msg.starts_with('!') {
let tokens = msg[1..].split_whitespace().collect::<Vec<_>>();
match Command::from_iter_safe(&tokens) {
Ok(args) => self.on_command(args, message.invoker).await?,
Err(e) if e.kind == structopt::clap::ErrorKind::HelpDisplayed => {
self.send_message(format!("\n{}", e.message)).await;
}
_ => (),
}
}
Ok(())
}
async fn on_command(
&mut self,
command: Command,
invoker: Invoker,
) -> Result<(), AudioPlayerError> {
match command {
Command::Play => {
if !self.player.is_started() {
if !self.playlist.is_empty() {
self.player.stop_current()?;
}
} else {
self.player.play()?;
}
}
Command::Add { url } => {
// strip bbcode tags from url
let url = url.replace("[URL]", "").replace("[/URL]", "");
self.add_audio(url.to_string(), invoker.name).await;
}
Command::Search { query } => {
self.add_audio(format!("ytsearch:{}", query.join(" ")), invoker.name)
.await;
}
Command::Pause => {
self.player.pause()?;
}
Command::Stop => {
self.player.reset()?;
}
Command::Seek { amount } => {
if let Ok(time) = self.player.seek(amount) {
self.send_message(format!("New position: {}", ts::bold(&time)))
.await;
} else {
self.send_message(String::from("Failed to seek")).await;
}
}
Command::Next => {
if !self.playlist.is_empty() {
info!(self.logger, "Skipping to next track");
self.player.stop_current()?;
} else {
info!(self.logger, "Playlist empty, cannot skip");
self.player.reset()?;
}
}
Command::Clear => {
self.send_message(String::from("Cleared playlist")).await;
self.playlist.clear();
}
Command::Volume { volume } => {
self.player.change_volume(volume)?;
self.update_name(self.state()).await;
}
Command::Leave => {
self.quit(String::from("Leaving"), true).await.unwrap();
}
}
Ok(())
}
async fn update_name(&mut self, state: State) {
let volume = (self.volume().await * 100.0).round();
let name = match state {
State::EndOfStream => format!("🎵 {} ({}%)", self.name, volume),
_ => format!("🎵 {} - {} ({}%)", self.name, state, volume),
};
self.set_nickname(name).await;
}
async fn on_state(&mut self, new_state: State) -> Result<(), AudioPlayerError> {
if self.state != new_state {
match new_state {
State::EndOfStream => {
self.player.reset()?;
let next_track = self.playlist.pop();
if let Some(request) = next_track {
info!(self.logger, "Advancing playlist");
self.start_playing_audio(request).await;
} else {
self.update_name(new_state).await;
self.set_description(String::new()).await;
}
}
State::Stopped => {
if self.state != State::EndOfStream {
self.update_name(new_state).await;
self.set_description(String::new()).await;
}
}
_ => self.update_name(new_state).await,
}
}
if !(self.state == State::EndOfStream && new_state == State::Stopped) {
self.state = new_state;
}
Ok(())
}
async fn on_message(&mut self, message: MusicBotMessage) -> Result<(), AudioPlayerError> {
match message {
MusicBotMessage::TextMessage(message) => {
if MessageTarget::Channel == message.target {
self.on_text(message).await?;
}
}
MusicBotMessage::ClientChannel {
client: _,
old_channel,
} => {
self.on_client_left_channel(old_channel).await;
}
MusicBotMessage::ClientDisconnected { id: _, client } => {
let old_channel = client.channel;
self.on_client_left_channel(old_channel).await;
}
MusicBotMessage::StateChange(state) => {
self.on_state(state).await?;
}
_ => (),
}
Ok(())
}
// FIXME logs an error if this music bot is the one leaving
async fn on_client_left_channel(&mut self, old_channel: ChannelId) {
let current_channel = match self.current_channel().await {
Some(c) => c,
None => {
return;
}
};
if old_channel == current_channel && self.user_count(current_channel).await <= 1 {
self.quit(String::from("Channel is empty"), true)
.await
.unwrap();
}
}
pub async fn quit(
&mut self,
reason: String,
inform_master: bool,
) -> Result<(), tsclientlib::Error> {
// FIXME logs errors if the bot is playing something because it tries to
// change its name and description
self.player.reset().unwrap();
let ts = self.teamspeak.as_mut().unwrap();
ts.disconnect(&reason).await?;
if inform_master {
if let Some(master) = &self.master {
master
.send(BotDisonnected {
name: self.name.clone(),
identity: self.identity.clone(),
})
.await
.unwrap();
}
}
Ok(())
}
}
#[async_trait]
impl Actor for MusicBot {
async fn started(&mut self, ctx: &mut Context<Self>) {
let addr = ctx.address().unwrap().downgrade();
self.player.register_bot(addr);
}
}
#[async_trait]
impl Handler<Connect> for MusicBot {
async fn handle(
&mut self,
opt: Connect,
ctx: &mut Context<Self>,
) -> Result<(), tsclientlib::Error> {
let addr = ctx.address().unwrap().downgrade();
self.teamspeak
.as_mut()
.unwrap()
.connect_for_bot(opt.0, addr)?;
let mut connection = self.teamspeak.as_ref().unwrap().clone();
let handle = tokio::runtime::Handle::current();
self.player
.setup_with_audio_callback(Some(Box::new(move |samples| {
handle.block_on(connection.send_audio_packet(samples));
})))
.unwrap();
Ok(())
}
}
pub struct GetName;
impl Message for GetName {
type Result = String;
}
#[async_trait]
impl Handler<GetName> for MusicBot {
async fn handle(&mut self, _: GetName, _: &mut Context<Self>) -> String {
self.name().to_owned()
}
}
pub struct GetBotData;
impl Message for GetBotData {
type Result = crate::web_server::BotData;
}
#[async_trait]
impl Handler<GetBotData> for MusicBot {
async fn handle(&mut self, _: GetBotData, _: &mut Context<Self>) -> crate::web_server::BotData {
crate::web_server::BotData {
name: self.name.clone(),
playlist: self.playlist.to_vec(),
currently_playing: self.player.currently_playing(),
position: self.player.position(),
state: self.state(),
volume: self.volume().await,
}
}
}
pub struct GetChannel;
impl Message for GetChannel {
type Result = Option<ChannelId>;
}
#[async_trait]
impl Handler<GetChannel> for MusicBot {
async fn handle(&mut self, _: GetChannel, _: &mut Context<Self>) -> Option<ChannelId> {
self.current_channel().await
}
}
#[async_trait]
impl Handler<Quit> for MusicBot {
async fn handle(&mut self, q: Quit, _: &mut Context<Self>) -> Result<(), tsclientlib::Error> {
self.quit(q.0, false).await
}
}
#[async_trait]
impl Handler<MusicBotMessage> for MusicBot {
async fn handle(
&mut self,
msg: MusicBotMessage,
_: &mut Context<Self>,
) -> Result<(), AudioPlayerError> {
self.on_message(msg).await
}
}
fn spawn_stdin_reader(addr: WeakAddress<MusicBot>) {
use tokio::io::AsyncBufReadExt;
tokio::task::spawn(async move {
let stdin = tokio::io::stdin();
let reader = tokio::io::BufReader::new(stdin);
let mut lines = reader.lines();
while let Some(line) = lines.next_line().await.unwrap() {
let message = MusicBotMessage::TextMessage(ChatMessage {
target: MessageTarget::Channel,
invoker: Invoker {
name: String::from("stdin"),
id: ClientId(0),
uid: None,
},
text: line,
});
addr.send(message).await.unwrap().unwrap();
}
});
}
|