Skip to content

Commit

Permalink
Add support for DMs and groups
Browse files Browse the repository at this point in the history
  • Loading branch information
Noskcaj19 committed Sep 10, 2020
1 parent d9cd89c commit cb58ba8
Show file tree
Hide file tree
Showing 11 changed files with 399 additions and 108 deletions.
291 changes: 226 additions & 65 deletions src/channel.rs

Large diffs are not rendered by default.

42 changes: 41 additions & 1 deletion src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::{
rc::{Rc, Weak},
};
use tracing_subscriber::EnvFilter;
use twilight::model::id::GuildId;
use twilight::model::id::{ChannelId, GuildId};
use weechat::{
config::{
BooleanOptionSettings, Conf, Config as WeechatConfig, ConfigSection, ConfigSectionSettings,
Expand All @@ -19,6 +19,7 @@ use weechat::{
mod guild;

pub use guild::{GuildConfig, GuildConfigInner};
use weechat::config::BaseConfigOption;

#[derive(Clone)]
pub struct Config {
Expand All @@ -43,6 +44,7 @@ pub struct InnerConfig {
pub nick_suffix: String,
pub nick_suffix_color: String,
pub guilds: HashMap<GuildId, GuildConfig>,
pub autojoin_private: Vec<ChannelId>,
}

impl InnerConfig {
Expand All @@ -57,6 +59,7 @@ impl InnerConfig {
nick_suffix: "".to_string(),
nick_suffix_color: "".to_string(),
guilds: HashMap::new(),
autojoin_private: Vec::new(),
}
}
}
Expand Down Expand Up @@ -132,6 +135,39 @@ impl Config {
}),
)
.expect("Unable to create tracing window option");

let inner_clone = Weak::clone(&inner);
sec.new_string_option(
StringOptionSettings::new("autojoin_private")
.description("List of private channels to autojoin")
.set_change_callback(move |_, option| {
let inner = inner_clone
.upgrade()
.expect("Outer config has outlived inner config");

let mut channels: Vec<_> = option
.value()
.split(',')
.map(|ch| ch.parse().map(ChannelId))
.flatten()
.collect();

channels.sort();
channels.dedup();

option.set(
&channels
.iter()
.map(|c| c.0.to_string())
.collect::<Vec<_>>()
.join(","),
false,
);

inner.borrow_mut().autojoin_private = channels;
}),
)
.expect("Unable to create autojoin private option");
}

