reformat, add ping command

This commit is contained in:
Ondřej Hruška 2021-08-22 19:30:36 +02:00
parent 448746b1da
commit 0403d1ef71
No known key found for this signature in database
GPG key ID: 2C5FD5035250423D
7 changed files with 108 additions and 237 deletions

View file

@ -2,10 +2,7 @@ use std::process::Command;
use std::str; use std::str;
fn main() { fn main() {
let desc_c = Command::new("git") let desc_c = Command::new("git").args(&["describe", "--all", "--long"]).output().unwrap();
.args(&["describe", "--all", "--long"])
.output()
.unwrap();
let desc = unsafe { str::from_utf8_unchecked(&desc_c.stdout) }; let desc = unsafe { str::from_utf8_unchecked(&desc_c.stdout) };

4
rustfmt.toml Normal file
View file

@ -0,0 +1,4 @@
max_width=120
newline_style="Unix"
use_field_init_shorthand=true
chain_width=80

View file

@ -19,6 +19,7 @@ pub enum StatusCommand {
Help, Help,
ListMembers, ListMembers,
Leave, Leave,
Ping,
} }
macro_rules! p_user { macro_rules! p_user {
@ -48,20 +49,15 @@ static RE_UNBAN_USER: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"unb
static RE_BAN_SERVER: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"ban\s+", p_server!())); static RE_BAN_SERVER: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"ban\s+", p_server!()));
static RE_UNBAN_SERVER: once_cell::sync::Lazy<Regex> = static RE_UNBAN_SERVER: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"unban\s+", p_server!()));
Lazy::new(|| command!(r"unban\s+", p_server!()));
static RE_ADD_MEMBER: once_cell::sync::Lazy<Regex> = static RE_ADD_MEMBER: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"(?:add)\s+", p_user!()));
Lazy::new(|| command!(r"(?:add)\s+", p_user!()));
static RE_REMOVE_MEMBER: once_cell::sync::Lazy<Regex> = static RE_REMOVE_MEMBER: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"(?:kick|remove)\s+", p_user!()));
Lazy::new(|| command!(r"(?:kick|remove)\s+", p_user!()));
static RE_GRANT_ADMIN: once_cell::sync::Lazy<Regex> = static RE_GRANT_ADMIN: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"(?:op|admin)\s+", p_user!()));
Lazy::new(|| command!(r"(?:op|admin)\s+", p_user!()));
static RE_REVOKE_ADMIN: once_cell::sync::Lazy<Regex> = static RE_REVOKE_ADMIN: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"(?:deop|deadmin)\s+", p_user!()));
Lazy::new(|| command!(r"(?:deop|deadmin)\s+", p_user!()));
static RE_OPEN_GROUP: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"opengroup")); static RE_OPEN_GROUP: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"opengroup"));
@ -73,6 +69,8 @@ static RE_MEMBERS: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"(?:mem
static RE_LEAVE: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"(?:leave)")); static RE_LEAVE: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"(?:leave)"));
static RE_PING: once_cell::sync::Lazy<Regex> = Lazy::new(|| command!(r"(?:ping)"));
static RE_ANNOUNCE: once_cell::sync::Lazy<Regex> = static RE_ANNOUNCE: once_cell::sync::Lazy<Regex> =
Lazy::new(|| Regex::new(concat!(r"(?:^|\s|>|\n)[\\/]announce\s+(.*)$")).unwrap()); Lazy::new(|| Regex::new(concat!(r"(?:^|\s|>|\n)[\\/]announce\s+(.*)$")).unwrap());
@ -115,6 +113,11 @@ pub fn parse_status(content: &str) -> Vec<StatusCommand> {
commands.push(StatusCommand::Leave); commands.push(StatusCommand::Leave);
} }
if RE_PING.is_match(&content) {
debug!("PING");
commands.push(StatusCommand::Ping);
}
if RE_MEMBERS.is_match(&content) { if RE_MEMBERS.is_match(&content) {
debug!("MEMBERS"); debug!("MEMBERS");
commands.push(StatusCommand::ListMembers); commands.push(StatusCommand::ListMembers);
@ -216,9 +219,8 @@ mod test {
use crate::command::{parse_status, StatusCommand}; use crate::command::{parse_status, StatusCommand};
use super::{ use super::{
RE_ADD_MEMBER, RE_ANNOUNCE, RE_BAN_SERVER, RE_BAN_USER, RE_BOOST, RE_CLOSE_GROUP, RE_ADD_MEMBER, RE_ANNOUNCE, RE_BAN_SERVER, RE_BAN_USER, RE_BOOST, RE_CLOSE_GROUP, RE_GRANT_ADMIN, RE_HELP,
RE_GRANT_ADMIN, RE_HELP, RE_IGNORE, RE_LEAVE, RE_MEMBERS, RE_OPEN_GROUP, RE_REMOVE_MEMBER, RE_IGNORE, RE_LEAVE, RE_MEMBERS, RE_OPEN_GROUP, RE_REMOVE_MEMBER, RE_REVOKE_ADMIN,
RE_REVOKE_ADMIN,
}; };
#[test] #[test]
@ -275,24 +277,15 @@ mod test {
let c = RE_BAN_USER.captures("/ban lain@pleroma.soykaf.com"); let c = RE_BAN_USER.captures("/ban lain@pleroma.soykaf.com");
assert!(c.is_some()); assert!(c.is_some());
assert_eq!( assert_eq!(c.unwrap().get(1).unwrap().as_str(), "lain@pleroma.soykaf.com");
c.unwrap().get(1).unwrap().as_str(),
"lain@pleroma.soykaf.com"
);
let c = RE_BAN_USER.captures("/ban lain@pleroma.soykaf.com xx"); let c = RE_BAN_USER.captures("/ban lain@pleroma.soykaf.com xx");
assert!(c.is_some()); assert!(c.is_some());
assert_eq!( assert_eq!(c.unwrap().get(1).unwrap().as_str(), "lain@pleroma.soykaf.com");
c.unwrap().get(1).unwrap().as_str(),
"lain@pleroma.soykaf.com"
);
let c = RE_BAN_USER.captures("/ban @lain@pleroma.soykaf.com"); let c = RE_BAN_USER.captures("/ban @lain@pleroma.soykaf.com");
assert!(c.is_some()); assert!(c.is_some());
assert_eq!( assert_eq!(c.unwrap().get(1).unwrap().as_str(), "@lain@pleroma.soykaf.com");
c.unwrap().get(1).unwrap().as_str(),
"@lain@pleroma.soykaf.com"
);
let c = RE_BAN_USER.captures("/ban @lain"); let c = RE_BAN_USER.captures("/ban @lain");
assert!(c.is_some()); assert!(c.is_some());
@ -345,10 +338,7 @@ mod test {
let c = RE_REMOVE_MEMBER.captures("/kick lain@pleroma.soykaf.com"); let c = RE_REMOVE_MEMBER.captures("/kick lain@pleroma.soykaf.com");
assert!(c.is_some()); assert!(c.is_some());
assert_eq!( assert_eq!(c.unwrap().get(1).unwrap().as_str(), "lain@pleroma.soykaf.com");
c.unwrap().get(1).unwrap().as_str(),
"lain@pleroma.soykaf.com"
);
} }
#[test] #[test]
@ -361,10 +351,7 @@ mod test {
let c = RE_GRANT_ADMIN.captures("/op @lain@pleroma.soykaf.com"); let c = RE_GRANT_ADMIN.captures("/op @lain@pleroma.soykaf.com");
assert!(c.is_some()); assert!(c.is_some());
assert_eq!( assert_eq!(c.unwrap().get(1).unwrap().as_str(), "@lain@pleroma.soykaf.com");
c.unwrap().get(1).unwrap().as_str(),
"@lain@pleroma.soykaf.com"
);
} }
#[test] #[test]

View file

@ -91,9 +91,7 @@ impl GroupHandle {
loop { loop {
if next_save < Instant::now() { if next_save < Instant::now() {
self.save_if_needed() self.save_if_needed().await.log_error("Failed to save group");
.await
.log_error("Failed to save group");
next_save = Instant::now() + PERIODIC_SAVE; next_save = Instant::now() + PERIODIC_SAVE;
} }
@ -104,27 +102,18 @@ impl GroupHandle {
match tokio::time::timeout(timeout, events.next()).await { match tokio::time::timeout(timeout, events.next()).await {
Ok(Some(event)) => { Ok(Some(event)) => {
debug!( debug!("(@{}) Event: {}", self.config.get_acct(), EventDisplay(&event));
"(@{}) Event: {}",
self.config.get_acct(),
EventDisplay(&event)
);
match event { match event {
Event::Update(_status) => {} Event::Update(_status) => {}
Event::Notification(n) => { Event::Notification(n) => {
self.handle_notification(n) self.handle_notification(n).await.log_error("Error handling a notification");
.await
.log_error("Error handling a notification");
} }
Event::Delete(_id) => {} Event::Delete(_id) => {}
Event::FiltersChanged => {} Event::FiltersChanged => {}
} }
} }
Ok(None) => { Ok(None) => {
warn!( warn!("Group @{} socket closed, restarting...", self.config.get_acct());
"Group @{} socket closed, restarting...",
self.config.get_acct()
);
break; break;
} }
Err(_) => { Err(_) => {
@ -181,13 +170,9 @@ impl GroupHandle {
// Someone tagged the group in OP, boost it. // Someone tagged the group in OP, boost it.
info!("Boosting OP mention"); info!("Boosting OP mention");
tokio::time::sleep(DELAY_BEFORE_ACTION).await; tokio::time::sleep(DELAY_BEFORE_ACTION).await;
self.client self.client.reblog(&status.id).await.log_error("Failed to boost");
.reblog(&status.id)
.await
.log_error("Failed to boost");
} else { } else {
replies replies.push("You are not allowed to post to this group".to_string());
.push("You are not allowed to post to this group".to_string());
} }
} else { } else {
debug!("Not OP, ignore mention"); debug!("Not OP, ignore mention");
@ -208,10 +193,7 @@ impl GroupHandle {
if can_write { if can_write {
do_boost_prev_post = status.in_reply_to_id.is_some(); do_boost_prev_post = status.in_reply_to_id.is_some();
} else { } else {
replies.push( replies.push("You are not allowed to share to this group".to_string());
"You are not allowed to share to this group"
.to_string(),
);
} }
} }
StatusCommand::BanUser(u) => { StatusCommand::BanUser(u) => {
@ -221,24 +203,17 @@ impl GroupHandle {
match self.config.ban_user(&u, true) { match self.config.ban_user(&u, true) {
Ok(_) => { Ok(_) => {
any_admin_cmd = true; any_admin_cmd = true;
replies.push(format!( replies.push(format!("User {} banned from group!", u));
"User {} banned from group!",
u
));
// no announcement here // no announcement here
} }
Err(e) => { Err(e) => {
replies.push(format!( replies.push(format!("Failed to ban user {}: {}", u, e));
"Failed to ban user {}: {}",
u, e
));
} }
} }
} }
} else { } else {
replies replies.push("Only admins can manage user bans".to_string());
.push("Only admins can manage user bans".to_string());
} }
} }
StatusCommand::UnbanUser(u) => { StatusCommand::UnbanUser(u) => {
@ -258,8 +233,7 @@ impl GroupHandle {
} }
} }
} else { } else {
replies replies.push("Only admins can manage user bans".to_string());
.push("Only admins can manage user bans".to_string());
} }
} }
StatusCommand::BanServer(s) => { StatusCommand::BanServer(s) => {
@ -268,26 +242,16 @@ impl GroupHandle {
match self.config.ban_server(&s, true) { match self.config.ban_server(&s, true) {
Ok(_) => { Ok(_) => {
any_admin_cmd = true; any_admin_cmd = true;
announcements.push(format!( announcements.push(format!("Server \"{}\" has been banned.", s));
"Server \"{}\" has been banned.", replies.push(format!("Server {} banned from group!", s));
s
));
replies.push(format!(
"Server {} banned from group!",
s
));
} }
Err(e) => { Err(e) => {
replies.push(format!( replies.push(format!("Failed to ban server {}: {}", s, e));
"Failed to ban server {}: {}",
s, e
));
} }
} }
} }
} else { } else {
replies replies.push("Only admins can manage server bans".to_string());
.push("Only admins can manage server bans".to_string());
} }
} }
StatusCommand::UnbanServer(s) => { StatusCommand::UnbanServer(s) => {
@ -296,12 +260,8 @@ impl GroupHandle {
match self.config.ban_server(&s, false) { match self.config.ban_server(&s, false) {
Ok(_) => { Ok(_) => {
any_admin_cmd = true; any_admin_cmd = true;
announcements.push(format!( announcements.push(format!("Server \"{}\" has been un-banned.", s));
"Server \"{}\" has been un-banned.", replies.push(format!("Server {} un-banned!", s));
s
));
replies
.push(format!("Server {} un-banned!", s));
} }
Err(_) => { Err(_) => {
unreachable!() unreachable!()
@ -309,8 +269,7 @@ impl GroupHandle {
} }
} }
} else { } else {
replies replies.push("Only admins can manage server bans".to_string());
.push("Only admins can manage server bans".to_string());
} }
} }
StatusCommand::AddMember(u) => { StatusCommand::AddMember(u) => {
@ -320,23 +279,15 @@ impl GroupHandle {
match self.config.set_member(&u, true) { match self.config.set_member(&u, true) {
Ok(_) => { Ok(_) => {
any_admin_cmd = true; any_admin_cmd = true;
replies.push(format!( replies.push(format!("User {} added to the group!", u));
"User {} added to the group!",
u
));
if self.config.is_member_only() { if self.config.is_member_only() {
announcements.push(format!( announcements
"Welcome new member @{} to the group!", .push(format!("Welcome new member @{} to the group!", u));
u
));
} }
} }
Err(e) => { Err(e) => {
replies.push(format!( replies.push(format!("Failed to add user {} to group: {}", u, e));
"Failed to add user {} to group: {}",
u, e
));
} }
} }
} }
@ -351,10 +302,7 @@ impl GroupHandle {
match self.config.set_member(&u, false) { match self.config.set_member(&u, false) {
Ok(_) => { Ok(_) => {
any_admin_cmd = true; any_admin_cmd = true;
replies.push(format!( replies.push(format!("User {} removed from the group.", u));
"User {} removed from the group.",
u
));
} }
Err(_) => { Err(_) => {
unreachable!() unreachable!()
@ -372,14 +320,9 @@ impl GroupHandle {
match self.config.set_admin(&u, true) { match self.config.set_admin(&u, true) {
Ok(_) => { Ok(_) => {
any_admin_cmd = true; any_admin_cmd = true;
replies.push(format!( replies.push(format!("User {} is now a group admin!", u));
"User {} is now a group admin!", announcements
u .push(format!("User @{} can now manage this group!", u));
));
announcements.push(format!(
"User @{} can now manage this group!",
u
));
} }
Err(e) => { Err(e) => {
replies.push(format!( replies.push(format!(
@ -400,20 +343,13 @@ impl GroupHandle {
match self.config.set_admin(&u, false) { match self.config.set_admin(&u, false) {
Ok(_) => { Ok(_) => {
any_admin_cmd = true; any_admin_cmd = true;
replies.push(format!( replies.push(format!("User {} is no longer a group admin!", u));
"User {} is no longer a group admin!", announcements
u .push(format!("User @{} no longer manages this group.", u));
));
announcements.push(format!(
"User @{} no longer manages this group.",
u
));
} }
Err(e) => { Err(e) => {
replies.push(format!( replies
"Failed to revoke {}'s group admin: {}", .push(format!("Failed to revoke {}'s group admin: {}", u, e));
u, e
));
} }
} }
} }
@ -426,14 +362,11 @@ impl GroupHandle {
if self.config.is_member_only() { if self.config.is_member_only() {
any_admin_cmd = true; any_admin_cmd = true;
self.config.set_member_only(false); self.config.set_member_only(false);
replies replies.push("Group changed to open-access".to_string());
.push("Group changed to open-access".to_string()); announcements.push("This group is now open-access!".to_string());
announcements
.push("This group is now open-access!".to_string());
} }
} else { } else {
replies replies.push("Only admins can set group options".to_string());
.push("Only admins can set group options".to_string());
} }
} }
StatusCommand::CloseGroup => { StatusCommand::CloseGroup => {
@ -441,14 +374,11 @@ impl GroupHandle {
if !self.config.is_member_only() { if !self.config.is_member_only() {
any_admin_cmd = true; any_admin_cmd = true;
self.config.set_member_only(true); self.config.set_member_only(true);
replies replies.push("Group changed to member-only".to_string());
.push("Group changed to member-only".to_string()); announcements.push("This group is now member-only!".to_string());
announcements
.push("This group is now member-only!".to_string());
} }
} else { } else {
replies replies.push("Only admins can set group options".to_string());
.push("Only admins can set group options".to_string());
} }
} }
StatusCommand::Help => { StatusCommand::Help => {
@ -474,12 +404,13 @@ impl GroupHandle {
replies.push( replies.push(
"\nTo share an original post, mention the group user.\n\ "\nTo share an original post, mention the group user.\n\
Posts with commands, and replies, won't be shared.\n\ Replies and mentions with commands won't be shared.\n\
\n\ \n\
**Supported commands:**\n\ **Supported commands:**\n\
`/ignore, /i` - make the group completely ignore the post\n\ `/ignore, /i` - make the group completely ignore the post\n\
`/members, /who` - show group members / admins\n\ `/members, /who` - show group members / admins\n\
`/boost, /b` - boost the replied-to post into the group" `/boost, /b` - boost the replied-to post into the group\n\
`/ping - check that the service is alive"
.to_string(), .to_string(),
); );
@ -497,7 +428,9 @@ impl GroupHandle {
`/deop, /deadmin user` - revoke admin rights\n\ `/deop, /deadmin user` - revoke admin rights\n\
`/opengroup` - make member-only\n\ `/opengroup` - make member-only\n\
`/closegroup` - make public-access\n\ `/closegroup` - make public-access\n\
`/announce x` - make a public announcement from the rest of the status".to_string()); `/announce x` - make a public announcement from the rest of the status"
.to_string(),
);
} }
} }
StatusCommand::ListMembers => { StatusCommand::ListMembers => {
@ -505,10 +438,8 @@ impl GroupHandle {
if is_admin { if is_admin {
if self.config.is_member_only() { if self.config.is_member_only() {
replies.push("Group members:".to_string()); replies.push("Group members:".to_string());
let admins = let admins = self.config.get_admins().collect::<HashSet<_>>();
self.config.get_admins().collect::<HashSet<_>>(); let mut members = self.config.get_members().collect::<Vec<_>>();
let mut members =
self.config.get_members().collect::<Vec<_>>();
members.extend(admins.iter()); members.extend(admins.iter());
members.sort(); members.sort();
members.dedup(); members.dedup();
@ -528,8 +459,7 @@ impl GroupHandle {
if show_admins { if show_admins {
replies.push("Group admins:".to_string()); replies.push("Group admins:".to_string());
let mut admins = let mut admins = self.config.get_admins().collect::<Vec<_>>();
self.config.get_admins().collect::<Vec<_>>();
admins.sort(); admins.sort();
for a in admins { for a in admins {
replies.push(a.to_string()); replies.push(a.to_string());
@ -543,6 +473,9 @@ impl GroupHandle {
replies.push("You left the group.".to_string()); replies.push("You left the group.".to_string());
} }
} }
StatusCommand::Ping => {
replies.push("Pong".to_string());
}
} }
} }
@ -566,11 +499,7 @@ impl GroupHandle {
.build() .build()
.expect("error build status"); .expect("error build status");
let _ = self let _ = self.client.new_status(post).await.log_error("Failed to post");
.client
.new_status(post)
.await
.log_error("Failed to post");
} }
if !announcements.is_empty() { if !announcements.is_empty() {
@ -578,15 +507,11 @@ impl GroupHandle {
let post = StatusBuilder::new() let post = StatusBuilder::new()
.status(format!("**📢 Group announcement**\n{msg}", msg = msg)) .status(format!("**📢 Group announcement**\n{msg}", msg = msg))
.content_type("text/markdown") .content_type("text/markdown")
.visibility(Visibility::Unlisted) .visibility(Visibility::Public)
.build() .build()
.expect("error build status"); .expect("error build status");
let _ = self let _ = self.client.new_status(post).await.log_error("Failed to post");
.client
.new_status(post)
.await
.log_error("Failed to post");
} }
if any_admin_cmd { if any_admin_cmd {
@ -598,8 +523,7 @@ impl GroupHandle {
info!("New follower!"); info!("New follower!");
tokio::time::sleep(Duration::from_millis(500)).await; tokio::time::sleep(Duration::from_millis(500)).await;
let text = let text = if self.config.is_member_only() {
if self.config.is_member_only() {
// Admins are listed without @, so they won't become handles here. // Admins are listed without @, so they won't become handles here.
// Tagging all admins would be annoying. // Tagging all admins would be annoying.
let mut admins = self.config.get_admins().cloned().collect::<Vec<_>>(); let mut admins = self.config.get_admins().cloned().collect::<Vec<_>>();
@ -607,7 +531,10 @@ impl GroupHandle {
format!( format!(
"@{user} welcome to the group! This is a member-only group, you won't be \ "@{user} welcome to the group! This is a member-only group, you won't be \
able to post. Ask the group admins if you wish to join!\n\n\ able to post. Ask the group admins if you wish to join!\n\n\
Admins: {admins}", user = notif_acct, admins = admins.join(", ")) Admins: {admins}",
user = notif_acct,
admins = admins.join(", ")
)
} else { } else {
format!( format!(
"@{user} welcome to the group! \ "@{user} welcome to the group! \
@ -623,11 +550,7 @@ impl GroupHandle {
.build() .build()
.expect("error build status"); .expect("error build status");
let _ = self let _ = self.client.new_status(post).await.log_error("Failed to post");
.client
.new_status(post)
.await
.log_error("Failed to post");
} }
_ => {} _ => {}
} }
@ -670,9 +593,7 @@ impl GroupHandle {
for n in notifs_to_handle { for n in notifs_to_handle {
debug!("Handling missed notification: {}", NotificationDisplay(&n)); debug!("Handling missed notification: {}", NotificationDisplay(&n));
self.handle_notification(n) self.handle_notification(n).await.log_error("Error handling a notification");
.await
.log_error("Error handling a notification");
} }
Ok(true) Ok(true)

View file

@ -249,19 +249,13 @@ mod tests {
assert!(!group.is_member_only()); assert!(!group.is_member_only());
assert!(!group.is_member("piggo@piggo.space")); assert!(!group.is_member("piggo@piggo.space"));
assert!(!group.is_admin("piggo@piggo.space")); assert!(!group.is_admin("piggo@piggo.space"));
assert!( assert!(group.can_write("piggo@piggo.space"), "anyone can post by default");
group.can_write("piggo@piggo.space"),
"anyone can post by default"
);
} }
#[test] #[test]
fn test_member_only() { fn test_member_only() {
let mut group = GroupConfig::default(); let mut group = GroupConfig::default();
assert!( assert!(group.can_write("piggo@piggo.space"), "rando can write in public group");
group.can_write("piggo@piggo.space"),
"rando can write in public group"
);
group.set_member_only(true); group.set_member_only(true);
assert!( assert!(
@ -299,10 +293,7 @@ mod tests {
// Banning single user // Banning single user
let mut group = GroupConfig::default(); let mut group = GroupConfig::default();
group.ban_user("piggo@piggo.space", true).unwrap(); group.ban_user("piggo@piggo.space", true).unwrap();
assert!( assert!(!group.can_write("piggo@piggo.space"), "banned user can't post");
!group.can_write("piggo@piggo.space"),
"banned user can't post"
);
group.ban_user("piggo@piggo.space", false).unwrap(); group.ban_user("piggo@piggo.space", false).unwrap();
assert!(group.can_write("piggo@piggo.space"), "un-ban works"); assert!(group.can_write("piggo@piggo.space"), "un-ban works");
} }
@ -316,25 +307,13 @@ mod tests {
group.set_member("piggo@piggo.space", true).unwrap(); group.set_member("piggo@piggo.space", true).unwrap();
assert!(group.can_write("piggo@piggo.space"), "member can write"); assert!(group.can_write("piggo@piggo.space"), "member can write");
assert!(group.is_member("piggo@piggo.space"), "member is member"); assert!(group.is_member("piggo@piggo.space"), "member is member");
assert!( assert!(!group.is_banned("piggo@piggo.space"), "user not banned by default");
!group.is_banned("piggo@piggo.space"),
"user not banned by default"
);
group.ban_user("piggo@piggo.space", true).unwrap(); group.ban_user("piggo@piggo.space", true).unwrap();
assert!( assert!(group.is_member("piggo@piggo.space"), "still member even if banned");
group.is_member("piggo@piggo.space"), assert!(group.is_banned("piggo@piggo.space"), "banned user is banned");
"still member even if banned"
);
assert!(
group.is_banned("piggo@piggo.space"),
"banned user is banned"
);
assert!( assert!(!group.can_write("piggo@piggo.space"), "banned member can't post");
!group.can_write("piggo@piggo.space"),
"banned member can't post"
);
// unban // unban
group.ban_user("piggo@piggo.space", false).unwrap(); group.ban_user("piggo@piggo.space", false).unwrap();
@ -355,10 +334,7 @@ mod tests {
!group.can_write("1488@nazi.camp"), !group.can_write("1488@nazi.camp"),
"users from banned server can't write" "users from banned server can't write"
); );
assert!( assert!(group.can_write("troll@freezepeach.xyz"), "other users can still write");
group.can_write("troll@freezepeach.xyz"),
"other users can still write"
);
group.ban_server("nazi.camp", false).unwrap(); group.ban_server("nazi.camp", false).unwrap();
assert!(group.can_write("hitler@nazi.camp"), "server unban works"); assert!(group.can_write("hitler@nazi.camp"), "server unban works");
@ -374,9 +350,7 @@ mod tests {
group.ban_user("piggo@piggo.space", true), group.ban_user("piggo@piggo.space", true),
"can't bad admin users" "can't bad admin users"
); );
group group.ban_user("piggo@piggo.space", false).expect("can unbad admin");
.ban_user("piggo@piggo.space", false)
.expect("can unbad admin");
group.ban_user("hitler@nazi.camp", true).unwrap(); group.ban_user("hitler@nazi.camp", true).unwrap();
assert_eq!( assert_eq!(

View file

@ -54,10 +54,7 @@ impl ConfigStore {
} }
/// Spawn a new group /// Spawn a new group
pub async fn auth_new_group( pub async fn auth_new_group(self: &Arc<Self>, opts: NewGroupOptions) -> Result<GroupHandle, GroupError> {
self: &Arc<Self>,
opts: NewGroupOptions,
) -> Result<GroupHandle, GroupError> {
let registration = Registration::new(&opts.server) let registration = Registration::new(&opts.server)
.client_name("group-actor") .client_name("group-actor")
.force_login(true) .force_login(true)
@ -84,10 +81,7 @@ impl ConfigStore {
/// Re-auth an existing group /// Re-auth an existing group
pub async fn reauth_group(self: &Arc<Self>, acct: &str) -> Result<GroupHandle, GroupError> { pub async fn reauth_group(self: &Arc<Self>, acct: &str) -> Result<GroupHandle, GroupError> {
let groups = self.data.read().await; let groups = self.data.read().await;
let mut config = groups let mut config = groups.get_group_config(acct).ok_or(GroupError::GroupNotExist)?.clone();
.get_group_config(acct)
.ok_or(GroupError::GroupNotExist)?
.clone();
println!("--- Re-authenticating bot user @{} ---", acct); println!("--- Re-authenticating bot user @{} ---", acct);
let registration = Registration::new(config.get_appdata().base.to_string()) let registration = Registration::new(config.get_appdata().base.to_string())

View file

@ -22,10 +22,7 @@ pub(crate) fn acct_to_server(acct: &str) -> Option<&str> {
acct.trim_start_matches('@').split('@').nth(1) acct.trim_start_matches('@').split('@').nth(1)
} }
pub(crate) fn normalize_acct<'a, 'g>( pub(crate) fn normalize_acct<'a, 'g>(acct: &'a str, group: &'g str) -> Result<Cow<'a, str>, GroupError> {
acct: &'a str,
group: &'g str,
) -> Result<Cow<'a, str>, GroupError> {
let acct = acct.trim_start_matches('@'); let acct = acct.trim_start_matches('@');
if acct_to_server(acct).is_some() { if acct_to_server(acct).is_some() {
// already has server // already has server
@ -82,9 +79,6 @@ mod test {
Ok("piggo@piggo.space".into()), Ok("piggo@piggo.space".into()),
normalize_acct("piggo@piggo.space", "uhh") normalize_acct("piggo@piggo.space", "uhh")
); );
assert_eq!( assert_eq!(Err(GroupError::BadConfig("_".into())), normalize_acct("piggo", "uhh"));
Err(GroupError::BadConfig("_".into())),
normalize_acct("piggo", "uhh")
);
} }
} }