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
|
use std::time::Duration;
use rand::{thread_rng, distributions::{Weighted, WeightedChoice, Distribution}};
use serenity::http::AttachmentType;
use serenity::builder::CreateMessage;
use serenity::framework::standard::Args;
use diesel::PgConnection;
use reqwest::{
Client,
header::{
Headers,
ContentLength,
UserAgent,
Accept,
AcceptEncoding,
Encoding,
qitem,
ContentType,
},
mime
};
use super::*;
use super::playback::CtxExt;
use ::db::*;
use ::{Error, Result};
#[derive(Clone, Copy, Debug)]
enum MemeType {
Text,
Image,
Audio,
}
static mut MEME_WEIGHTS: [Weighted<MemeType>; 3] = [
Weighted { weight: 1, item: MemeType::Text },
Weighted { weight: 1, item: MemeType::Image },
Weighted { weight: 1, item: MemeType::Audio },
];
static mut TTS_WEIGHTS: [Weighted<bool>; 2] = [
Weighted { weight: 4, item: false },
Weighted { weight: 1, item: true }
];
pub fn meme(ctx: &mut Context, msg: &Message, mut args: Args) -> Result<()> {
if args.len_quoted() == 0 {
return rand_meme(ctx, msg);
}
macro_rules! next { () => { args.single_quoted::<String>()?.to_lowercase() }; }
match next!().as_ref() {
"add" => { // e.g.: !thulani meme add title [image IMAGE] [audio|sound AUDIO] [text TEXT...]
let mut new_meme = NewMeme {
title: next!(),
content: None,
image_id: None,
audio_id: None,
metadata_id: 0,
};
let mut headers = Headers::new();
headers.set(AcceptEncoding(vec!(qitem(Encoding::Gzip))));
headers.set(UserAgent::new("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0)"));
headers.set(Accept(vec![
qitem(mime::IMAGE_STAR),
qitem("video/webm".parse().unwrap())
]));
let client = Client::builder()
.default_headers(headers)
.timeout(Duration::from_secs(5))
.build()?;
let conn = connection()?;
while args.len_quoted() > 0 {
info!("args.len_quoted: {}; args: {:?}", args.len_quoted(), args);
match next!().as_ref() {
"text" => {
new_meme.content = Some(args.full().to_owned());
break;
},
"image" => {
if new_meme.image_id.is_some() {
send(msg.channel_id, "ONLY ONE IMAGE YOU FUCK", msg.tts)?;
bail!("user tried to supply more than one image");
}
let mut url = args.single_quoted::<String>()?;
if url.to_lowercase().trim() == "attached" {
let res = msg.attachments.first()
.ok_or::<Error>(::failure::err_msg("no attachments found"))
.and_then(|att| {
let data = att.download()?;
let image_id = Image::create(&conn, &att.filename, data, msg.author.id.0)?;
new_meme.image_id = Some(image_id);
Ok(())
});
if res.is_err() {
send(msg.channel_id, "fix yer gotdang attachments", msg.tts)?;
return res;
}
continue;
}
let resp = client.head(&url).send()?;
if !resp.status().is_success() {
return send(msg.channel_id, "pick a better url next time thanks", msg.tts);
}
let len = resp.headers().get::<ContentLength>()
.map(|ct_len| **ct_len)
.unwrap_or(0);
let content_type_valid = resp.headers().get::<ContentType>()
.map(|ct_type| ct_type.type_() == "image" || (ct_type.type_() == "video" && ct_type.subtype() == "webm"))
.unwrap_or(false);
if len > 20_000_000 || !content_type_valid {
return send(msg.channel_id, "yer pushin me over the fuckin line", msg.tts);
}
let mut resp = client.get(&url).send()?;
if !resp.status().is_success() {
return send(msg.channel_id, "bad link reeeeee", msg.tts);
}
let len = resp.headers().get::<ContentLength>()
.map(|ct_len| **ct_len)
.unwrap_or(0);
let content_type_valid = resp.headers().get::<ContentType>()
.map(|ct_type| ct_type.type_() == "image" || (ct_type.type_() == "video" && ct_type.subtype() == "webm"))
.unwrap_or(false);
if len > 20_000_000 || !content_type_valid {
return send(msg.channel_id, "are ye fuckin serious", msg.tts);
}
let mut data = Vec::with_capacity(len as usize);
::std::io::copy(&mut resp, &mut data)?;
let ext = resp.headers().get::<ContentType>()
.and_then(|typ| ::mime_guess::get_extensions(typ.type_().as_str(), typ.subtype().as_str()))
.and_then(|x| x.first())
.unwrap_or(&"bin");
let filename = format!("{}.{}", new_meme.title, *ext);
let image_id = Image::create(&conn, &filename, data, msg.author.id.0)?;
new_meme.image_id = Some(image_id);
},
"audio" | "sound" => {
let _url = args.single_quoted::<String>()?;
},
_ => {
return send(msg.channel_id, "hueh?", msg.tts);
}
}
}
if new_meme.content.is_none() && new_meme.image_id.is_none() && new_meme.audio_id.is_none() {
return send(msg.channel_id, "hahAA it's empty xdddd", msg.tts);
}
new_meme.save(&conn, msg.author.id.0)?;
send(msg.channel_id, "i hate my job", msg.tts)?
},
"delete" | "remove" => {
send(msg.channel_id, "hwaet", msg.tts)?
},
search => {
let conn = connection()?;
let mem = match find_meme(&conn, search) {
Ok(x) => x,
Err(e) => {
send(msg.channel_id, "what in ryan's name", msg.tts)?;
return Err(e)
},
};
send_meme(ctx, &mem, &conn, msg)?;
}
}
Ok(())
}
fn rand_meme(ctx: &Context, message: &Message) -> Result<()> {
let conn = connection()?;
let should_audio = ctx.currently_playing() && ctx.users_listening()?;
let weights = if should_audio {
unsafe { &mut MEME_WEIGHTS }
} else {
unsafe { &mut MEME_WEIGHTS[..2] }
};
let dist = WeightedChoice::new(weights);
let mut mem = match dist.sample(&mut thread_rng()) {
MemeType::Text => rand_text(&conn),
MemeType::Image => rand_image(&conn),
MemeType::Audio => rand_audio(&conn),
}.map_err(Error::from);
mem = mem
.and_then(|mem| {
let mut mem = mem;
let mut ctr = 0;
while !should_audio && mem.audio_id.is_some() {
mem = rand_text(&conn)?;
ctr += 1;
if ctr > 10 {
send(message.channel_id, "yer listenin to somethin else", message.tts)?;
bail!("looped too many times trying to find a non-audio meme");
}
}
Ok(mem)
});
if let Err(e) = mem {
send(message.channel_id, "i don't know any :(", message.tts)?;
return Err(e);
}
send_meme(ctx, &mem?, &conn, message).map_err(Error::from)
}
fn send_meme(ctx: &Context, t: &Meme, conn: &PgConnection, msg: &Message) -> Result<()> {
debug!("sending meme: {:?}", t);
let image = t.image(conn);
let audio = t.audio(conn);
let dist = WeightedChoice::new(unsafe { &mut TTS_WEIGHTS });
let create_msg = |m: CreateMessage| {
let ret = m
.tts(dist.sample(&mut thread_rng()));
match t.content {
Some(ref text) => ret.content(text),
None => ret
}
};
match image {
Some(image) => {
let image = image?;
msg.channel_id.send_files(vec!(AttachmentType::Bytes((&image.data, &image.filename))), create_msg)?
},
None => msg.channel_id.send_message(create_msg)?,
};
// note: slight edge-case race condition here: there could have been something queued since we
// checked whether anything was playing. not a significant negative impact and unlikely, so i'm
// not worrying about it
if let Some(audio) = audio {
let audio = audio?;
let queue_lock = ctx.data.lock().get::<PlayQueue>().cloned().unwrap();
let mut play_queue = queue_lock.write().unwrap();
play_queue.queue.push_front(PlayArgs{
initiator: msg.author.name.clone(),
data: ::either::Right(audio.data.clone()),
sender_channel: msg.channel_id,
});
}
Ok(())
}
pub fn db_fallback(ctx: &mut Context, msg: &Message, s: &str) -> Result<()> {
Ok(())
}
|