WIP: Add !create
This commit is contained in:
parent
ac21f1bf6e
commit
3e016a6486
File diff suppressed because it is too large
Load Diff
|
@ -4,3 +4,12 @@ version = "0.1.0"
|
|||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.89"
|
||||
clap = { version = "4.5.18", features = [ "derive", "env" ] }
|
||||
js_int = { version = "0.2.2", features = [ "serde" ] }
|
||||
lazy-regex = "3.3.0"
|
||||
matrix-sdk = { version = "0.7.1", features = [ "anyhow" ] }
|
||||
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];
|
||||
}
|
||||
];
|
||||
};
|
||||
|
|
|
@ -0,0 +1,271 @@
|
|||
use anyhow::bail;
|
||||
use anyhow::Result;
|
||||
use lazy_regex::regex_captures;
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
|
||||
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::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::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 super::events;
|
||||
use super::events::my_room_member::FiskenState;
|
||||
use super::events::my_room_member::FiskenType;
|
||||
use events::my_room_member::RoomMemberEventContent as myRoomMemberEventContent;
|
||||
|
||||
/// 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();
|
||||
let name = name.to_owned();
|
||||
if name == "" {
|
||||
let content = RoomMessageEventContent::text_plain("command: !create <name>");
|
||||
room.send(content).await.unwrap();
|
||||
}
|
||||
|
||||
tokio::spawn(actually_create(name, event, room, client));
|
||||
}
|
||||
|
||||
/// Actually create a new CTF-space
|
||||
pub async fn actually_create(
|
||||
name: String,
|
||||
event: OriginalSyncRoomMessageEvent,
|
||||
room: Room,
|
||||
client: Client,
|
||||
) {
|
||||
// Create main space
|
||||
let space = match create_main(&name, &room, client.clone()).await {
|
||||
Ok(space) => space,
|
||||
Err(e) => {
|
||||
println!("{e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// 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_room(
|
||||
name: &str,
|
||||
parent: &Room,
|
||||
client: Client,
|
||||
room_type: Option<RoomType>,
|
||||
) -> anyhow::Result<Room> {
|
||||
println!("Creating room: {name}");
|
||||
// Create a room
|
||||
let mut creation_content = CreationContent::new();
|
||||
creation_content.room_type = room_type;
|
||||
|
||||
// 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::Restricted(restriction);
|
||||
let join_rule_content = RoomJoinRulesEventContent::new(join_rule);
|
||||
let join_rule_state = InitialStateEvent::<RoomJoinRulesEventContent>::new(join_rule_content);
|
||||
|
||||
// Copy PLs from the parent room
|
||||
let mut delay = 2;
|
||||
let mut parent_pl = loop {
|
||||
let maybe_parent_pl = parent
|
||||
.get_state_event_static::<RoomPowerLevelsEventContent>()
|
||||
.await?;
|
||||
|
||||
if let Some(raw) = maybe_parent_pl {
|
||||
let pl = match raw.deserialize()? {
|
||||
SyncOrStrippedState::Sync(SyncStateEvent::Original(ev)) => ev.content,
|
||||
_ => todo!(),
|
||||
};
|
||||
|
||||
break pl;
|
||||
}
|
||||
|
||||
println!("Couldn't get PLs, waiting {delay}: {:?}", maybe_parent_pl);
|
||||
sleep(Duration::from_secs(delay)).await;
|
||||
delay *= 2;
|
||||
|
||||
if delay > 3600 {
|
||||
bail!("Couldn't get power-level event from parent-room");
|
||||
}
|
||||
};
|
||||
|
||||
// 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.to_string());
|
||||
request.power_level_content_override = Some(Raw::new(&plec).unwrap());
|
||||
|
||||
let room = client.create_room(request).await?;
|
||||
|
||||
// Get the pfp and display name of the bot from the !create room
|
||||
let parent_member = match parent
|
||||
.get_state_event_static_for_key::<myRoomMemberEventContent, _>(
|
||||
&client.user_id().unwrap().to_owned(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Some(RawSyncOrStrippedState::Sync(r)) => match r.deserialize()? {
|
||||
SyncStateEvent::Original(e) => e.content,
|
||||
_ => todo!(),
|
||||
},
|
||||
_ => todo!(),
|
||||
};
|
||||
|
||||
// Get member event to edit
|
||||
let mut new_member_event = match parent
|
||||
.get_state_event_static_for_key::<myRoomMemberEventContent, _>(
|
||||
&client.user_id().unwrap().to_owned(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Some(RawSyncOrStrippedState::Sync(r)) => match r.deserialize()? {
|
||||
SyncStateEvent::Original(e) => e.content,
|
||||
_ => todo!(),
|
||||
},
|
||||
_ => todo!(),
|
||||
};
|
||||
|
||||
new_member_event.avatar_url = parent_member.avatar_url;
|
||||
new_member_event.displayname = parent_member.displayname;
|
||||
|
||||
room.send_state_event_for_key(client.user_id().unwrap(), new_member_event)
|
||||
.await?;
|
||||
|
||||
return Ok(room);
|
||||
}
|
||||
|
||||
async fn create_command(name: &str, parent: &Room, client: Client) -> Result<Room> {
|
||||
let command_room = create_room(name, parent, client.clone(), None).await?;
|
||||
|
||||
// Get settings from room that issued !create
|
||||
let parent_member = match parent
|
||||
.get_state_event_static_for_key::<myRoomMemberEventContent, _>(
|
||||
&client.user_id().unwrap().to_owned(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Some(RawSyncOrStrippedState::Sync(r)) => match r.deserialize()? {
|
||||
SyncStateEvent::Original(e) => e.content,
|
||||
_ => todo!(),
|
||||
},
|
||||
_ => todo!(),
|
||||
};
|
||||
|
||||
// Get member event to edit
|
||||
let mut new_member_event = match parent
|
||||
.get_state_event_static_for_key::<myRoomMemberEventContent, _>(
|
||||
&client.user_id().unwrap().to_owned(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Some(RawSyncOrStrippedState::Sync(r)) => match r.deserialize()? {
|
||||
SyncStateEvent::Original(e) => e.content,
|
||||
_ => todo!(),
|
||||
},
|
||||
_ => todo!(),
|
||||
};
|
||||
|
||||
new_member_event.fisken_type = Some(FiskenType::Command);
|
||||
new_member_event.parent = Some(parent.room_id().to_owned());
|
||||
|
||||
command_room
|
||||
.send_state_event_for_key(client.user_id().unwrap(), new_member_event)
|
||||
.await?;
|
||||
|
||||
Ok(command_room)
|
||||
}
|
||||
|
||||
async fn create_main(name: &str, parent: &Room, client: Client) -> Result<Room> {
|
||||
let main = create_room(name, parent, client.clone(), Some(RoomType::Space)).await?;
|
||||
|
||||
// Get settings from room that issued !create
|
||||
let parent_member = match parent
|
||||
.get_state_event_static_for_key::<myRoomMemberEventContent, _>(
|
||||
&client.user_id().unwrap().to_owned(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Some(RawSyncOrStrippedState::Sync(r)) => match r.deserialize()? {
|
||||
SyncStateEvent::Original(e) => e.content,
|
||||
_ => todo!(),
|
||||
},
|
||||
_ => todo!(),
|
||||
};
|
||||
|
||||
// Get member event to edit
|
||||
let mut new_member_event = match parent
|
||||
.get_state_event_static_for_key::<myRoomMemberEventContent, _>(
|
||||
&client.user_id().unwrap().to_owned(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Some(RawSyncOrStrippedState::Sync(r)) => match r.deserialize()? {
|
||||
SyncStateEvent::Original(e) => e.content,
|
||||
_ => todo!(),
|
||||
},
|
||||
_ => todo!(),
|
||||
};
|
||||
|
||||
new_member_event.fisken_type = Some(FiskenType::Main);
|
||||
new_member_event.active_space = parent_member.active_space;
|
||||
new_member_event.archival_space = parent_member.archival_space;
|
||||
new_member_event.fisken_state = Some(FiskenState::Active);
|
||||
|
||||
main.send_state_event_for_key(client.user_id().unwrap(), new_member_event)
|
||||
.await?;
|
||||
|
||||
// Create a command-room
|
||||
main.sync_up().await;
|
||||
let command_room = create_command(&format!("🐠 - {name}"), &main, client.clone()).await?;
|
||||
|
||||
let mut space_child_command =
|
||||
SpaceChildEventContent::new(vec![client.user_id().unwrap().server_name().to_owned()]);
|
||||
space_child_command.order = Some("00".into());
|
||||
space_child_command.suggested = true;
|
||||
|
||||
main.send_state_event_for_key(command_room.room_id(), space_child_command)
|
||||
.await?;
|
||||
|
||||
Ok(main)
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
pub mod my_room_member;
|
|
@ -0,0 +1,163 @@
|
|||
// From https://github.com/ruma/ruma/blob/c06af4385e0e30c48a8e9ca3d488da32102d0db9/crates/ruma-events/src/room/member.rs
|
||||
// Then trimmed and added to
|
||||
// License: MIT
|
||||
|
||||
use matrix_sdk::ruma::events::macros::EventContent;
|
||||
use matrix_sdk::ruma::OwnedMxcUri;
|
||||
use matrix_sdk::ruma::OwnedRoomId;
|
||||
use matrix_sdk::ruma::OwnedUserId;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use matrix_sdk::ruma::events::room::member::{MembershipState, ThirdPartyInvite};
|
||||
|
||||
#[derive(Clone, Deserialize, Serialize, EventContent)]
|
||||
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
|
||||
#[ruma_event(
|
||||
type = "m.room.member",
|
||||
kind = State,
|
||||
state_key_type = OwnedUserId,
|
||||
)]
|
||||
pub struct RoomMemberEventContent {
|
||||
/// The avatar URL for this user, if any.
|
||||
///
|
||||
/// This is added by the homeserver. If you activate the `compat-empty-string-null` feature,
|
||||
/// this field being an empty string in JSON will result in `None` here during deserialization.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[cfg_attr(
|
||||
feature = "compat-empty-string-null",
|
||||
serde(default, deserialize_with = "ruma_common::serde::empty_string_as_none")
|
||||
)]
|
||||
pub avatar_url: Option<OwnedMxcUri>,
|
||||
|
||||
/// The display name for this user, if any.
|
||||
///
|
||||
/// This is added by the homeserver.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub displayname: Option<String>,
|
||||
|
||||
/// Flag indicating whether the room containing this event was created with the intention of
|
||||
/// being a direct chat.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_direct: Option<bool>,
|
||||
|
||||
/// The membership state of this user.
|
||||
pub membership: MembershipState,
|
||||
|
||||
/// If this member event is the successor to a third party invitation, this field will
|
||||
/// contain information about that invitation.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub third_party_invite: Option<ThirdPartyInvite>,
|
||||
|
||||
/// The [BlurHash](https://blurha.sh) for the avatar pointed to by `avatar_url`.
|
||||
///
|
||||
/// This uses the unstable prefix in
|
||||
/// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448).
|
||||
#[cfg(feature = "unstable-msc2448")]
|
||||
#[serde(
|
||||
rename = "xyz.amorgan.blurhash",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub blurhash: Option<String>,
|
||||
|
||||
/// User-supplied text for why their membership has changed.
|
||||
///
|
||||
/// For kicks and bans, this is typically the reason for the kick or ban. For other membership
|
||||
/// changes, this is a way for the user to communicate their intent without having to send a
|
||||
/// message to the room, such as in a case where Bob rejects an invite from Alice about an
|
||||
/// upcoming concert, but can't make it that day.
|
||||
///
|
||||
/// Clients are not recommended to show this reason to users when receiving an invite due to
|
||||
/// the potential for spam and abuse. Hiding the reason behind a button or other component
|
||||
/// is recommended.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub reason: Option<String>,
|
||||
|
||||
/// Arbitrarily chosen `UserId` (MxID) of a local user who can send an invite.
|
||||
#[serde(rename = "join_authorised_via_users_server")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub join_authorized_via_users_server: Option<OwnedUserId>,
|
||||
|
||||
// Custom fields for fiskebot
|
||||
/// What type of room is this?
|
||||
#[serde(
|
||||
rename = "xyz.dandellion.fisken.type",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub fisken_type: Option<FiskenType>,
|
||||
|
||||
/// Which space is this rooms canonical parent, according to fiskebot?
|
||||
#[serde(
|
||||
rename = "xyz.dandellion.fisken.parent",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub parent: Option<OwnedRoomId>,
|
||||
|
||||
/// Where should we add the room/space when it is active?
|
||||
#[serde(
|
||||
rename = "xyz.dandellion.fisken.archivespace",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub active_space: Option<OwnedRoomId>,
|
||||
|
||||
/// Where should we move this room to after its "done"?
|
||||
#[serde(
|
||||
rename = "xyz.dandellion.fisken.done",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub done_space: Option<OwnedRoomId>,
|
||||
|
||||
/// Where should we move the room when archiving?
|
||||
#[serde(
|
||||
rename = "xyz.dandellion.fisken.archivespace",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub archival_space: Option<OwnedRoomId>,
|
||||
|
||||
#[serde(
|
||||
rename = "xyz.dandellion.fisken.state",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub fisken_state: Option<FiskenState>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum FiskenType {
|
||||
#[serde(rename = "main")]
|
||||
Main,
|
||||
#[serde(rename = "command")]
|
||||
Command,
|
||||
#[serde(rename = "task")]
|
||||
Task,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum FiskenState {
|
||||
#[serde(rename = "active")]
|
||||
Active,
|
||||
#[serde(rename = "archived")]
|
||||
Archived,
|
||||
}
|
||||
|
||||
impl RoomMemberEventContent {
|
||||
/// Creates a new `RoomMemberEventContent` with the given membership state.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
membership: MembershipState::Join,
|
||||
avatar_url: None,
|
||||
displayname: None,
|
||||
is_direct: None,
|
||||
third_party_invite: None,
|
||||
#[cfg(feature = "unstable-msc2448")]
|
||||
blurhash: None,
|
||||
reason: None,
|
||||
join_authorized_via_users_server: None,
|
||||
fisken_type: None,
|
||||
parent: None,
|
||||
done_space: None,
|
||||
archival_space: None,
|
||||
active_space: None,
|
||||
fisken_state: None,
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
mod create;
|
||||
pub use create::*;
|
||||
|
||||
mod events;
|
|
@ -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());
|
||||
});
|
||||
}
|
66
src/main.rs
66
src/main.rs
|
@ -1,3 +1,65 @@
|
|||
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);
|
||||
|
||||
// let sync_settings = SyncSettings::new().full_state(true);
|
||||
let sync_settings = SyncSettings::new();
|
||||
|
||||
client.sync(sync_settings).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue