// Copyright (C) 2023-2099 The crate authors. // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Affero General Public License as published by the // Free Software Foundation, either version 3 of the License, or (at your // option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License // for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . #![feature(let_chains)] #![feature(never_type)] mod error; mod web; mod webhook; mod xmpp; use crate::error::Error; use crate::web::webhooks; use crate::webhook::WebHook; use crate::xmpp::XmppClient; use std::convert::Infallible; use std::fs::File; use std::io::{Error as IoError, ErrorKind as IoErrorKind, Read}; use std::net::{IpAddr, Ipv6Addr, SocketAddr}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use clap::Parser; use hyper::{ service::{make_service_fn, service_fn}, Server, }; use serde::{Deserialize, Serialize}; use tokio::sync::mpsc; use xmpp_parsers::BareJid; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Config file path #[arg(short, long)] config: Option, } #[derive(Debug, Serialize, Deserialize)] struct Config { /// Account address jid: BareJid, /// Account password password: String, /// Rooms to join, e.g., room@chat.example.org #[serde(default = "Vec::new")] rooms: Vec, /// Nickname to use in rooms #[serde(default = "default_nickname")] nickname: String, /// Token to match the one provided by the Webhook service #[serde(rename = "webhook-token")] webhook_token: Option, /// HTTP Webhook listening address and port, e.g., 127.0.0.1:1234 or [::1]:1234 #[serde(default = "default_addr")] addr: SocketAddr, } fn default_nickname() -> String { String::from("cusku") } fn default_addr() -> SocketAddr { SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 3000) } fn config_from_file(file: PathBuf) -> Result { if file.try_exists().is_err() { let err = IoError::new(IoErrorKind::NotFound, format!("{:?} not found", file)); return Err(Error::Io(err)); } let mut buf = String::new(); let mut f = File::open(file)?; f.read_to_string(&mut buf)?; Ok(toml::from_str(&buf)?) } #[tokio::main] async fn main() -> Result { pretty_env_logger::init(); let args = Args::parse(); let config = { let path = match args.config { Some(path) => { if !path.starts_with("/") { std::env::current_dir()?.join(path) } else { path } } None => { let confdir: PathBuf = match std::env::var("XDG_CONFIG_HOME") { Ok(ref dir) => Path::new(dir).to_path_buf(), Err(_) => { let home = std::env::var("HOME")?; Path::new(home.as_str()).join(".config") } }; confdir.join("cusku/config.toml") } }; match config_from_file(path) { Ok(config) => config, Err(err) => return Err(err), } }; let (value_tx, mut value_rx) = mpsc::unbounded_channel::(); if let Some(token) = config.webhook_token { let value_tx = Arc::new(Mutex::new(value_tx)); let make_svc = make_service_fn(move |_conn| { let value_tx = value_tx.clone(); let token = token.clone(); async move { Ok::<_, Infallible>(service_fn(move |req| { let value_tx = value_tx.clone(); let token = token.clone(); webhooks(req, token, value_tx) })) } }); let server = Server::bind(&config.addr).serve(make_svc); println!("Listening on http://{}", &config.addr); let _join = tokio::spawn(server); } let mut client = XmppClient::new( &String::from(config.jid), config.password.as_str(), config.rooms, config.nickname, ); loop { tokio::select! { _ = client.next() => (), wh = value_rx.recv() => { if let Some(wh) = wh { client.webhook(wh).await } } } } }