Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Few more minor refactorings #71

Merged
merged 8 commits into from
Sep 17, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/cache/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ impl Cache {
let guild = guild.as_ref().unwrap();

if let Some(thread_parent_id) = guild.active_thread_parents.get(&channel_id) {
current_channel_id = Some(thread_parent_id.to_owned());
current_channel_id = Some(*thread_parent_id);
return false;
}

Expand Down
13 changes: 6 additions & 7 deletions src/cache/events/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl UpdateCache for ChannelCreate {
.insert(self.id, CachedChannel::from_channel(channel, self));

guild
})
});
}
}

Expand All @@ -32,14 +32,13 @@ impl UpdateCache for ChannelDelete {

cache.guilds.alter(&guild_id, |_, mut guild| {
guild.channels.remove(&self.id);
guild.active_thread_parents = guild

guild
.active_thread_parents
.into_iter()
.filter(|(_, channel_id)| channel_id != &self.id)
.collect();
.retain(|_, &mut channel_id| channel_id != self.id);
circuitsacul marked this conversation as resolved.
Show resolved Hide resolved

guild
})
});
}
}

Expand All @@ -58,6 +57,6 @@ impl UpdateCache for ChannelUpdate {
.insert(self.id, CachedChannel::from_channel(channel, self));

guild
})
});
}
}
2 changes: 1 addition & 1 deletion src/cache/events/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ impl UpdateCache for MessageDelete {
impl UpdateCache for MessageDeleteBulk {
async fn update_cache(&self, cache: &Cache) {
for id in &self.ids {
cache.messages.insert(id.clone(), None, 1).await;
cache.messages.insert(*id, None, 1).await;
}
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/cache/events/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ impl UpdateCache for ThreadCreate {
cache.guilds.alter(&guild_id, |_, mut guild| {
guild.active_thread_parents.insert(self.id, parent_id);
guild
})
});
}
}

Expand All @@ -32,7 +32,7 @@ impl UpdateCache for ThreadDelete {
cache.guilds.alter(&self.guild_id, |_, mut guild| {
guild.active_thread_parents.remove(&self.id);
guild
})
});
}
}

Expand Down Expand Up @@ -60,7 +60,7 @@ impl UpdateCache for ThreadUpdate {
}

guild
})
});
}
}

Expand All @@ -84,7 +84,7 @@ impl UpdateCache for ThreadListSync {
.filter(|(_, parent_id)| !channel_ids.contains(parent_id))
.collect();

for thread in self.threads.iter() {
for thread in &self.threads {
if let Some(parent_id) = thread.parent_id {
threads.insert(thread.id, parent_id);
}
Expand All @@ -94,6 +94,6 @@ impl UpdateCache for ThreadListSync {
}

guild
})
});
}
}
4 changes: 2 additions & 2 deletions src/client/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ impl Config {
};
let token = env::var("DISCORD_TOKEN").expect("DISCORD_TOKEN not set");
let shards = env::var("SHARDS")
.unwrap_or("1".to_string())
.unwrap_or_else(|_| "1".to_string())
.parse()
.unwrap();
let db_url = env::var("SB_DATABASE_URL").expect("No database url specified.");
let error_channel = env::var("ERROR_CHANNEL_ID")
.ok()
.map(|v| v.parse().expect("Invalid ID for error log channel."));
let development = env::var("DEVELOPMENT")
.unwrap_or("false".to_string())
.unwrap_or_else(|_| "false".to_string())
.parse()
.expect("Invalid boolean for DEVELOPMENT.");
let owner_ids = env::var("OWNER_IDS").ok().map(|var| {
Expand Down
6 changes: 6 additions & 0 deletions src/client/cooldowns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,9 @@ impl Cooldowns {
}
}
}