{
Expand Down Expand Up @@ -225,6 +261,10 @@ impl Config {
pub fn guilds(&self) -> HashMap<GuildId, GuildConfig> {
self.inner.borrow().guilds.clone()
}

pub fn autojoin_private(&self) -> Vec<ChannelId> {
self.inner.borrow().autojoin_private.clone()
}
}

impl Drop for Config {
Expand Down
63 changes: 51 additions & 12 deletions src/discord/discord_connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
discord::plugin_message::PluginMessage,
instance::Instance,
refcell::{Ref, RefCell},
twilight_utils::ext::MessageExt,
twilight_utils::ext::{MessageExt, UserExt},
};
use anyhow::Result;
use std::sync::Arc;
Expand Down Expand Up @@ -119,11 +119,8 @@ impl DiscordConnection {

match event {
PluginMessage::Connected { user } => {
Weechat::print(&format!(
"discord: ready as: {}#{:04}",
user.name, user.discriminator
));
tracing::info!("Ready as {}#{:04}", user.name, user.discriminator);
Weechat::print(&format!("discord: ready as: {}", user.tag()));
tracing::info!("Ready as {}", user.tag());

for (guild_id, guild_config) in config.guilds() {
let guild = crate::guild::Guild::new(
Expand All @@ -137,12 +134,30 @@ impl DiscordConnection {
tracing::warn!("Unable to connect guild: {}", e);
};
}
instance.borrow_mut().insert(guild_id, guild);
instance.borrow_guilds_mut().insert(guild_id, guild);
}

for channel_id in config.autojoin_private() {
if let Some(channel) = conn.cache.private_channel(channel_id) {
if let Ok(channel) =
crate::channel::Channel::private(&channel, &conn, &config, |_| {})
{
if let Err(e) = channel.load_history().await {
tracing::warn!("Error occurred joining private channel: {}", e)
}

instance
.borrow_private_channels_mut()
.insert(channel_id, channel);
}
} else {
tracing::warn!("Unable to find channel: {}", channel_id)
}
}
},
PluginMessage::MessageCreate { message } => {
if let Some(guild_id) = message.guild_id {
let channels = match instance.borrow().get(&guild_id) {
let channels = match instance.borrow_guilds().get(&guild_id) {
Some(guild) => guild.channels(),
None => continue,
};
Expand All @@ -152,12 +167,20 @@ impl DiscordConnection {
None => continue,
};

channel.add_message(&conn.cache, &message, message.is_own(&conn.cache));
channel.add_message(&conn.cache, &message, !message.is_own(&conn.cache));
} else {
let private_channels = instance.borrow_private_channels_mut();
let channel = match private_channels.get(&message.channel_id) {
Some(channel) => channel,
None => continue,
};

channel.add_message(&conn.cache, &message, !message.is_own(&conn.cache));
}
},
PluginMessage::MessageDelete { event } => {
if let Some(guild_id) = event.guild_id {
let channels = match instance.borrow().get(&guild_id) {
let channels = match instance.borrow_guilds().get(&guild_id) {
Some(guild) => guild.channels(),
None => continue,
};
Expand All @@ -167,12 +190,20 @@ impl DiscordConnection {
None => continue,
};

channel.remove_message(&conn.cache, event.id);
} else {
let private_channels = instance.borrow_private_channels_mut();
let channel = match private_channels.get(&event.channel_id) {
Some(channel) => channel,
None => continue,
};

channel.remove_message(&conn.cache, event.id);
}
},
PluginMessage::MessageUpdate { message } => {
if let Some(guild_id) = message.guild_id {
let channels = match instance.borrow().get(&guild_id) {
let channels = match instance.borrow_guilds().get(&guild_id) {
Some(guild) => guild.channels(),
None => continue,
};
Expand All @@ -182,6 +213,14 @@ impl DiscordConnection {
None => continue,
};

channel.update_message(&conn.cache, *message);
} else {
let private_channels = instance.borrow_private_channels_mut();
let channel = match private_channels.get(&message.channel_id) {
Some(channel) => channel,
None => continue,
};

channel.update_message(&conn.cache, *message);
}
},
Expand All @@ -196,7 +235,7 @@ impl DiscordConnection {
);
}
if let Some(channel_id) = channel_id {
let channels = match instance.borrow().get(&member_chunk.guild_id) {
let channels = match instance.borrow_guilds().get(&member_chunk.guild_id) {
Some(guild) => guild.channels(),
None => continue,
};
Expand Down
13 changes: 9 additions & 4 deletions src/guild.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl GuildBuffer {
let name = name.to_string();
move |_: &Weechat, _: &Buffer| {
tracing::trace!(buffer.id=%id, buffer.name=%name, "Buffer close");
if let Ok(mut instance) = instance.try_borrow_mut() {
if let Ok(mut instance) = instance.try_borrow_guilds_mut() {
if let Some(x) = instance.remove(&id) {
x.inner.borrow_mut().closed = true;
}
Expand Down Expand Up @@ -147,16 +147,21 @@ impl Guild {
) -> anyhow::Result<()> {
let weak_inner = Rc::downgrade(&self.inner);
let channel_id = channel.id();
let channel =
crate::channel::Channel::new(&channel, &guild, &inner.conn, &self.config, move |_| {
let channel = crate::channel::Channel::guild(
&channel,
&guild,
&inner.conn,
&self.config,
move |_| {
if let Some(inner) = weak_inner.upgrade() {
if let Ok(mut inner) = inner.try_borrow_mut() {
if let Some(channel) = inner.channels.remove(&channel_id) {
channel.set_closed();
}
}
}
})?;
},
)?;

channel.load_history().await?;

Expand Down
37 changes: 24 additions & 13 deletions src/hooks/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ impl DiscordCommand {
.search_section_mut("server")
.expect("Can't get server section");

if !instance.borrow().contains_key(&guild.id) {
if !instance.borrow_guilds().contains_key(&guild.id) {
tracing::info!(%guild.id, %guild.name, "Adding guild to config.");
Weechat::print(&format!("discord: Added \"{}\"", guild.name));
instance.borrow_mut().insert(
instance.borrow_guilds_mut().insert(
guild.id,
Guild::new(
guild.id,
Expand Down Expand Up @@ -97,14 +97,14 @@ impl DiscordCommand {
{
let instance = self.instance.clone();
Weechat::spawn(async move {
let guild_ids = instance.borrow().keys().copied().collect::<Vec<_>>();
let guild_ids = instance.borrow_guilds().keys().copied().collect::<Vec<_>>();
match crate::twilight_utils::search_striped_guild_name(
&cache,
guild_ids,
&guild_name,
) {
Some(guild) => {
if instance.borrow_mut().remove(&guild.id).is_some() {
if instance.borrow_guilds_mut().remove(&guild.id).is_some() {
tracing::info!(%guild.id, %guild.name, "Removed guild from config.");
Weechat::print(&format!("discord: Removed \"{}\"", guild.name));
} else {
Expand All @@ -129,7 +129,7 @@ impl DiscordCommand {

if let Some(connection) = self.connection.borrow().as_ref() {
let cache = connection.cache.clone();
for (guild_id, guild_) in self.instance.borrow().clone().into_iter() {
for (guild_id, guild_) in self.instance.borrow_guilds().clone().into_iter() {
let cache = cache.clone();
Weechat::spawn(async move {
let guild = cache.guild(guild_id);
Expand All @@ -149,7 +149,7 @@ impl DiscordCommand {
});
}
} else {
for (guild_id, guild) in self.instance.borrow().clone().into_iter() {
for (guild_id, guild) in self.instance.borrow_guilds().clone().into_iter() {
Weechat::print(&format!("{:?}", guild_id));
for channel_id in guild.guild_config.autojoin_channels() {
Weechat::print(&format!(" #{:?}", channel_id));
Expand Down Expand Up @@ -180,11 +180,11 @@ impl DiscordCommand {

match crate::twilight_utils::search_striped_guild_name(
&conn.cache,
instance.borrow().keys().copied(),
instance.borrow_guilds().keys().copied(),
&guild_name,
) {
Some(guild) => {
if let Some(weechat_guild) = instance.borrow().get(&guild.id) {
if let Some(weechat_guild) = instance.borrow_guilds().get(&guild.id) {
tracing::info!(%guild.id, %guild.name, "Enabled autoconnect for guild");
weechat_guild.guild_config.set_autoconnect(true);
weechat_guild.guild_config.write(&weechat_guild.config);
Expand Down Expand Up @@ -230,11 +230,11 @@ impl DiscordCommand {

match crate::twilight_utils::search_striped_guild_name(
&cache,
instance.borrow().keys().copied(),
instance.borrow_guilds().keys().copied(),
&guild_name,
) {
Some(guild) => {
if let Some(weechat_guild) = instance.borrow().get(&guild.id) {
if let Some(weechat_guild) = instance.borrow_guilds().get(&guild.id) {
tracing::info!(%guild.id, %guild.name, "Disabled autoconnect for guild");
weechat_guild.guild_config.set_autoconnect(false);
weechat_guild.guild_config.write(&weechat_guild.config);
Expand Down Expand Up @@ -370,7 +370,9 @@ impl DiscordCommand {
});

if let Ok((guild, channel)) = rx.recv() {
if let Some(weecord_guild) = instance.borrow().values().find(|g| g.id == guild.id) {
if let Some(weecord_guild) =
instance.borrow_guilds().values().find(|g| g.id == guild.id)
{
Some((guild, weecord_guild.clone(), channel))
} else {
tracing::warn!(%guild.id, "Guild has not been added to weechat");
Expand Down Expand Up @@ -405,18 +407,27 @@ impl DiscordCommand {
fn process_debug_matches(&self, matches: &ArgMatches) {
match matches.subcommand() {
("buffer", Some(_)) => {
for guild in self.instance.borrow().values() {
for guild in self.instance.borrow_guilds().values() {
let (strng, weak) = guild.debug_counts();
Weechat::print(&format!("Guild [{} {}]: {}", strng, weak, guild.id));

for channel in guild.channels().values() {
Weechat::print(&format!(" Channel: {}", channel.id));
}
}

for private_channel in self.instance.borrow_private_channels().values() {
let (strng, weak) = private_channel.debug_counts();

Weechat::print(&format!(
"Private Channel [{} {}]: {}",
strng, weak, private_channel.id
));
}
},
("shutdown", Some(_)) => {
self.connection.shutdown();
self.instance.borrow_mut().clear();
self.instance.borrow_guilds_mut().clear();
},
_ => {},
}
Expand Down
Loading

0 comments on commit cb58ba8

Please sign in to comment.