Skip to content
This repository was archived by the owner on Jan 4, 2022. It is now read-only.

Commit 68a2317

Browse files
committed
add logpump
1 parent 1b4a3e6 commit 68a2317

File tree

17 files changed

+338
-65
lines changed

17 files changed

+338
-65
lines changed

.cargo/config

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
[build]
2-
rustflags = ["-C", "target-cpu=native"]
2+
rustflags = ["-C", "target-cpu=sandybridge" , "-C", "target-feature=+aes,+sse2,+sse4.1,+ssse3"]

Cargo.lock

+1-12
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ bitflags = "1.2"
1313
chrono = "0.4"
1414
ctrlc = { version = "3", features = ["termination"] }
1515
darkredis = "0.7"
16-
dashmap = { version = "4.0.0-rc6", features=["serde"] }
1716
flexi_logger = { version = "0.15", default-features = false, features = ["colors", "specfile", "ziplogs"] }
1817
fluent-bundle = "0.12"
1918
futures-util = { version = "0.3", default-features = false }

src/commands/debug/test.rs

+4-36
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,12 @@
11
// use twilight_model::channel::{Reaction, ReactionType};
22
// use twilight_model::id::GuildId;
33

4-
use crate::core::CommandContext;
4+
use crate::core::{CommandContext, LogType};
55
use crate::CommandResult;
66
use twilight_model::id::UserId;
77

8-
pub async fn test(ctx: CommandContext) -> CommandResult {
9-
// let reactor = Reactors::new_emoji_list();
10-
// let reaction = Reaction {
11-
// channel_id: Default::default(),
12-
// emoji: ReactionType::Unicode { name: "".to_string() },
13-
// guild_id: None,
14-
// member: None,
15-
// message_id: Default::default(),
16-
// user_id: Default::default(),
17-
// };
18-
// if reactor.processes(&reaction) {
19-
// reactor
20-
// .do_your_thing(ctx.bot_context, &reaction, ctx.message.get_author_as_member()?)
21-
// .await;
22-
// }
23-
24-
// let out = Pattern::new(ctx.parser.parts.len() - 1)
25-
// .arrange(
26-
// ctx.parser
27-
// .parts
28-
// .iter()
29-
// .skip(1)
30-
// .map(String::from)
31-
// .collect::<Vec<String>>(),
32-
// )
33-
// .iter()
34-
// .map(|inner| inner.join("").to_string())
35-
// .collect::<Vec<String>>()
36-
// .join("\n");
37-
//
38-
// ctx.reply_raw(out).await?;
39-
ctx.bot_context
40-
.http
41-
.delete_ban(ctx.get_guild()?.id, UserId(366972849258496000))
42-
.await?;
8+
pub async fn test(mut ctx: CommandContext) -> CommandResult {
9+
let arg = ctx.parser.get_remaining();
10+
ctx.log(LogType::TEST(arg), None, None);
4311
Ok(())
4412
}

src/core/context/bot/mod.rs

+9
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ pub(crate) mod status;
1919
pub use stats::BotStats;
2020

2121
use crate::core::cache::Cache;
22+
use crate::core::logpump::LogData;
2223
use crate::core::GuildConfig;
2324
use crate::crypto::EncryptionKey;
2425
use crate::database::api_structs::{RawTeamMembers, TeamInfo, TeamMember};
@@ -29,6 +30,7 @@ use fluent_bundle::FluentArgs;
2930
use std::collections::HashMap;
3031
use std::sync::atomic::AtomicU64;
3132
use std::sync::Arc;
33+
use tokio::sync::mpsc::UnboundedSender;
3234
use tokio::sync::RwLock;
3335
use unic_langid::LanguageIdentifier;
3436

@@ -62,6 +64,7 @@ pub struct BotContext {
6264
pub start_time: DateTime<Utc>,
6365
pub global_admins: Vec<UserId>,
6466
team_info: RawTeamMembers,
67+
logpump_sender: UnboundedSender<LogData>,
6568
}
6669

6770
impl BotContext {
@@ -72,6 +75,7 @@ impl BotContext {
7275
translations: Translations,
7376
config_ops: (Option<Vec<u8>>, Vec<u64>),
7477
stats: Arc<BotStats>,
78+
logpump_sender: UnboundedSender<LogData>,
7579
) -> Self {
7680
let scheme_info = bot_core.2;
7781
let mut shard_states = HashMap::with_capacity(scheme_info.shards_per_cluster as usize);
@@ -112,6 +116,7 @@ impl BotContext {
112116
start_time: Utc::now(),
113117
global_admins,
114118
team_info,
119+
logpump_sender,
115120
}
116121
}
117122

@@ -161,4 +166,8 @@ impl BotContext {
161166

162167
TeamInfo { members }
163168
}
169+
170+
pub fn log(&self, data: LogData) {
171+
self.logpump_sender.send(data);
172+
}
164173
}

src/core/context/command/mod.rs

+18-1
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,11 @@ use twilight_model::{id::MessageId, user::CurrentUser};
1010

1111
use crate::commands::meta::nodes::GearBotPermissions;
1212
use crate::core::cache::{CachedChannel, CachedGuild, CachedMember, CachedUser};
13-
use crate::core::{BotContext, GuildConfig};
13+
use crate::core::{BotContext, GuildConfig, LogData, LogType};
1414
use crate::parser::Parser;
1515
use crate::translation::GearBotString;
1616
use crate::utils::{CommandError, OtherFailure};
17+
use twilight_model::id::{ChannelId, UserId};
1718

1819
mod messaging;
1920
mod object_fetcher;
@@ -125,4 +126,20 @@ impl CommandContext {
125126
None => Err(CommandError::NoDM),
126127
}
127128
}
129+
130+
pub fn log(
131+
&self,
132+
log_type: LogType,
133+
source_channel: Option<ChannelId>,
134+
source_user: Option<UserId>,
135+
) -> Result<(), CommandError> {
136+
log::debug!("Logging {:?}", log_type);
137+
self.bot_context.log(LogData {
138+
log_type,
139+
guild: self.get_guild()?.id,
140+
source_channel,
141+
source_user,
142+
});
143+
Ok(())
144+
}
128145
}

