WIP
This commit is contained in:
parent
ac21f1bf6e
commit
4034c26635
3411
Cargo.lock
generated
Normal file
3411
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -4,3 +4,11 @@ version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.89"
|
||||
clap = { version = "4.5.18", features = [ "derive", "env" ] }
|
||||
lazy-regex = "3.3.0"
|
||||
matrix-sdk = "0.7.1"
|
||||
regex = "1.10.6"
|
||||
serde = "1.0.210"
|
||||
serde_json = "1.0.128"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
|
@ -37,6 +37,7 @@
|
||||
enable = true;
|
||||
channel = "stable"; # hmmm? bruker du ikke nightly? 😏😏😏
|
||||
};
|
||||
packages = with pkgs; [ openssl sqlite];
|
||||
}
|
||||
];
|
||||
};
|
||||
|
150
src/ctf/create.rs
Normal file
150
src/ctf/create.rs
Normal file
@ -0,0 +1,150 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use lazy_regex::regex_captures;
|
||||
use matrix_sdk::ruma::OwnedUserId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
use matrix_sdk::deserialized_responses::RawSyncOrStrippedState;
|
||||
use matrix_sdk::deserialized_responses::SyncOrStrippedState;
|
||||
use matrix_sdk::ruma::api::client::room::create_room::v3::CreationContent;
|
||||
use matrix_sdk::ruma::api::client::room::create_room::v3::Request as CreateRoomRequest;
|
||||
use matrix_sdk::ruma::events::macros::EventContent;
|
||||
use matrix_sdk::ruma::events::room::join_rules::AllowRule;
|
||||
use matrix_sdk::ruma::events::room::join_rules::JoinRule;
|
||||
use matrix_sdk::ruma::events::room::join_rules::Restricted;
|
||||
use matrix_sdk::ruma::events::room::join_rules::RoomJoinRulesEventContent;
|
||||
use matrix_sdk::ruma::events::room::member::RoomMemberEventContent;
|
||||
use matrix_sdk::ruma::events::room::member::RoomMemberUnsigned;
|
||||
use matrix_sdk::ruma::events::room::message::{
|
||||
MessageType, OriginalSyncRoomMessageEvent, RoomMessageEventContent,
|
||||
};
|
||||
use matrix_sdk::ruma::events::room::power_levels::RoomPowerLevelsEventContent;
|
||||
use matrix_sdk::ruma::events::InitialStateEvent;
|
||||
use matrix_sdk::ruma::events::SyncStateEvent;
|
||||
use matrix_sdk::ruma::room::RoomType;
|
||||
use matrix_sdk::ruma::serde::Raw;
|
||||
use matrix_sdk::ruma::Int;
|
||||
use matrix_sdk::{Client, Room, RoomState};
|
||||
use matrix_sdk::ruma::ruma_macros::EventContent;
|
||||
|
||||
/// Create a new CTF-space
|
||||
pub async fn create(event: OriginalSyncRoomMessageEvent, room: Room, client: Client) {
|
||||
if room.state() != RoomState::Joined {
|
||||
return;
|
||||
}
|
||||
|
||||
let MessageType::Text(text_content) = event.content.msgtype else {
|
||||
return;
|
||||
};
|
||||
|
||||
if !text_content.body.starts_with("!create") {
|
||||
return;
|
||||
}
|
||||
|
||||
let (_, name) = regex_captures!(r#"^!create (.+)$"#, &text_content.body,).unwrap();
|
||||
if name == "" {
|
||||
let content = RoomMessageEventContent::text_plain("command: !create <name>");
|
||||
room.send(content).await.unwrap();
|
||||
}
|
||||
|
||||
// Create main space
|
||||
let space = match create_space(name.into(), &room, client.clone()).await {
|
||||
Ok(space) => space,
|
||||
Err(e) => {
|
||||
println!("{e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// Add command channel
|
||||
|
||||
// Inform about the space
|
||||
let content = RoomMessageEventContent::text_plain(format!(
|
||||
"Created space: https://matrix.to/#/{}?via={}",
|
||||
space.room_id(),
|
||||
client.user_id().unwrap().server_name()
|
||||
));
|
||||
room.send(content).await.unwrap();
|
||||
}
|
||||
|
||||
async fn create_space(
|
||||
name: String,
|
||||
parent: &Room,
|
||||
client: Client,
|
||||
) -> Result<Room, matrix_sdk::Error> {
|
||||
// Create a space
|
||||
let mut creation_content = CreationContent::new();
|
||||
creation_content.room_type = Some(RoomType::Space);
|
||||
|
||||
// Allow members of the room where !create was issued to join the space
|
||||
let restriction = Restricted::new(vec![AllowRule::room_membership(
|
||||
parent.room_id().to_owned(),
|
||||
)]);
|
||||
let join_rule = JoinRule::KnockRestricted(restriction);
|
||||
let join_rule_content = RoomJoinRulesEventContent::new(join_rule);
|
||||
let join_rule_state = InitialStateEvent::<RoomJoinRulesEventContent>::new(join_rule_content);
|
||||
|
||||
// Copy PLs from the room where !create was issued
|
||||
let mut parent_pl = match parent
|
||||
.get_state_event_static::<RoomPowerLevelsEventContent>()
|
||||
.await?
|
||||
.expect("every room has a power_levels event")
|
||||
.deserialize()?
|
||||
{
|
||||
SyncOrStrippedState::Sync(SyncStateEvent::Original(ev)) => ev.content,
|
||||
_ => todo!(),
|
||||
};
|
||||
// Also make the bot Admin in the space
|
||||
parent_pl.users.insert(client.user_id().unwrap().to_owned(), Int::new_saturating(100));
|
||||
let mut plec = RoomPowerLevelsEventContent::new();
|
||||
plec.users = parent_pl.users;
|
||||
|
||||
// Actually create the room
|
||||
let mut request = CreateRoomRequest::new();
|
||||
request.creation_content = Some(Raw::new(&creation_content).unwrap());
|
||||
request.initial_state = vec![join_rule_state.to_raw_any()];
|
||||
request.name = Some(name);
|
||||
request.power_level_content_override = Some(Raw::new(&plec).unwrap());
|
||||
|
||||
|
||||
// Get the pfp and display name of the bot from the !create room
|
||||
let mut a = match parent.get_state_event_static_for_key::<RoomMemberEventContent, _>(client.user_id().unwrap()).await? {
|
||||
Some(RawSyncOrStrippedState::Sync(r)) => r,
|
||||
_ => todo!()
|
||||
};
|
||||
|
||||
let pfp = a.get_field::<String>("avatar_url")?.unwrap_or_default();
|
||||
let display_name = a.get_field::<String>("displayname")?.unwrap_or("Youmu".into());
|
||||
|
||||
// let mut raw_member = HashMap::new();
|
||||
// raw_member.insert("membership", "join");
|
||||
// raw_member.insert("displayname", &display_name);
|
||||
// raw_member.insert("avatar_url", &pfp);
|
||||
// raw_member.insert("xyz.dandellion.fisken.", &pfp);
|
||||
|
||||
|
||||
|
||||
|
||||
let space = client.create_room(request).await;
|
||||
|
||||
// if let Ok(space) = space {
|
||||
// spce
|
||||
// }
|
||||
|
||||
return space;
|
||||
}
|
||||
|
||||
#[derive(EventContent, Serialize, Deserialize)]
|
||||
#[ruma_event(
|
||||
type = "m.room.member",
|
||||
kind = State,
|
||||
state_key_type = OwnedUserId,
|
||||
unsigned_type = RoomMemberUnsigned,
|
||||
)]
|
||||
struct CustomRoomMemberEventContent {
|
||||
#[serde(flatten)]
|
||||
pub original_fields: RoomMemberEventContent,
|
||||
pub custom_field_a: String,
|
||||
pub custom_field_b: bool,
|
||||
}
|
2
src/ctf/mod.rs
Normal file
2
src/ctf/mod.rs
Normal file
@ -0,0 +1,2 @@
|
||||
mod create;
|
||||
pub use create::*;
|
38
src/invite.rs
Normal file
38
src/invite.rs
Normal file
@ -0,0 +1,38 @@
|
||||
// Stolen from https://github.com/matrix-org/matrix-rust-sdk/blob/5ba90611b43915926a37be83f3de1d4d53bca6bd/examples/autojoin/src/main.rs
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
use matrix_sdk::ruma::events::room::member::StrippedRoomMemberEvent;
|
||||
use matrix_sdk::{Client, Room};
|
||||
|
||||
pub async fn on_stripped_state_member(
|
||||
room_member: StrippedRoomMemberEvent,
|
||||
client: Client,
|
||||
room: Room,
|
||||
) {
|
||||
if room_member.state_key != client.user_id().unwrap() {
|
||||
return;
|
||||
}
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut delay = 2;
|
||||
|
||||
while let Err(err) = room.join().await {
|
||||
// retry autojoin due to synapse sending invites, before the
|
||||
// invited user can join for more information see
|
||||
// https://github.com/matrix-org/synapse/issues/4345
|
||||
eprintln!(
|
||||
"Failed to join room {} ({err:?}), retrying in {delay}s",
|
||||
room.room_id()
|
||||
);
|
||||
|
||||
sleep(Duration::from_secs(delay)).await;
|
||||
delay *= 2;
|
||||
|
||||
if delay > 3600 {
|
||||
eprintln!("Can't join room {} ({err:?})", room.room_id());
|
||||
break;
|
||||
}
|
||||
}
|
||||
println!("Successfully joined room {}", room.room_id());
|
||||
});
|
||||
}
|
63
src/main.rs
63
src/main.rs
@ -1,3 +1,62 @@
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Context;
|
||||
use clap::Parser;
|
||||
|
||||
use matrix_sdk::config::SyncSettings;
|
||||
use matrix_sdk::Client;
|
||||
|
||||
mod ctf;
|
||||
mod invite;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version, about, long_about = None)]
|
||||
struct Cli {
|
||||
/// Homeserver url for the bot-user
|
||||
/// Example: "https://matrix-client.matrix.org"
|
||||
#[arg(short = 's', long, value_name = "URL")]
|
||||
homeserver_url: String,
|
||||
/// username of the bot
|
||||
/// Example: "fisken"
|
||||
#[arg(short, long, value_name = "username")]
|
||||
username: String,
|
||||
/// A file containg the access token for the bot-user
|
||||
/// Example: "$CREDENTIALS_DIRECTORY/password"
|
||||
#[arg(short, long, value_name = "FILE")]
|
||||
password_file: PathBuf,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let cli = Cli::parse();
|
||||
|
||||
let password = fs::read_to_string(&cli.password_file).with_context(|| {
|
||||
format!(
|
||||
"Failed to read password from {}",
|
||||
&cli.password_file.display()
|
||||
)
|
||||
})?;
|
||||
let password = password.trim();
|
||||
|
||||
let client = Client::builder()
|
||||
.homeserver_url(cli.homeserver_url)
|
||||
.build()
|
||||
.await?;
|
||||
client
|
||||
.matrix_auth()
|
||||
.login_username(&cli.username, password)
|
||||
.initial_device_display_name("fischedubi")
|
||||
.await?;
|
||||
println!("logged in as {}", &cli.username);
|
||||
|
||||
client.sync_once(SyncSettings::default()).await?;
|
||||
|
||||
// Autojoin invites
|
||||
client.add_event_handler(invite::on_stripped_state_member);
|
||||
|
||||
client.add_event_handler(ctf::create);
|
||||
|
||||
client.sync(SyncSettings::default()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user