Compare commits
8
Commits
9aee5ab2a5
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38f849e323
|
||
|
|
233a0944c7 | ||
|
|
0ed1871042
|
||
|
|
bf6ccc6df1
|
||
|
|
624d90f3c9
|
||
|
|
db0eb7db5e
|
||
|
|
19877c0ac4
|
||
|
|
982fb7e091
|
No files matched your search
Generated
+874
-310
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -15,5 +15,5 @@ serde_json = "1.0"
|
|||||||
tracing-subscriber = "0.3.18"
|
tracing-subscriber = "0.3.18"
|
||||||
clap = { version = "4.6.7", features = ["derive"] }
|
clap = { version = "4.6.7", features = ["derive"] }
|
||||||
tokio = { version = "1.41", features = ["macros", "rt-multi-thread"] }
|
tokio = { version = "1.41", features = ["macros", "rt-multi-thread"] }
|
||||||
matrix-sdk = { version = "0.8.0", default-features = false, features = [ "native-tls", "anyhow", "markdown" ] }
|
matrix-sdk = { version = "0.18.0", default-features = false, features = [ "anyhow", "markdown" ] }
|
||||||
rumqttc = "0.25"
|
rumqttc = "0.25"
|
||||||
@@ -9,6 +9,8 @@ mqtt:
|
|||||||
rooms:
|
rooms:
|
||||||
- "!iFCnqQcvrVIeehrjQO:chat.labolyon.fr"
|
- "!iFCnqQcvrVIeehrjQO:chat.labolyon.fr"
|
||||||
|
|
||||||
|
debounce_delay: 10 # seconds
|
||||||
|
|
||||||
# username / password login
|
# username / password login
|
||||||
# /!\ will create a new device every time the bot starts
|
# /!\ will create a new device every time the bot starts
|
||||||
username: "login"
|
username: "login"
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ pub enum AuthConfig {
|
|||||||
pub struct Config {
|
pub struct Config {
|
||||||
pub mqtt: MQTTConfig,
|
pub mqtt: MQTTConfig,
|
||||||
pub rooms: Vec<String>,
|
pub rooms: Vec<String>,
|
||||||
|
pub debounce_delay: u64,
|
||||||
#[serde(flatten)]
|
#[serde(flatten)]
|
||||||
pub auth: AuthConfig,
|
pub auth: AuthConfig,
|
||||||
pub homeserver_uri: String
|
pub homeserver_uri: String
|
||||||
|
|||||||
+73
-15
@@ -17,12 +17,15 @@
|
|||||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#![recursion_limit = "256"]
|
||||||
|
|
||||||
mod config;
|
mod config;
|
||||||
mod matrix;
|
mod matrix;
|
||||||
mod mqtt;
|
mod mqtt;
|
||||||
|
|
||||||
use tokio::{
|
use tokio::{
|
||||||
sync::{Notify, broadcast},
|
sync::{Notify, broadcast, mpsc},
|
||||||
|
time::{sleep, Duration},
|
||||||
task::JoinHandle,
|
task::JoinHandle,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -46,11 +49,16 @@ struct Args {
|
|||||||
config: String,
|
config: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(PartialEq)]
|
#[derive(PartialEq, Clone, Copy, Debug)]
|
||||||
enum LolOpenerStatus {
|
enum DoorSensorStatus {
|
||||||
Open,
|
Open,
|
||||||
Closed,
|
Closed,
|
||||||
}
|
}
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct LolOpenerState {
|
||||||
|
sensor_status: Option<DoorSensorStatus>,
|
||||||
|
pending: Option<(DoorSensorStatus, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
@@ -78,25 +86,75 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
matrix_ready.notified().await;
|
matrix_ready.notified().await;
|
||||||
info!("Matrix is ready");
|
info!("Matrix is ready");
|
||||||
|
|
||||||
let current_status = Arc::new(Mutex::new(None));
|
let current_state = Arc::new(Mutex::new(LolOpenerState {
|
||||||
let current_status = Arc::clone(¤t_status);
|
sensor_status: None,
|
||||||
|
pending: None
|
||||||
|
}));
|
||||||
|
let current_state = Arc::clone(¤t_state);
|
||||||
|
|
||||||
|
let (debounce_tx, mut debounce_rx) = mpsc::unbounded_channel::<(DoorSensorStatus, String)>();
|
||||||
|
let debounce_delay = config.debounce_delay;
|
||||||
|
let rooms = config.rooms.clone();
|
||||||
|
let handle = tokio::spawn(async move {
|
||||||
|
|
||||||
|
while let Some((new_status, msg)) = debounce_rx.recv().await {
|
||||||
|
let should_wait = {
|
||||||
|
//XXX: Panic if the lock is poisoned
|
||||||
|
let mut state = current_state.lock().unwrap();
|
||||||
|
let should_wait = state.pending.is_none();
|
||||||
|
|
||||||
|
state.pending = Some((new_status, msg));
|
||||||
|
should_wait
|
||||||
|
};
|
||||||
|
|
||||||
|
if should_wait {
|
||||||
|
let tx = bcast_tx.clone();
|
||||||
|
let rooms = rooms.clone();
|
||||||
|
let state = current_state.clone();
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
sleep(Duration::from_secs(debounce_delay)).await;
|
||||||
|
|
||||||
|
let msg = {
|
||||||
|
//XXX: Panic if the lock is poisoned
|
||||||
|
let mut state = state.lock().unwrap();
|
||||||
|
let pending = state.pending.take();
|
||||||
|
|
||||||
|
match pending {
|
||||||
|
Some((status, msg))
|
||||||
|
if state.sensor_status.as_ref() != Some(&status) => {
|
||||||
|
state.sensor_status = Some(status);
|
||||||
|
Some(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(msg) = msg {
|
||||||
|
debug!("Sending msg {}", msg);
|
||||||
|
//XXX: Panic if the matrix module can't get the message
|
||||||
|
tx.send((msg, rooms)).unwrap();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
let mut mqtt = MQTT::new(config.mqtt.clone()).await;
|
let mut mqtt = MQTT::new(config.mqtt.clone()).await;
|
||||||
mqtt.subscribe(move |status: StatusMessage| {
|
mqtt.subscribe(move |status: StatusMessage| {
|
||||||
let (new_status, msg) = match status {
|
let (new_status, msg) = match status {
|
||||||
StatusMessage { contact: true, .. } => (Some(LolOpenerStatus::Closed), "🔴 Le LOL est fermé :("),
|
StatusMessage { contact: true, .. } => (DoorSensorStatus::Closed, "🔴 Le LOL est fermé :("),
|
||||||
StatusMessage { contact: false, .. } => (Some(LolOpenerStatus::Open), "🟢 Le LOL est ouvert :)"),
|
StatusMessage { contact: false, .. } => (DoorSensorStatus::Open, "🟢 Le LOL est ouvert :)"),
|
||||||
};
|
};
|
||||||
|
|
||||||
//XXX: Panic if the lock is poisoned (why would that happen?)
|
//XXX: Panic if the channel is closed
|
||||||
let mut current_status = current_status.lock().unwrap();
|
debounce_tx.send((new_status, String::from(msg))).unwrap();
|
||||||
if new_status != *current_status {
|
|
||||||
debug!("Sending msg {}", msg);
|
|
||||||
//XXX: Panic if the matrix module can't get the message
|
|
||||||
bcast_tx.send((msg.into(), config.rooms.clone())).unwrap();
|
|
||||||
*current_status = new_status;
|
|
||||||
}
|
|
||||||
}).await.unwrap(); //XXX: Panic if the mqtt broker fails
|
}).await.unwrap(); //XXX: Panic if the mqtt broker fails
|
||||||
|
|
||||||
|
handle.abort();
|
||||||
|
handle.await.unwrap();
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+44
-13
@@ -18,16 +18,20 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
use matrix_sdk::{
|
use matrix_sdk::{
|
||||||
matrix_auth::{
|
authentication::{
|
||||||
MatrixAuth,
|
matrix::{
|
||||||
MatrixSession,
|
MatrixAuth,
|
||||||
MatrixSessionTokens
|
MatrixSession,
|
||||||
|
},
|
||||||
|
SessionTokens,
|
||||||
},
|
},
|
||||||
SessionMeta,
|
SessionMeta,
|
||||||
|
store::RoomLoadSettings,
|
||||||
config::SyncSettings,
|
config::SyncSettings,
|
||||||
ruma::events::room::{
|
ruma::events::room::{
|
||||||
member::StrippedRoomMemberEvent,
|
member::StrippedRoomMemberEvent,
|
||||||
message::RoomMessageEventContent
|
message::RoomMessageEventContent,
|
||||||
|
pinned_events::RoomPinnedEventsEventContent,
|
||||||
},
|
},
|
||||||
ruma::{RoomId, OwnedUserId, device_id},
|
ruma::{RoomId, OwnedUserId, device_id},
|
||||||
Client, Room
|
Client, Room
|
||||||
@@ -41,7 +45,7 @@ use tokio::{
|
|||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use tracing::{error, info};
|
use tracing::{error, info, debug};
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
|
|
||||||
use crate::config::AuthConfig;
|
use crate::config::AuthConfig;
|
||||||
@@ -51,6 +55,7 @@ async fn on_stripped_state_member(
|
|||||||
client: Client,
|
client: Client,
|
||||||
room: Room,
|
room: Room,
|
||||||
) {
|
) {
|
||||||
|
//XXX: Panic if authentication has failed
|
||||||
if room_member.state_key != client.user_id().unwrap() {
|
if room_member.state_key != client.user_id().unwrap() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -86,16 +91,39 @@ async fn send_to_room(
|
|||||||
match room.client().join_room_by_id(room.room_id()).await {
|
match room.client().join_room_by_id(room.room_id()).await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
info!("Posting to room {}", room.room_id());
|
info!("Posting to room {}", room.room_id());
|
||||||
room.send(RoomMessageEventContent::text_html(msg.clone(), msg)).await?;
|
let res = room.send(RoomMessageEventContent::text_html(msg.clone(), msg)).await?;
|
||||||
|
|
||||||
return Ok(());
|
debug!("Retrieving list of pinned events");
|
||||||
|
let mut old_pinned_eids = room.pinned_event_ids().unwrap_or_default();
|
||||||
|
let mut new_pinned_eids = Vec::with_capacity(old_pinned_eids.len());
|
||||||
|
|
||||||
|
for eid in old_pinned_eids.drain(..) {
|
||||||
|
match room.event(eid.as_ref(), None).await {
|
||||||
|
Ok(ev) => {
|
||||||
|
let client = room.client();
|
||||||
|
|
||||||
|
if client.user_id() != ev.sender().as_deref() {
|
||||||
|
new_pinned_eids.push(eid);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(err) => {
|
||||||
|
error!("Failed to retrieve pinned event {eid:?}: {err:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
info!("Updating pinned events");
|
||||||
|
new_pinned_eids.push(res.response.event_id);
|
||||||
|
room.send_state_event(RoomPinnedEventsEventContent::new(new_pinned_eids)).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("Failed to join room {e:?}");
|
error!("Failed to join room {e:?}");
|
||||||
|
|
||||||
return Err(e.into());
|
Err(e.into())
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn login(
|
async fn login(
|
||||||
@@ -105,7 +133,9 @@ async fn login(
|
|||||||
match auth_config {
|
match auth_config {
|
||||||
AuthConfig::PasswordAuthConfig{username, password} => {
|
AuthConfig::PasswordAuthConfig{username, password} => {
|
||||||
matrix_auth.login_username(username, password)
|
matrix_auth.login_username(username, password)
|
||||||
.initial_device_display_name("bender v0.2.0").await?;
|
.initial_device_display_name(
|
||||||
|
format!("{} v{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")).as_str()
|
||||||
|
).await?;
|
||||||
},
|
},
|
||||||
AuthConfig::TokenAuthConfig{user_id, device_id, access_token} => {
|
AuthConfig::TokenAuthConfig{user_id, device_id, access_token} => {
|
||||||
matrix_auth.restore_session(
|
matrix_auth.restore_session(
|
||||||
@@ -114,11 +144,12 @@ async fn login(
|
|||||||
user_id: <OwnedUserId>::try_from(user_id.as_str())?,
|
user_id: <OwnedUserId>::try_from(user_id.as_str())?,
|
||||||
device_id: device_id!(device_id.as_str()).to_owned(),
|
device_id: device_id!(device_id.as_str()).to_owned(),
|
||||||
},
|
},
|
||||||
tokens: MatrixSessionTokens {
|
tokens: SessionTokens {
|
||||||
access_token: access_token.to_owned(),
|
access_token: access_token.to_owned(),
|
||||||
refresh_token: None,
|
refresh_token: None,
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
RoomLoadSettings::All
|
||||||
).await?;
|
).await?;
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user