src/core/gearbot.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,12 @@ use twilight_model::{
2121
use crate::core::cache::Cache;
2222
use crate::core::context::bot::status as bot_status;
2323
use crate::core::handlers::{commands, general, modlog};
24-
use crate::core::{BotConfig, BotContext, BotStats, ColdRebootData};
24+
use crate::core::{logpump, BotConfig, BotContext, BotStats, ColdRebootData};
2525
use crate::database::Redis;
2626
use crate::translation::Translations;
2727
use crate::utils::{EventHandlerError, StartupError};
2828
use crate::{gearbot_error, gearbot_important, gearbot_info, SchemeInfo};
29+
use tokio::sync::mpsc::unbounded_channel;
2930

3031
pub async fn run(
3132
scheme_info: SchemeInfo,
@@ -120,14 +121,20 @@ pub async fn run(
120121
}
121122

122123
let cluster = cb.build().await?;
124+
125+
let (sender, receiver) = unbounded_channel();
126+
123127
let context = Arc::new(BotContext::new(
124128
(cache, cluster, scheme_info),
125129
(http, bot_user),
126130
(postgres_pool, redis_pool),
127131
translations,
128132
(config.__main_encryption_key, config.global_admins),
129133
stats,
134+
sender,
130135
));
136+
let ctx = context.clone();
137+
let mut logpump_task = tokio::spawn(logpump::run(ctx, receiver));
131138

132139
//establish api connection
133140
let c = context.clone();
@@ -166,6 +173,9 @@ pub async fn run(
166173
}
167174
context.cluster.down();
168175

176+
//TODO: enable when we move to tokio 0.3
177+
// logpump_task.abort();
178+
169179
Ok(())
170180
}
171181

src/core/guild_config.rs

+15-8
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
use serde::{Deserialize, Serialize};
22
use twilight_model::guild::Permissions;
3-
use twilight_model::id::{RoleId, UserId};
3+
use twilight_model::id::{ChannelId, RoleId, UserId};
44
use unic_langid::LanguageIdentifier;
55

66
use crate::commands::meta::nodes::GearBotPermissions;
7+
use crate::core::{DataLessLogType, LogFilter, LogType};
78
use crate::translation::DEFAULT_LANG;
9+
use std::collections::HashMap;
810

911
#[derive(Deserialize, Serialize, Debug)]
1012
pub struct GuildConfig {
@@ -13,6 +15,7 @@ pub struct GuildConfig {
1315
pub message_logs: MessageLogs,
1416
pub language: LanguageIdentifier,
1517
pub permission_groups: Vec<PermissionGroup>,
18+
pub log_channels: HashMap<ChannelId, LogChannelConfig>,
1619
}
1720

1821
#[derive(Deserialize, Serialize, Debug)]
@@ -40,15 +43,18 @@ pub enum LogStyle {
4043
Text,
4144
Embed,
4245
}
46+
#[derive(Deserialize, Serialize, Debug, Eq, PartialEq)]
47+
pub enum LogCategory {
48+
TEST,
49+
}
4350

4451
#[derive(Deserialize, Serialize, Debug)]
45-
pub struct LogChannelConfig {}
46-
47-
#[derive(Deserialize, Serialize, Debug)]
48-
pub enum LogCategories {}
49-
50-
#[derive(Deserialize, Serialize, Debug)]
51-
pub enum LogSubCategory {}
52+
pub struct LogChannelConfig {
53+
pub categories: Vec<LogCategory>,
54+
pub disabled_keys: Vec<DataLessLogType>,
55+
pub style: LogStyle,
56+
pub filters: Vec<LogFilter>,
57+
}
5258

5359
impl Default for GuildConfig {
5460
fn default() -> Self {
@@ -100,6 +106,7 @@ impl Default for GuildConfig {
100106
users: vec![],
101107
},
102108
],
109+
log_channels: HashMap::new(),
103110
}
104111
}
105112
}

