-
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathmap.rs
More file actions
650 lines (547 loc) · 21 KB
/
map.rs
File metadata and controls
650 lines (547 loc) · 21 KB
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
use std::fmt::Write;
use bathbot_macros::PaginationBuilder;
use bathbot_util::{
AuthorBuilder, Authored, CowUtils, EmbedBuilder, FooterBuilder, MessageOrigin, attachment,
constants::{AVATAR_URL, OSU_BASE},
datetime::SecToMinSec,
fields,
modal::{ModalBuilder, TextInputBuilder},
numbers::{WithComma, round},
};
use eyre::{ContextCompat, Result, WrapErr};
use rosu_pp::{
Difficulty,
any::hitresult_generator::{Closest, Composable, Fast},
};
use rosu_v2::prelude::{
BeatmapExtended, BeatmapsetExtended, GameMode, GameModsIntermode, Username,
};
use twilight_model::{
channel::message::{
Component,
component::{ActionRow, Button, ButtonStyle},
},
id::{Id, marker::UserMarker},
};
use crate::{
active::{
BuildPage, ComponentResult, IActiveMessage,
pagination::{Pages, handle_pagination_component},
},
commands::osu::CustomAttrs,
core::Context,
manager::redis::osu::UserArgs,
util::{
Emote, ModalExt,
interaction::{InteractionComponent, InteractionModal},
},
};
#[derive(PaginationBuilder)]
pub struct MapPagination {
mapset: BeatmapsetExtended,
#[pagination(per_page = 1)]
maps: Box<[BeatmapExtended]>,
mods: GameModsIntermode,
attrs: CustomAttrs,
origin: MessageOrigin,
content: Box<str>,
msg_owner: Id<UserMarker>,
pages: Pages,
}
impl IActiveMessage for MapPagination {
async fn build_page(&mut self) -> Result<BuildPage> {
let map = &self.maps[self.pages.index()];
let mut title = String::with_capacity(32);
if map.mode == GameMode::Mania {
let _ = write!(title, "[{}K] ", map.cs as u32);
}
let _ = write!(
title,
"{} - {}",
self.mapset.artist.as_str().cow_escape_markdown(),
self.mapset.title.as_str().cow_escape_markdown()
);
#[cfg(not(feature = "server"))]
let url = "https://www.google.com";
#[cfg(feature = "server")]
let url = &crate::core::BotConfig::get().server.public_url;
let download_value = format!(
"[osu!direct]({url}/osudirect/{mapset_id})\n\
[catboy.best](https://catboy.best/d/{mapset_id})\n\
[osu.direct](https://osu.direct/d/{mapset_id})\n\
[nerinyan.moe](https://api.nerinyan.moe/d/{mapset_id})",
mapset_id = map.mapset_id,
);
let mut seconds_total = map.seconds_total;
let mut seconds_drain = map.seconds_drain;
let mut bpm = map.bpm as f64;
let clock_rate = match (self.attrs.bpm, self.attrs.clock_rate) {
(None, None) => self.mods.legacy_clock_rate(),
(_, Some(clock_rate)) => clock_rate,
(Some(new_bpm), None) => {
let old_bpm = map.bpm;
(new_bpm / old_bpm) as f64
}
};
seconds_total = (seconds_total as f64 / clock_rate) as u32;
seconds_drain = (seconds_drain as f64 / clock_rate) as u32;
bpm *= clock_rate;
let mut info_value = String::with_capacity(128);
let mut fields = Vec::with_capacity(3);
let map_manager = Context::osu_map();
let map_fut = map_manager.pp_map(map.map_id);
let creator_fut = creator_name(map, &self.mapset);
let (map_res, gd_creator) = tokio::join!(map_fut, creator_fut);
let mut rosu_map = map_res.wrap_err("Failed to get pp map")?;
if let Some(ar_) = self.attrs.ar {
rosu_map.ar = ar_ as f32;
}
if let Some(cs_) = self.attrs.cs {
rosu_map.cs = cs_ as f32;
}
if let Some(hp_) = self.attrs.hp {
rosu_map.hp = hp_ as f32;
}
if let Some(od_) = self.attrs.od {
rosu_map.od = od_ as f32;
}
let map_attrs = rosu_map
.attributes()
.mods(&self.mods)
.clock_rate(clock_rate)
.build();
const ACCS: [f32; 4] = [95.0, 97.0, 99.0, 100.0];
let mut pps = Vec::with_capacity(ACCS.len());
let stars = if rosu_map.check_suspicion().is_ok() {
let mut attrs = Difficulty::new()
.mods(&self.mods)
.clock_rate(clock_rate)
.calculate(&rosu_map);
for &acc in ACCS.iter() {
let pp_result = attrs
.performance()
.mods(&self.mods)
.accuracy(acc as f64)
.clock_rate(clock_rate)
.hitresult_generator::<Composable<Closest, Closest, Closest, Fast>>()
.calculate();
let pp = pp_result.pp();
let pp_str = if pp > 100_000.0 {
format!("{pp:.3e}")
} else {
round(pp as f32).to_string()
};
pps.push(pp_str);
attrs = pp_result.into();
}
attrs.stars()
} else {
for _ in ACCS.iter() {
pps.push("0".to_owned());
}
0.0
};
let mut pp_values = String::with_capacity(128);
let mut lens = Vec::with_capacity(ACCS.len());
pp_values.push_str("```ansi\nAcc ");
for (pp, &acc) in pps.iter().zip(&ACCS) {
let acc = acc.to_string() + "%";
let len = pp.len().max(acc.len()) + 2;
let _ = write!(pp_values, "|{acc:^len$}");
lens.push(len);
}
pp_values.push_str("\n----");
for len in lens.iter() {
let _ = write!(pp_values, "+{:->len$}", "-");
}
pp_values.push_str("\n PP ");
let bold = "\u{001b}[1m";
let reset = "\u{001b}[0m";
for (pp, len) in pps.iter().zip(&lens) {
let _ = write!(pp_values, "|{bold}{pp:^len$}{reset}");
}
pp_values.push_str("\n```");
if let Some(combo) = map.max_combo {
let _ = write!(info_value, "Combo: `{combo}x`");
}
let _ = writeln!(
info_value,
" Stars: [`{stars:.2}★`]({origin} \"{stars}\")",
origin = self.origin
);
let _ = write!(info_value, "Length: `{}` ", SecToMinSec::new(seconds_total));
if seconds_drain != seconds_total {
let _ = write!(info_value, "(`{}`) ", SecToMinSec::new(seconds_drain));
}
let _ = write!(
info_value,
"BPM: `{}` Objects: `{}`\nCS: `{}` AR: `{}` OD: `{}` HP: `{}` Spinners: `{}`",
round(bpm as f32),
map.count_circles + map.count_sliders + map.count_spinners,
round(map_attrs.cs as f32),
round(map_attrs.ar as f32),
round(map_attrs.od as f32),
round(map_attrs.hp as f32),
map.count_spinners,
);
let mut info_name = format!(
"{mode} __[{version}]__",
mode = Emote::from(map.mode),
version = map.version.as_str().cow_escape_markdown()
);
if !self.mods.is_empty() {
let _ = write!(info_name, " +{}", self.mods);
}
fields![fields {
info_name, info_value, true;
"Download", download_value, true;
}];
let mut field_name = format!(
":heart: {} :play_pause: {} | {:?}, {:?}",
WithComma::new(self.mapset.favourite_count),
WithComma::new(self.mapset.playcount),
self.mapset.language.expect("no language in mapset"),
self.mapset.genre.expect("no genre in mapset"),
);
if self.mapset.nsfw {
field_name.push_str(" :underage: NSFW");
}
fields![fields { field_name, pp_values, false }];
let (date_text, timestamp) = if let Some(ranked_date) = self.mapset.ranked_date {
(format!("{:?}", map.status), ranked_date)
} else {
("Last updated".to_owned(), map.last_updated)
};
let mut author_text = format!("Created by {}", self.mapset.creator_name);
if let Some(gd_creator) = gd_creator {
let _ = write!(author_text, " (guest difficulty by {gd_creator})");
}
let author_icon = self.mapset.creator.as_ref().map_or_else(
|| format!("{AVATAR_URL}{}", self.mapset.creator_id),
|creator| creator.avatar_url.to_owned(),
);
let author = AuthorBuilder::new(author_text)
.url(format!("{OSU_BASE}u/{}", self.mapset.creator_id))
.icon_url(author_icon);
let page = self.pages.curr_page();
let pages = self.pages.last_page();
let footer_text = format!("Map {page} out of {pages} in the mapset, {date_text}");
let footer = FooterBuilder::new(footer_text);
let image = attachment("map_graph.png");
let mut description = format!(
":musical_note: [Song preview](https://b.ppy.sh/preview/{mapset_id}.mp3) \
:frame_photo: [Full background](https://catboy.best/preview/background/{mapset_id}/set)",
mapset_id = self.mapset.mapset_id
);
match map.mode {
GameMode::Osu => {
let mut base_url = format!(
"https://preview.tryz.id.vn/?b={map_id}",
map_id = map.map_id
);
// preview.tryz.id supports only DT, HR and HD but it
// checks for them by simply `string.includes(two symbol acronym)`
// so it's safe to just dump all the mods if any present
// ^ https://github.com/FukutoTojido/beatmap-viewer-web/blob/058382c1069b2dfb4fdce4aae16220bddb80b452/src/app/Config/ExperimentalConfig.ts#L23-L34
if !self.mods.is_empty() {
let _ = write!(base_url, "&m={}", self.mods);
}
let _ = write!(description, " :clapper: [Map preview]({base_url})",);
}
GameMode::Mania | GameMode::Taiko => {
let _ = write!(
description,
" :clapper: [Map preview](https://osu-preview.jmir.xyz/preview#{map_id})",
map_id = map.map_id
);
}
// Waiting on a preview website that supports catch
GameMode::Catch => {}
}
let embed = EmbedBuilder::new()
.author(author)
.description(description)
.fields(fields)
.footer(footer)
.image(image)
.timestamp(timestamp)
.title(title)
.url(map.url.as_str());
let build = BuildPage::new(embed, true).content(self.content.clone());
Ok(build)
}
fn build_components(&self) -> Vec<Component> {
let mods = Button {
custom_id: Some("map_mods".to_owned()),
disabled: false,
emoji: None,
label: Some("Mods".to_owned()),
style: ButtonStyle::Primary,
url: None,
sku_id: None,
};
let clock_rate = Button {
custom_id: Some("map_clock_rate".to_owned()),
disabled: false,
emoji: None,
label: Some("Clock rate".to_owned()),
style: ButtonStyle::Primary,
url: None,
sku_id: None,
};
let attrs = Button {
custom_id: Some("map_attrs".to_owned()),
disabled: false,
emoji: None,
label: Some("Attributes".to_owned()),
style: ButtonStyle::Primary,
url: None,
sku_id: None,
};
let top: Component = Component::ActionRow(ActionRow {
components: vec![mods, clock_rate, attrs]
.into_iter()
.map(Component::Button)
.collect(),
});
let pages = if self.pages.last_index() == 0 {
None
} else {
let jump_start = Button {
custom_id: Some("pagination_start".to_owned()),
disabled: self.pages.index() == 0,
emoji: Some(Emote::JumpStart.reaction_type()),
label: None,
style: ButtonStyle::Secondary,
url: None,
sku_id: None,
};
let single_step_back = Button {
custom_id: Some("pagination_back".to_owned()),
disabled: self.pages.index() == 0,
emoji: Some(Emote::SingleStepBack.reaction_type()),
label: None,
style: ButtonStyle::Secondary,
url: None,
sku_id: None,
};
let jump_custom = Button {
custom_id: Some("pagination_custom".to_owned()),
disabled: false,
emoji: Some(Emote::MyPosition.reaction_type()),
label: None,
style: ButtonStyle::Secondary,
url: None,
sku_id: None,
};
let single_step = Button {
custom_id: Some("pagination_step".to_owned()),
disabled: self.pages.index() == self.pages.last_index(),
emoji: Some(Emote::SingleStep.reaction_type()),
label: None,
style: ButtonStyle::Secondary,
url: None,
sku_id: None,
};
let jump_end = Button {
custom_id: Some("pagination_end".to_owned()),
disabled: self.pages.index() == self.pages.last_index(),
emoji: Some(Emote::JumpEnd.reaction_type()),
label: None,
style: ButtonStyle::Secondary,
url: None,
sku_id: None,
};
Some(Component::ActionRow(ActionRow {
components: vec![
Component::Button(jump_start),
Component::Button(single_step_back),
Component::Button(jump_custom),
Component::Button(single_step),
Component::Button(jump_end),
],
}))
};
let mut components = vec![top];
if let Some(pages) = pages {
components.push(pages);
}
components
}
async fn handle_component(&mut self, component: &mut InteractionComponent) -> ComponentResult {
let user_id = match component.user_id() {
Ok(user_id) => user_id,
Err(err) => return ComponentResult::Err(err),
};
if user_id != self.msg_owner {
return ComponentResult::Ignore;
}
if component.data.custom_id.starts_with("pagination") {
return handle_pagination_component(component, self.msg_owner, true, &mut self.pages)
.await;
}
let modal = match component.data.custom_id.as_str() {
"map_mods" => {
let input = TextInputBuilder::new("map_mods", "Mods")
.placeholder("E.g. hd or HdHRdteZ")
.required(false);
ModalBuilder::new("map_mods", "Specify mods").input(input)
}
"map_clock_rate" => {
let clock_rate = TextInputBuilder::new("map_clock_rate", "Clock rate")
.placeholder("Specify a clock rate")
.required(false);
let bpm = TextInputBuilder::new(
"map_bpm",
"BPM (overwritten if clock rate is specified)",
)
.placeholder("Specify a BPM")
.required(false);
ModalBuilder::new("map_speed_adjustments", "Speed adjustments")
.input(clock_rate)
.input(bpm)
}
"map_attrs" => {
let ar = TextInputBuilder::new("map_ar", "AR")
.placeholder("Specify an approach rate")
.required(false);
let cs = TextInputBuilder::new("map_cs", "CS")
.placeholder("Specify a circle size")
.required(false);
let hp = TextInputBuilder::new("map_hp", "HP")
.placeholder("Specify a drain rate")
.required(false);
let od = TextInputBuilder::new("map_od", "OD")
.placeholder("Specify an overall difficulty")
.required(false);
ModalBuilder::new("map_attrs", "Attributes")
.input(ar)
.input(cs)
.input(hp)
.input(od)
}
other => {
warn!(name = %other, ?component, "Unknown map component");
return ComponentResult::Ignore;
}
};
ComponentResult::CreateModal(modal)
}
async fn handle_modal(&mut self, modal: &mut InteractionModal) -> Result<()> {
if modal.user_id()? != self.msg_owner {
return Ok(());
}
let input = modal
.data
.components
.first()
.and_then(|row| row.components.first())
.wrap_err("Missing map modal input")?
.value
.as_deref()
.filter(|val| !val.is_empty());
let map = &self.maps[self.pages.index()];
match modal.data.custom_id.as_str() {
"pagination_custom" => {
let Some(Ok(page)) = input.map(str::parse) else {
debug!(input = input, "Failed to parse page input as usize");
return Ok(());
};
let max_page = self.pages.last_page();
if !(1..=max_page).contains(&page) {
debug!("Page {page} is not between 1 and {max_page}");
return Ok(());
}
self.pages.set_index((page - 1) * self.pages.per_page());
}
"map_mods" => {
let mods_res = input.map(|s| {
s.trim_start_matches('+')
.trim_end_matches('!')
.parse::<GameModsIntermode>()
});
let mods = match mods_res {
Some(Ok(value)) => Some(value),
Some(Err(_)) => {
debug!(input, "Failed to parse simulate mods");
return Ok(());
}
None => None,
};
debug!(?mods, "Matched mods");
match mods.map(|mods| mods.try_with_mode(map.mode)) {
Some(Some(mods)) if mods.is_valid() => self.mods = mods.into(),
None => self.mods = GameModsIntermode::new(),
Some(Some(mods)) => {
debug!("Incompatible mods {mods}");
return Ok(());
}
Some(None) => {
debug!(input, "Invalid mods for mode");
return Ok(());
}
}
}
"map_attrs" => {
self.attrs.ar = parse_attr(&*modal, "map_ar");
self.attrs.cs = parse_attr(&*modal, "map_cs");
self.attrs.hp = parse_attr(&*modal, "map_hp");
self.attrs.od = parse_attr(&*modal, "map_od");
}
"map_speed_adjustments" => {
self.attrs.clock_rate = parse_attr(&*modal, "map_clock_rate");
self.attrs.bpm = parse_attr(modal, "map_bpm");
}
other => warn!(name = %other, ?modal, "Unknown map modal"),
}
if let Err(err) = modal.defer().await {
warn!(?err, "Failed to defer modal");
}
Ok(())
}
}
impl MapPagination {
pub fn set_index(&mut self, index: usize) {
self.pages.set_index(index);
}
}
async fn creator_name(map: &BeatmapExtended, mapset: &BeatmapsetExtended) -> Option<Username> {
if map.creator_id == mapset.creator_id {
return None;
}
match Context::osu_user().name(map.creator_id).await {
Ok(name @ Some(_)) => return name,
Ok(None) => {}
Err(err) => warn!("{err:?}"),
}
let args = UserArgs::user_id(map.creator_id, GameMode::Osu);
match Context::redis().osu_user(args).await {
Ok(user) => Some(user.username.as_str().into()),
Err(err) => {
warn!(?err, "Failed to get user");
None
}
}
}
fn parse_attr<T: std::str::FromStr + std::fmt::Debug>(
modal: &InteractionModal,
component_id: &str,
) -> Option<T> {
modal
.data
.components
.iter()
.find_map(|row| {
row.components.first().and_then(|component| {
(component.custom_id == component_id).then(|| {
component
.value
.as_deref()
.filter(|value| !value.is_empty())
.map(str::parse)
.and_then(Result::ok)
})
})
})
.flatten()
}