aboutsummaryrefslogtreecommitdiff
path: root/src/commands/playback.rs
blob: 21393a288b1a9e83e1191733a241af8ac061edfb (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
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
use either::{
    Left,
    Right,
};
use log::{
    debug,
    error,
    info,
    warn,
};
use serenity::{
    framework::standard::{
        macros::{
            command,
            group,
        },
        Args,
        CommandError,
        CommandResult,
    },
    futures::TryFutureExt,
    model::channel::Message,
    prelude::*,
};
use tap::{
    Conv,
    Pipe,
};

use crate::{
    audio::{
        parse_times,
        PlayArgs,
        PlayQueue,
        VoiceManager,
    },
    commands::sound_levels::*,
    util,
    CONFIG,
};

#[group]
#[commands(skip, pause, resume, list, die, mute, unmute, play, volume)]
#[only_in(guild)]
struct Playback;

pub async fn _play(ctx: &Context, msg: &Message, url: &str) -> CommandResult {
    use url::{
        Host,
        Url,
    };

    debug!("playing '{}'", url);
    if !url.starts_with("http") {
        warn!("got bad url argument to play: {}", url);
        util::send(ctx, msg.channel_id, "bAD LiNk", msg.tts).await?;
        return Ok(());
    }

    let url = match Url::parse(url) {
        Err(e) => {
            error!("bad url: {}", e);
            util::send(ctx, msg.channel_id, "INVALID URL", msg.tts).await?;
            return Ok(());
        },
        Ok(u) => u,
    };

    let host = url.host().and_then(|u| match u {
        Host::Domain(h) => Some(h.to_owned()),
        _ => None,
    });

    if host.map(|h| h.to_lowercase().contains("imgur")).unwrap_or(false) {
        info!("detected imgur link");

        if msg.author.id.get() == 106160362109272064 {
            util::send(ctx, msg.channel_id, "fuck you conway", true).await?;
        } else {
            util::send(ctx, msg.channel_id, "IMGUR IS BAD, YOU TRASH CAN MAN", msg.tts).await?;
        }

        return Ok(());
    }

    let (start, end) = parse_times(&msg.content);

    let queue_lock = ctx.data.write().await.get::<PlayQueue>().cloned().unwrap();
    let mut play_queue = queue_lock.write().unwrap();

    play_queue.general_queue.push_back(PlayArgs {
        initiator: msg.author.name.clone(),
        data: Left(url.conv::<String>()),
        sender_channel: msg.channel_id,
        start,
        end,
    });

    Ok(())
}

#[command]
pub async fn play(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
    if args.len() == 0 {
        return _resume(ctx, msg).await;
    }

    let url = match args.single::<String>() {
        Ok(url) => url,
        Err(e) => {
            error!("unable to parse url from args: {}", e);
            return util::send(ctx, msg.channel_id, "BAD LINK", msg.tts)
                .await
                .map_err(CommandError::from);
        },
    };

    _play(ctx, msg, &url)
}

#[command]
pub async fn pause(ctx: &Context, msg: &Message, _: Args) -> CommandResult {
    let queue_lock = ctx.data.write().await.get::<PlayQueue>().cloned().unwrap();

    let done = || util::send(ctx, msg.channel_id, "r u srs", msg.tts).map_err(CommandError::from);
    let playing = {
        let play_queue = queue_lock.read().unwrap();

        let current_item = match play_queue.playing {
            Some(ref x) => x,
            None => return done().await,
        };

        let audio = current_item.audio.lock();
        audio.playing
    };

    if !playing {
        return done().await;
    }

    {
        let queue = queue_lock.write().unwrap();
        let ref audio = queue.playing.clone().unwrap().audio;
        audio.lock().pause();

        info!("paused playback");
    }

    Ok(())
}

#[command]
#[aliases("continue")]
pub async fn resume(ctx: &Context, msg: &Message, _: Args) -> CommandResult {
    _resume(ctx, msg).await
}

async fn _resume(ctx: &Context, msg: &Message) -> CommandResult {
    let queue_lock = ctx.data.write().await.get::<PlayQueue>().cloned().unwrap();

    let done = || util::send(ctx, msg.channel_id, "r u srs", msg.tts).map_err(CommandError::from);
    let playing = {
        let play_queue = queue_lock.read().unwrap();

        let current_item = match play_queue.playing {
            Some(ref x) => x,
            None => {
                done().await?;
                return Ok(());
            },
        };

        let audio = current_item.audio.lock();
        audio.playing
    };

    if playing {
        done().await?;
        debug!("attempted to resume playback while sound was already playing");
        return Ok(());
    }

    {
        let queue = queue_lock.write().unwrap();
        let ref audio = queue.playing.clone().unwrap().audio;
        audio.lock().play();
        info!("playback resumed");
    }

    Ok(())
}

#[command]
#[aliases("next")]
pub async fn skip(ctx: &Context, _msg: &Message, _args: Args) -> CommandResult {
    let data = ctx.data.write().await;

    let mgr_lock = data.get::<VoiceManager>().cloned().unwrap();
    let mut manager = mgr_lock.lock();

    let queue_lock = data.get::<PlayQueue>().cloned().unwrap();

    if let Some(handler) = manager.get_mut(CONFIG.discord.guild()) {
        handler.stop();
        let mut play_queue = queue_lock.write().unwrap();
        play_queue.playing = None;
        info!("skipped currently-playing audio");
    } else {
        debug!("got skip with no handler attached");
    }

    Ok(())
}

#[command]
#[aliases("sudoku", "fuckoff", "stop")]
pub async fn die(ctx: &Context, msg: &Message, _: Args) -> CommandResult {
    let data = ctx.data.write().await;

    let mgr_lock = data.get::<VoiceManager>().cloned().unwrap();
    let mut manager = mgr_lock.lock();

    let queue_lock = data.get::<PlayQueue>().cloned().unwrap();

    {
        let mut play_queue = queue_lock.write().unwrap();

        play_queue.playing = None;
        play_queue.general_queue.clear();
        play_queue.meme_queue.clear();
    }

    if let Some(handler) = manager.get_mut(CONFIG.discord.guild()) {
        info!("killing playback");
        handler.stop();
        handler.leave();
    } else {
        util::send(ctx, msg.channel_id, "YOU die", msg.tts).await?;
        debug!("got die with no handler attached");
    }

    Ok(())
}

#[command]
#[aliases("queue")]
pub async fn list(ctx: &Context, msg: &Message, _: Args) -> CommandResult {
    let queue_lock = ctx.data.write().await.get::<PlayQueue>().cloned().unwrap();
    let play_queue = queue_lock.read().unwrap();

    let channel = msg.channel(&ctx).await.unwrap().guild().unwrap();

    info!("listing queue");
    match play_queue.playing {
        Some(ref info) => {
            let audio = info.audio.lock();
            let status = if audio.playing {
                "playing"
            } else {
                "paused:"
            };

            let playing_info = match info.init_args.data {
                Left(ref url) => format!(" `{}`", url),
                Right(_) => "memeing".to_owned(),
            };

            util::send(
                ctx,
                msg.channel_id,
                &format!("Currently {} {} ({})", status, playing_info, info.init_args.initiator),
                msg.tts,
            )
            .await?;
        },
        None => {
            debug!("`list` called with no items in queue");
            util::send(ctx, msg.channel_id, "Nothing is playing you meme", msg.tts).await?;
            return Ok(());
        },
    }

    play_queue
        .meme_queue
        .iter()
        .chain(play_queue.general_queue.iter())
        .pipe(serenity::futures::stream::iter)
        .for_each(|info| async move {
            let playing_info = match info.data {
                Left(ref url) => format!("`{}`", url),
                Right(_) => "meme".to_owned(),
            };

            let _ = channel.say(&ctx, &format!("{} ({})", playing_info, info.initiator)).await;
        })
        .await;

    Ok(())
}