src/core/logpump/log_data.rs

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
use crate::core::logpump::log_type::LogType;
2+
use twilight_model::id::{ChannelId, GuildId, UserId};
3+
4+
#[derive(Debug)]
5+
pub struct LogData {
6+
pub log_type: LogType,
7+
pub guild: GuildId,
8+
pub source_channel: Option<ChannelId>,
9+
pub source_user: Option<UserId>,
10+
}

src/core/logpump/log_filter.rs

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
use crate::core::{DataLessLogType, LogData, LogType};
2+
use serde::{Deserialize, Serialize};
3+
use std::sync::Arc;
4+
use twilight_model::id::{ChannelId, UserId};
5+
6+
#[derive(Deserialize, Serialize, Debug)]
7+
pub struct LogFilter {
8+
log_types: Vec<DataLessLogType>,
9+
source_channels: Vec<ChannelId>,
10+
source_users: Vec<UserId>,
11+
}
12+
13+
impl LogFilter {
14+
pub fn matches(
15+
&self,
16+
log_type: &DataLessLogType,
17+
source_channel: &Option<ChannelId>,
18+
source_user: &Option<UserId>,
19+
) -> bool {
20+
if self.log_types.contains(log_type) {
21+
return true;
22+
}
23+
if let Some(channel) = source_channel {
24+
if self.source_channels.contains(channel) {
25+
return true;
26+
}
27+
}
28+
29+
if let Some(user) = source_user {
30+
if self.source_users.contains(user) {
31+
return true;
32+
}
33+
}
34+
false
35+
}
36+
}

src/core/logpump/log_type.rs

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use crate::core::guild_config::LogCategory;
2+
use crate::utils::MessageError;
3+
use serde::{Deserialize, Serialize};
4+
use twilight_embed_builder::{EmbedBuildError, EmbedBuilder};
5+
use twilight_model::channel::embed::Embed;
6+
7+
#[derive(Deserialize, Serialize, Debug, Eq, PartialEq)]
8+
pub enum LogType {
9+
TEST(String),
10+
}
11+
12+
#[derive(Deserialize, Serialize, Debug, Eq, PartialEq)]
13+
pub enum DataLessLogType {
14+
TEST,
15+
}
16+
17+
impl LogType {
18+
pub fn get_category(&self) -> LogCategory {
19+
match self {
20+
LogType::TEST(_) => LogCategory::TEST,
21+
}
22+
}
23+
24+
pub fn to_embed(&self) -> Result<Embed, MessageError> {
25+
Ok(match self {
26+
LogType::TEST(data) => EmbedBuilder::new().description(data)?,
27+
}
28+
.build()?)
29+
}
30+
31+
pub fn to_text(&self) -> &str {
32+
match self {
33+
LogType::TEST(data) => data,
34+
}
35+
}
36+
37+
pub fn dataless(&self) -> DataLessLogType {
38+
match self {
39+
Self::TEST(_) => DataLessLogType::TEST,
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)