impl Default for Cooldowns {
fn default() -> Self {
Self::new()
}
}
4 changes: 2 additions & 2 deletions src/core/emoji.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl EmojiCommon for SimpleEmoji {
// input. https://emojipedia.org/variation-selector-16/
let input = input
.strip_suffix('\u{fe0f}')
.map_or((&input).to_string(), |s| s.to_string());
.map_or_else(|| input.to_string(), |s| s.to_string());

if emojis::get(&input).is_some() {
Some(Self {
Expand Down Expand Up @@ -151,7 +151,7 @@ impl EmojiCommon for Vec<SimpleEmoji> {

async fn from_user_input(input: String, bot: &StarboardBot, guild_id: Id<GuildMarker>) -> Self {
let mut arr = Vec::new();
for piece in (&input).split(' ') {
for piece in input.split(' ') {
let emoji = SimpleEmoji::from_user_input(piece.to_string(), bot, guild_id).await;
if let Some(emoji) = emoji {
arr.push(emoji);
Expand Down
2 changes: 1 addition & 1 deletion src/core/starboard/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ impl StarboardConfig {
emojis.extend(sb.settings.downvote_emojis);

let configs = StarboardOverride::list_by_starboard(&bot.pool, sb.id).await?;
for c in configs {
if let Some(c) = configs {
circuitsacul marked this conversation as resolved.
Show resolved Hide resolved
let ov = c.get_overrides()?;
if let Some(upvote_emojis) = ov.upvote_emojis {
emojis.extend(upvote_emojis);
Expand Down
122 changes: 57 additions & 65 deletions src/core/starboard/vote_status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,98 +35,90 @@ impl VoteStatus {
message_author_is_bot: bool,
message_has_image: Option<bool>,
) -> StarboardResult<VoteStatus> {
let message_has_image = match message_has_image {
Some(val) => Some(val),
None => match bot
.cache
let message_has_image = if let Some(val) = message_has_image {
val
} else {
bot.cache
.fog_message(bot, channel_id, message_id)
.await?
.value()
{
Some(msg) => Some(has_image(&msg.embeds, &msg.attachments)),
None => None,
},
.as_ref()
.map(|msg| has_image(&msg.embeds, &msg.attachments))
== Some(true)
};

let mut invalid_exists = false;
let mut allow_remove = true;

let mut upvote = Vec::new();
let mut downvote = Vec::new();
for config in configs {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis();

#[derive(Clone, Copy, PartialEq, Eq)]
enum VoteType {
Upvote,
Downvote,
}

let eval_config = |config: StarboardConfig| {
// skip disabled configurations
if !config.resolved.enabled || config.starboard.premium_locked {
continue;
return None;
}

let is_downvote;
if config.resolved.upvote_emojis.contains(&emoji.raw) {
is_downvote = false;
let vote_type = if config.resolved.upvote_emojis.contains(&emoji.raw) {
VoteType::Upvote
} else if config.resolved.downvote_emojis.contains(&emoji.raw) {
is_downvote = true;
VoteType::Downvote
} else {
continue;
}
return None;
};

// respect the `remove_invalid_reactions` setting
if !config.resolved.remove_invalid_reactions {
allow_remove = false;
}

// check settings
let is_valid;
// message age in seconds
let message_age: i64 = {
let created_at = message_id.timestamp() as u128;
((now - created_at) / 1000) as i64
};

// settings to check:
// - self_vote
// - allow_bots
// - require_image
// - older_than
// - newer_than
// alow need to check permroles
let min_age = config.resolved.older_than;
let max_age = config.resolved.newer_than;

let message_age: i64 = {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis();
let created_at = message_id.timestamp();
let self_vote_valid = config.resolved.self_vote || reactor_id != message_author_id;

((now - created_at as u128) / 1000).try_into().unwrap()
};
let older_than = config.resolved.older_than;
let newer_than = config.resolved.newer_than;

if !config.resolved.self_vote && reactor_id == message_author_id {
// self-vote
is_valid = false;
} else if !config.resolved.allow_bots && message_author_is_bot {
// allow-bots
is_valid = false;
} else if config.resolved.require_image && !matches!(message_has_image, Some(true)) {
// require-image
is_valid = false;
} else if older_than != 0 && message_age < older_than {
// older-than
is_valid = false;
} else if newer_than != 0 && message_age > newer_than {
// newer-than
is_valid = false;
} else {
is_valid = true;
}
let bots_valid = config.resolved.allow_bots || !message_author_is_bot;

if !is_valid {
invalid_exists = true;
continue;
}
let images_valid = config.resolved.require_image || message_has_image;

// add to corresponding list
if is_downvote {
downvote.push(config);
let time_valid = (min_age..max_age).contains(&message_age);

if self_vote_valid && bots_valid && images_valid && time_valid {
Some((config, vote_type))
} else {
upvote.push(config);
invalid_exists = true;
None
}
}
};

let mut upvote = Vec::new();
let mut downvote = Vec::new();

configs
.into_iter()
.filter_map(eval_config)
.for_each(|(config, vote_type)| {
if vote_type == VoteType::Upvote {
upvote.push(config)
} else {
downvote.push(config)
}
});

if upvote.is_empty() && downvote.is_empty() {
if invalid_exists && allow_remove {
Ok(VoteStatus::Remove)
Expand Down
2 changes: 1 addition & 1 deletion src/interactions/commands/chat/autostar/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl ViewAutoStarChannels {
"channel: <#{}>\n" <- asc.channel_id;
"emojis: {}\n" <- Vec::<SimpleEmoji>::from_stored(asc.emojis).into_readable(&ctx.bot, guild_id).await;
"min-chars: {}\n" <- asc.min_chars;
"max-chars: {}\n" <- asc.max_chars.map(|v| v.to_string()).unwrap_or("none".to_string());
"max-chars: {}\n" <- asc.max_chars.map(|v| v.to_string()).unwrap_or_else(|| "none".to_string());
"require-image: {}\n" <- asc.require_image;
"delete-invalid: {}" <- asc.delete_invalid;
);
Expand Down
12 changes: 6 additions & 6 deletions src/interactions/commands/format_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ pub async fn format_settings(
guild_id: Id<GuildMarker>,
config: &StarboardConfig,
) -> FormattedStarboardSettings {
let ov_values = match config.overrides.get(0) {
None => None,
Some(ov) => Some(ov.get_overrides().unwrap()),
};
let ov_values = config
.overrides
.get(0)
.map(|ov| ov.get_overrides().unwrap());

macro_rules! settings {
($($setting: ident, $pretty_name: expr, $value: expr;)*) => {{
Expand Down Expand Up @@ -54,7 +54,7 @@ pub async fn format_settings(
.resolved
.display_emoji
.clone()
.unwrap_or("none".to_string()),
.unwrap_or_else(|| "none".to_string()),
)
.into_readable(bot, guild_id)
.await;
Expand Down Expand Up @@ -114,7 +114,7 @@ pub async fn format_settings(
),
embed: settings!(
color, "color", &format!(
"#{:X}", res.color.unwrap_or(constants::BOT_COLOR.try_into().unwrap())
"#{:X}", res.color.unwrap_or_else(|| constants::BOT_COLOR.try_into().unwrap())
);
jump_to_message, "jump-to-message", res.jump_to_message;
attachments_list, "attachments-list", res.attachments_list;
Expand Down
2 changes: 1 addition & 1 deletion src/owner/commands/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub async fn run_sql(bot: &StarboardBot, event: &MessageCreate) -> anyhow::Resul
let result = SqlResult {
execution_times,
inspect: result.unwrap_or(None),
tag: (*meta.get("tag").unwrap_or(&"?query?")).to_string(),
tag: meta.get("tag").unwrap_or(&"?query?").to_string(),
};
results.push(result);
}
Expand Down
9 changes: 9 additions & 0 deletions src/utils/cooldowns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,15 @@ where
}
}

impl<K> Default for FlexibleMapping<K>
where
K: Hash + Eq + Clone,
{
fn default() -> Self {
Self::new()
}
}

pub struct JumpingWindow {
last_reset: Instant,
period: Duration,
Expand Down
3 changes: 1 addition & 2 deletions src/utils/notify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ pub async fn notify(bot: &StarboardBot, user_id: Id<UserMarker>, message: &str)
return;
}

let create = dm::dm(bot, user_id).await;
let create = match create {
let create = match dm::dm(bot, user_id).await {
Err(_) => return,
Ok(create) => create,
};
Expand Down