Skip to content

Commit

Permalink
Fix breakage caused by and use bool_to_bitflags
Browse files Browse the repository at this point in the history
  • Loading branch information
GnomedDev committed Jan 3, 2024
1 parent 1df7756 commit c980d93
Show file tree
Hide file tree
Showing 9 changed files with 136 additions and 170 deletions.
155 changes: 89 additions & 66 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ arrayvec = "0.7.4"
bitflags = "2.4.1"
paste = "1.0.14"
typesize = { version = "0.1.2", features = ["arrayvec"] }
futures-util = { version = "0.3.29", default-features = false }
bool_to_bitflags = { git = "https://github.com/GnomedDev/bool-to-bitflags", features = ["typesize"] }

[dependencies.symphonia]
features = ["mp3", "ogg", "wav", "pcm"]
Expand Down
3 changes: 1 addition & 2 deletions src/commands/premium.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::{borrow::Cow, fmt::Write as _};

use futures_util::{stream::BoxStream, StreamExt as _};

use poise::{
futures_util::{stream::BoxStream, StreamExt as _},
serenity_prelude::{self as serenity, builder::*},
CreateReply,
};
Expand Down
14 changes: 7 additions & 7 deletions src/commands/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ pub async fn settings(ctx: Context<'_>) -> CommandResult {
.replace("{sep1}", sep1)
.replace("{prefix}", prefix)
.replace("{channel_mention}", &channel_mention)
.replace("{autojoin}", &guild_row.flags.auto_join().to_string())
.replace("{autojoin}", &guild_row.auto_join().to_string())
.replace("{role_mention}", required_role.as_deref().unwrap_or(none_str)),
false)
.field("**TTS Settings**", &ctx.gettext("
Expand All @@ -172,10 +172,10 @@ pub async fn settings(ctx: Context<'_>) -> CommandResult {
{sep2} Max Repeated Characters: `{repeated_chars}`
")
.replace("{sep2}", sep2)
.replace("{xsaid}", &guild_row.flags.xsaid().to_string())
.replace("{bot_ignore}", &guild_row.flags.bot_ignore().to_string())
.replace("{audience_ignore}", &guild_row.flags.audience_ignore().to_string())
.replace("{require_voice}", &guild_row.flags.require_voice().to_string())
.replace("{xsaid}", &guild_row.xsaid().to_string())
.replace("{bot_ignore}", &guild_row.bot_ignore().to_string())
.replace("{audience_ignore}", &guild_row.audience_ignore().to_string())
.replace("{require_voice}", &guild_row.require_voice().to_string())
.replace("{required_prefix}", guild_row.required_prefix.as_deref().unwrap_or(none_str))
.replace("{guild_mode}", guild_mode.into())
.replace("{default_voice}", &default_voice)
Expand All @@ -187,7 +187,7 @@ pub async fn settings(ctx: Context<'_>) -> CommandResult {
{sep4} Translation Language: `{target_lang}`
")
.replace("{sep4}", sep4)
.replace("{to_translate}", &guild_row.flags.to_translate().to_string())
.replace("{to_translate}", &guild_row.to_translate().to_string())
.replace("{target_lang}", target_lang),
false)
.field("**User Specific**", &ctx.gettext("
Expand Down Expand Up @@ -976,7 +976,7 @@ pub async fn translation_lang(
let mut to_say = ctx
.gettext("The target translation language is now: `{}`")
.replace("{}", &target_lang);
if !data.guilds_db.get(guild_id).await?.flags.to_translate() {
if !data.guilds_db.get(guild_id).await?.to_translate() {
to_say.push_str(
ctx.gettext("\nYou may want to enable translation with `/set translation on`"),
);
Expand Down
100 changes: 22 additions & 78 deletions src/database_models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,48 +19,6 @@ fn truncate_convert<const MAX_SIZE: usize>(
ArrayString::from(&s).expect("Truncate to shrink to below the max size!")
}

macro_rules! set_flag_if {
($flags:ident, $flag:path, $value:expr) => {
if ($value) {
$flags |= $flag;
}
};
}

macro_rules! named_bitflags {
(pub struct $name:ident: $flag_size:ident {
$(const $flag_name:ident = $flag_value:expr;)*
}) => {
#[derive(TypeSize)]
pub struct $name($flag_size);

bitflags::bitflags! {
impl $name: $flag_size {
$(const $flag_name = $flag_value;)*
}
}

impl $name {
paste::paste! {
$(
pub fn [<$flag_name:lower>](&self) -> bool {
self.contains(Self::$flag_name)
}
)*
}
}

impl std::fmt::Debug for $name {
fn fmt(&self, mut f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, concat!(stringify!($name), "("))?;
bitflags::parser::to_writer(self, &mut f)?;
write!(f, ")")?;
Ok(())
}
}
};
}

pub trait Compact {
type Compacted;
fn compact(self) -> Self::Compacted;
Expand All @@ -86,23 +44,18 @@ pub struct GuildRowRaw {
pub voice_mode: TTSMode,
}

named_bitflags! {
pub struct GuildRowFlags: u8 {
const XSAID = 0b000001;
const AUTO_JOIN = 0b000010;
const BOT_IGNORE = 0b000100;
const TO_TRANSLATE = 0b001000;
const REQUIRE_VOICE = 0b010000;
const AUDIENCE_IGNORE = 0b100000;
}
}

#[derive(Debug, TypeSize)]
#[bool_to_bitflags::bool_to_bitflags(owning_setters)]
#[derive(Debug, typesize::derive::TypeSize)]
pub struct GuildRow {
pub flags: GuildRowFlags,
pub channel: Option<ChannelId>,
pub premium_user: Option<UserId>,
pub required_role: Option<RoleId>,
pub xsaid: bool,
pub auto_join: bool,
pub bot_ignore: bool,
pub to_translate: bool,
pub require_voice: bool,
pub audience_ignore: bool,
pub msg_length: u16,
pub repeated_chars: u16,
pub prefix: ArrayString<8>,
Expand All @@ -114,16 +67,8 @@ pub struct GuildRow {
impl Compact for GuildRowRaw {
type Compacted = GuildRow;
fn compact(self) -> Self::Compacted {
let mut flags = GuildRowFlags::empty();
set_flag_if!(flags, GuildRowFlags::XSAID, self.xsaid);
set_flag_if!(flags, GuildRowFlags::AUTO_JOIN, self.auto_join);
set_flag_if!(flags, GuildRowFlags::BOT_IGNORE, self.bot_ignore);
set_flag_if!(flags, GuildRowFlags::TO_TRANSLATE, self.to_translate);
set_flag_if!(flags, GuildRowFlags::REQUIRE_VOICE, self.require_voice);
set_flag_if!(flags, GuildRowFlags::AUDIENCE_IGNORE, self.audience_ignore);

Self::Compacted {
flags,
__generated_flags: GuildRowGeneratedFlags::empty(),
channel: (self.channel != 0).then(|| ChannelId::new(self.channel as u64)),
premium_user: self.premium_user.map(|id| UserId::new(id as u64)),
required_role: self.required_role.map(|id| RoleId::new(id as u64)),
Expand All @@ -138,6 +83,12 @@ impl Compact for GuildRowRaw {
.map(|t| truncate_convert(t, "guild.required_prefix")),
voice_mode: self.voice_mode,
}
.set_xsaid(self.xsaid)
.set_auto_join(self.auto_join)
.set_bot_ignore(self.bot_ignore)
.set_to_translate(self.to_translate)
.set_require_voice(self.require_voice)
.set_audience_ignore(self.audience_ignore)
}
}

Expand All @@ -149,32 +100,25 @@ pub struct UserRowRaw {
pub premium_voice_mode: Option<TTSMode>,
}

named_bitflags! {
pub struct UserRowFlags: u8 {
const DM_BLOCKED = 0b01;
const DM_WELCOMED = 0b10;
}
}

#[derive(Debug, TypeSize)]
#[bool_to_bitflags::bool_to_bitflags(owning_setters)]
#[derive(Debug, typesize::derive::TypeSize)]
pub struct UserRow {
pub flags: UserRowFlags,
pub dm_blocked: bool,
pub dm_welcomed: bool,
pub voice_mode: Option<TTSMode>,
pub premium_voice_mode: Option<TTSMode>,
}

impl Compact for UserRowRaw {
type Compacted = UserRow;
fn compact(self) -> Self::Compacted {
let mut flags = UserRowFlags::empty();
set_flag_if!(flags, UserRowFlags::DM_BLOCKED, self.dm_blocked);
set_flag_if!(flags, UserRowFlags::DM_WELCOMED, self.dm_welcomed);

Self::Compacted {
flags,
voice_mode: self.voice_mode,
premium_voice_mode: self.premium_voice_mode,
__generated_flags: UserRowGeneratedFlags::empty(),
}
.set_dm_blocked(self.dm_blocked)
.set_dm_welcomed(self.dm_welcomed)
}
}

Expand Down
10 changes: 5 additions & 5 deletions src/events/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ async fn process_tts_msg(
member_nick,
&message.attachments,
&voice,
guild_row.flags.xsaid(),
guild_row.xsaid(),
guild_row.repeated_chars as usize,
nickname_row.name.as_deref(),
&data.regex_cache,
Expand All @@ -98,7 +98,7 @@ async fn process_tts_msg(
if let Some(target_lang) = guild_row.target_lang.as_deref()
&& let Some(translation_url) = &data.config.translation_url
&& let Some(translation_token) = &data.config.translation_token
&& guild_row.flags.to_translate()
&& guild_row.to_translate()
&& data.premium_check(Some(guild_id)).await?.is_none()
{
content = funcs::translate(
Expand Down Expand Up @@ -284,14 +284,14 @@ async fn process_support_dm(
_ => return Ok(()),
};

if message.author.bot || message.content.starts_with('-') {
if message.author.bot() || message.content.starts_with('-') {
return Ok(());
}

data.analytics.log(Cow::Borrowed("dm"), false);

let userinfo = data.userinfo_db.get(message.author.id.into()).await?;
if userinfo.flags.dm_welcomed() {
if userinfo.dm_welcomed() {
let content = message.content.to_lowercase();

if content.contains("discord.gg") {
Expand All @@ -308,7 +308,7 @@ async fn process_support_dm(
channel.say(&ctx, content).await?;
} else if content.as_str() == "help" {
channel.say(&ctx, "We cannot help you unless you ask a question, if you want the help command just do `-help`!").await?;
} else if !userinfo.flags.dm_blocked() {
} else if !userinfo.dm_blocked() {
let webhook_username = format!("{} ({})", message.author.tag(), message.author.id);

let mut attachments = Vec::new();
Expand Down
2 changes: 1 addition & 1 deletion src/events/voice_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub async fn voice_state_update(
}

// All the users in the vc are now bots
if channel_members.into_iter().any(|m| !m.user.bot) {
if channel_members.into_iter().any(|m| !m.user.bot()) {
return Ok(());
};

Expand Down
18 changes: 9 additions & 9 deletions src/funcs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ pub async fn run_checks(
serenity::content_safe(
&guild,
&message.content,
&serenity::ContentSafeOptions::default()
serenity::ContentSafeOptions::default()
.clean_here(false)
.clean_everyone(false)
.show_discriminator(false),
Expand Down Expand Up @@ -338,35 +338,35 @@ pub async fn run_checks(
let bot_voice_state = guild.voice_states.get(&ctx.cache.current_user().id);

let mut to_autojoin = None;
if message.author.bot {
if guild_row.flags.bot_ignore() || bot_voice_state.is_none() {
if message.author.bot() {
if guild_row.bot_ignore() || bot_voice_state.is_none() {
return Ok(None); // Is bot
}
} else {
// If the bot is in vc
if let Some(vc) = bot_voice_state {
// If the user needs to be in the vc, and the user's voice channel is not the same as the bot's
if guild_row.flags.require_voice()
if guild_row.require_voice()
&& vc.channel_id != voice_state.and_then(|vs| vs.channel_id)
{
return Ok(None); // Wrong vc
}
// Else if the user is in the vc and autojoin is on
} else if let Some(voice_state) = voice_state
&& guild_row.flags.auto_join()
&& guild_row.auto_join()
{
to_autojoin = Some(voice_state.channel_id.try_unwrap()?);
} else {
return Ok(None); // Bot not in vc
};

if guild_row.flags.require_voice() {
if guild_row.require_voice() {
let voice_channel = voice_state.unwrap().channel_id.try_unwrap()?;
let channel = guild.channels.get(&voice_channel).try_unwrap()?;

if channel.kind == serenity::ChannelType::Stage
&& voice_state.map_or(false, |vs| vs.suppress)
&& guild_row.flags.audience_ignore()
&& voice_state.map_or(false, serenity::VoiceState::suppress)
&& guild_row.audience_ignore()
{
return Ok(None); // Is audience
}
Expand Down Expand Up @@ -456,7 +456,7 @@ pub fn clean_msg(
guild.voice_states.values()
.filter(|vs| vs.channel_id.map_or(false, |vc| vc == voice_channel_id))
.filter_map(|vs| guild.members.get(&vs.user_id))
.filter(|member| !member.user.bot)
.filter(|member| !member.user.bot())
.count() > 2)
})
})
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ async fn _main(start_time: std::time::SystemTime) -> Result<()> {
},
command_check: Some(|ctx| {
Box::pin(async move {
if ctx.author().bot {
if ctx.author().bot() {
return Ok(false);
};

Expand Down

0 comments on commit c980d93

Please sign in to comment.