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
|
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use poise::serenity_prelude as serenity;
use tokio::sync::oneshot;
use tracing::{debug, warn};
use crate::copyparty::{self, html_decode, percent_decode};
use crate::error::Error;
use crate::Data;
type Context<'a> = poise::Context<'a, Data, Error>;
const MAX_CHOICE_LEN: usize = 99;
/// Maximum time we wait for a fresh search before returning a mock entry.
/// Discord gives 3 seconds; we use 2 to leave room for the API call.
const AC_SEARCH_TIMEOUT: Duration = Duration::from_secs(2);
/// Value used for the mock "searching" placeholder — recognisable by the
/// command handler as a no-op.
const MOCK_SEARCHING: &str = "\u{231B}...";
fn truncate_choice(s: &str) -> String {
if s.chars().count() <= MAX_CHOICE_LEN {
return s.to_string();
}
let mut t: String = s.chars().take(MAX_CHOICE_LEN - 1).collect();
t.push('\u{2026}');
t
}
fn filename_label(raw_path: &str) -> Option<String> {
let raw_name = raw_path.rsplit('/').next()?;
if raw_name.is_empty() {
return None;
}
let decoded = html_decode(&percent_decode(raw_name));
Some(truncate_choice(&decoded))
}
/// Build (label, value) pairs from search hits. Sync because it doesn't stash.
fn build_choices(hits: &[copyparty::SearchHit]) -> Vec<(String, String)> {
let mut out = Vec::new();
for hit in hits {
let rp = match &hit.rp {
Some(p) => p.clone(),
None => continue,
};
let Some(label) = filename_label(&rp) else {
continue;
};
let value = truncate_choice(&rp);
out.push((label, value));
if out.len() >= 25 {
break;
}
}
out
}
/// Stash choices into the per-user ac_cache, then wrap into AutocompleteChoice.
async fn stash_and_wrap(
ctx: Context<'_>,
hits: &[copyparty::SearchHit],
pairs: Vec<(String, String)>,
) -> Vec<serenity::AutocompleteChoice> {
let mut choices = Vec::with_capacity(pairs.len());
for (label, value) in pairs {
// Re-stash into per-user cache so the command handler can resolve
let hit = hits
.iter()
.find(|h| {
h.rp
.as_deref()
.map(|rp| truncate_choice(rp) == value)
.unwrap_or(false)
})
.cloned();
if let Some(h) = hit {
ctx.data()
.ac_stash(ctx.author().id, value.clone(), h)
.await;
}
choices.push(serenity::AutocompleteChoice::new(label, value));
}
choices
}
/// Spawn a single Copyparty search task. Returns a oneshot receiver that will
/// receive the results when the search completes.
///
/// The task always runs to completion even if the receiver is dropped, and
/// writes results into the shared `ac_search_cache` so *future* autocomplete
/// invocations can serve from cache.
type SearchCache = Arc<
tokio::sync::Mutex<HashMap<String, (Vec<copyparty::SearchHit>, std::time::Instant)>>,
>;
fn spawn_search(
cache: SearchCache,
client: copyparty::CopypartyClient,
query: String,
extensions: Vec<String>,
) -> oneshot::Receiver<Vec<copyparty::SearchHit>> {
let (tx, rx) = oneshot::channel();
tokio::spawn(async move {
let exts: Vec<&str> = extensions.iter().map(|s| s.as_str()).collect();
let result = client.search(&query, 25, &exts).await;
match result {
Ok(hits) => {
debug!(%query, count = hits.len(), "background search completed");
// Always fill the shared search cache
cache
.lock()
.await
.insert(query, (hits.clone(), std::time::Instant::now()));
// Send to foreground (ignores error if receiver was dropped)
let _ = tx.send(hits);
}
Err(e) => {
debug!(%query, error = %e, "background search failed");
}
}
});
rx
}
/// Run a Copyparty search with mock fallback and background cache fill.
///
/// 1. Check shared search cache → return instantly if fresh and non-empty.
/// 2. Spawn a *single* search task that always runs to completion.
/// 3. Wait for it up to 2 seconds.
/// 4. On success: stash per-user + return real choices.
/// 5. On timeout: return a mock entry; the background task fills the cache,
/// so the next keystroke's autocomplete will get real results.
async fn timed_search(
ctx: Context<'_>,
partial: &str,
extensions: &[&str],
) -> Vec<serenity::AutocompleteChoice> {
// 1. Shared search cache hit?
if let Some(hits) = ctx.data().ac_search_cache_lookup(partial).await
&& !hits.is_empty() {
debug!(%partial, count = hits.len(), "autocomplete cache hit");
let pairs = build_choices(&hits);
return stash_and_wrap(ctx, &hits, pairs).await;
}
// 2. Spawn ONE search task (survives timeout → fills cache)
let exts: Vec<String> = extensions.iter().map(|s| s.to_string()).collect();
let mut rx = spawn_search(
ctx.data().ac_search_cache.clone(),
ctx.data().copyparty.clone(),
partial.to_string(),
exts,
);
// 3. Wait for the task with a timeout
match tokio::time::timeout(AC_SEARCH_TIMEOUT, &mut rx).await {
Ok(Ok(hits)) => {
debug!(%partial, count = hits.len(), "autocomplete got results in time");
let pairs = build_choices(&hits);
stash_and_wrap(ctx, &hits, pairs).await
}
Ok(Err(_)) => {
warn!(%partial, "autocomplete search task finished without sending (sender dropped)");
vec![]
}
Err(_elapsed) => {
warn!(
%partial,
"autocomplete search timed out after {AC_SEARCH_TIMEOUT:?}, returning mock"
);
// The search task is still running in the background and will fill
// the cache when done. Return a mock so the user sees *something*
// and is prompted to type more → fresh autocomplete → cache hit.
vec![serenity::AutocompleteChoice::new(
format!(
"\u{231B} Szukanie \u{201E}{}\u{201D}\u{2026}",
truncate_choice(partial)
),
MOCK_SEARCHING.to_string(),
)]
}
}
}
pub async fn audio_file(
ctx: Context<'_>,
partial: &str,
) -> Vec<serenity::AutocompleteChoice> {
timed_search(
ctx,
partial,
&["mp3", "wav", "ogg", "flac", "m4a", "opus"],
)
.await
}
pub async fn any_file(ctx: Context<'_>, partial: &str) -> Vec<serenity::AutocompleteChoice> {
timed_search(ctx, partial, &[]).await
}
pub async fn trigger_name(ctx: Context<'_>, partial: &str) -> Vec<String> {
let db_pool = &ctx.data().db_pool;
match crate::database::list_triggers(db_pool).await {
Ok(triggers) => {
let names: Vec<_> = triggers
.into_iter()
.map(|t| t.name)
.filter(|name| partial.is_empty() || name.starts_with(partial))
.take(25)
.collect();
names
}
Err(e) => {
warn!(%partial, error = %e, "autocomplete trigger_name failed");
vec![]
}
}
}
|