aboutsummaryrefslogtreecommitdiff
path: root/src/commands/meme/create.rs
blob: a4e96565102af4d2d807d1210750e6ad2ddc5e03 (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
use std::process::Stdio;

use anyhow::anyhow;
use diesel::result::Error as DieselError;
use grate::tracing;
use serenity::all::ReactionType;
use tap::Pipe;
use tokio::{
    io::AsyncReadExt,
    process::Command,
};
use url::Url;

use crate::{
    db::{
        connection,
        Audio,
        Image,
        NewMeme,
    },
    parse_times,
    util,
    PoiseContext,
    FFMPEG_COMMAND,
};

/// Add a text/image meme to the db.
#[poise::command(prefix_command, guild_only, category = "memes")]
pub async fn addmeme(
    ctx: PoiseContext<'_>,
    title: String,
    #[rest] text: Option<String>,
) -> anyhow::Result<()> {
    let mut conn = connection().await?;

    let image = util::msg(ctx).and_then(|msg| msg.attachments.first());

    if image.is_none() && text.is_none() {
        tracing::warn!("tried to create non-audio meme with no image or text");

        util::reply(ctx, "hahAA it's empty xdddd").await?;
        return Ok(());
    }

    let mut image_id = None;

    if let Some(att) = image {
        let data = att.download().await?;
        image_id =
            Some(Image::create(&mut conn, &att.filename, data, ctx.author().id.get()).await?);
    };

    let save_result = NewMeme {
        title,
        content: text,
        image_id,
        audio_id: None,
        metadata_id: 0,
    }
    .save(&mut conn, ctx.author().id.get())
    .await
    .map(|_| {});

    use diesel::result::DatabaseErrorKind;
    match save_result {
        Ok(_) => {
            util::react(ctx, '👌').await?;
        },
        Err(e) => {
            if let Some(DieselError::DatabaseError(DatabaseErrorKind::UniqueViolation, _)) =
                e.downcast_ref::<DieselError>()
            {
                tracing::error!("tried to create meme that already exists");

                util::react(ctx, '❌').await?;
                util::reply(ctx, "that meme already exists").await?;

                return Ok(());
            }

            return Err(e.into());
        },
    }

    Ok(())
}

/// Add an audiomeme to the meme db.
#[poise::command(prefix_command, guild_only, category = "memes")]
pub async fn addaudiomeme(
    ctx: PoiseContext<'_>,
    title: String,
    audio_str: String,
    #[rest] text: Option<String>,
) -> anyhow::Result<()> {
    tracing::debug!("running addaudiomeme");

    let elems = audio_str.split_whitespace().collect::<Vec<_>>();

    if elems.is_empty() {
        util::reply(ctx, "are you stupid").await?;
        return Err(anyhow!("no audio link was provided").into());
    }

    let audio_link = Url::parse(elems[0])?;
    let opts = elems[1..].join(" ");
    let (start, end) = parse_times(opts);

    util::react(ctx, '🔃').await?;

    let youtube_url = util::ytdl_url(audio_link.as_str()).await?;
    tracing::debug!("got download url: {youtube_url}");

    let duration_opts = if let Some(e) = end {
        vec![
            "-ss".to_owned(),
            start.map_or_else(
                || "00:00:00".to_owned(),
                |s| {
                    format!(
                        "{:02}:{:02}:{:02}",
                        s.num_hours(),
                        s.num_minutes() % 60,
                        s.num_seconds() % 60
                    )
                },
            ),
            "-to".to_owned(),
            format!("{:02}:{:02}:{:02}", e.num_hours(), e.num_minutes() % 60, e.num_seconds() % 60),
        ]
    } else {
        vec![]
    };

    let ffmpeg_command = Command::new(&*FFMPEG_COMMAND)
        .arg("-i")
        .arg(youtube_url)
        .args(duration_opts)
        .args([
            "-ac", "2", "-ar", "48000", "-f", "opus", "-acodec", "libopus", "-b:a", "96k", "-fs",
            "5M", "-",
        ])
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .stdin(Stdio::null())
        .spawn()?;

    let mut audio_reader = ffmpeg_command.stdout.unwrap();

    let mut conn = connection().await?;

    let image_att =
        util::msg(ctx).and_then(|x| x.attachments.first()).ok_or(anyhow!("no attachment"));

    let mut image_id = None;

    if let Ok(att) = image_att {
        let data = att.download().await?;
        image_id =
            Image::create(&mut conn, &att.filename, data, ctx.author().id.get()).await?.pipe(Some);
    }

    let mut audio_data = Vec::new();
    let bytes = audio_reader.read_to_end(&mut audio_data).await?;
    tracing::debug!("downloaded audio ({} bytes)", audio_data.len());

    if bytes == 0 {
        tracing::debug!("read 0 bytes from audio reader");

        util::unreact(ctx, '🔃').await?;
        util::reply(ctx, "🔇🔇🔇🔕🔕🔕🔕🔕🔇🔕🔕🔇🔕🔕📣📢📣📢📣").await?;
        return Ok(());
    }

    let audio_id = Audio::create(&mut conn, audio_data, ctx.author().id.get()).await?;

    let save_result = NewMeme {
        title,
        content: text,
        image_id,
        audio_id: Some(audio_id),
        metadata_id: 0,
    }
    .save(&mut conn, ctx.author().id.get())
    .await
    .map(|_| {});

    util::unreact(ctx, '🔃').await?;

    use diesel::result::DatabaseErrorKind;
    match save_result {
        Ok(_) => {
            util::react(ctx, ReactionType::Unicode("👌".to_owned())).await?;
        },
        Err(e) => {
            if let Some(DieselError::DatabaseError(DatabaseErrorKind::UniqueViolation, _)) =
                e.downcast_ref::<DieselError>()
            {
                tracing::error!("tried to create meme that already exists");

                util::react(ctx, ReactionType::Unicode("❌".to_owned())).await?;
                util::reply(ctx, "that meme already exists").await?;

                return Ok(());
            }

            return Err(e.into());
        },
    }

    Ok(())
}