1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use uuid::Uuid;
use ruma::{DeviceKeyAlgorithm, RoomId, UserId, UInt, presence::PresenceState, serde::Raw, api::client::r0::sync::sync_events::*};
use std::collections::BTreeMap;
use ureq::{Agent, AgentBuilder, OrAnyStatus};
use serde::{Serialize, Deserialize};
use serde_json::{json, Value};
use std::time::{Instant, Duration};

pub mod macros;
pub mod essentials;
pub mod plugins;
mod instruction_generators;
use instruction_generators::RoomTypeData;
const BASE: &str = "/_matrix/client/v3/";
const TIME_TO_IDLE: Duration = Duration::from_secs(3 * 60);
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct StorageData {
    pub auth_token: String,
}

#[allow(dead_code)]
pub struct SonicBotEventModule<'a> {
    pub name: String,
    pub essential: bool,
    pub main: Box<dyn Fn(EventArgs<'a>) -> Vec<crate::Instructions>>,
    help: String,
}
#[derive(Debug, Clone)]
pub struct MessageArgs<'a> {
    pub message_info: MessageInfo,
    pub owner: UserId,
    pub ctrlc_handler: &'a ctrlc_handler::CtrlCHandler,
    pub cleanup_on_ctrlc: bool,
    pub prefix: String,
}

impl<'a> MessageArgs<'a> {
    pub fn new(message_info: MessageInfo, owner: UserId, ctrlc_handler: &'a ctrlc_handler::CtrlCHandler, cleanup_on_ctrlc: bool, prefix: String) -> Self {
        Self {
            message_info: message_info,
            owner: owner,
            ctrlc_handler: ctrlc_handler,
            cleanup_on_ctrlc: cleanup_on_ctrlc,
            prefix: prefix,
        }
    }
}


#[derive(Debug, Clone)]
pub struct EventArgs<'a> {
    pub room_data: crate::instruction_generators::RoomTypeData,
    pub starting: bool,
    pub ctrlc_handler: &'a ctrlc_handler::CtrlCHandler,
    pub cleanup_on_ctrlc: bool,
    pub owner: UserId,
    pub prefix: String,
    pub me: UserId,
}

impl<'a> EventArgs<'a> {
    pub fn new(room_data: crate::instruction_generators::RoomTypeData, starting: bool, ctrlc_handler: &'a ctrlc_handler::CtrlCHandler, cleanup_on_ctrlc: bool, owner: UserId, prefix: String, me: UserId) -> Self {
        Self {
            room_data: room_data,
            starting: starting,
            ctrlc_handler: ctrlc_handler,
            cleanup_on_ctrlc: cleanup_on_ctrlc,
            owner: owner,
            prefix: prefix,
            me: me,
        }
    }
}

pub struct SonicBotMessageModule<'a> {
    pub name: String,
    pub essential: bool,
    pub main: Box<dyn Fn(MessageArgs<'a>) -> Vec<crate::Instructions>>,
    pub help: String,
}

pub fn generate_module_names(glob_results: glob::Paths) -> Vec<String> {
    let mut module_names: Vec<String> = Vec::new();
    for r in glob_results {
        let file_name: String = r.unwrap().as_path().file_name().unwrap().to_str().unwrap().to_string();
        let module_name = file_name.split(".").collect::<Vec<&str>>()[0];
        if module_name != "mod" {
            module_names.push(module_name.to_string());
        }
    }
    module_names.sort_by(|a, b| a.to_lowercase().cmp(&b.to_lowercase()));
    module_names
}

#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct EventResponse {
    /// The batch token to supply in the `since` param of the next `/sync` request.
    pub next_batch: String,

    /// Updates to rooms.
    #[serde(default, skip_serializing_if = "Rooms::is_empty")]
    pub rooms: Rooms,

    /// Updates to the presence status of other users.
    #[serde(default, skip_serializing_if = "Presence::is_empty")]
    pub presence: Presence,

    /// The global private data created by this user.
    #[serde(default, skip_serializing_if = "GlobalAccountData::is_empty")]
    pub account_data: GlobalAccountData,

    /// Messages sent directly between devices.
    #[serde(default, skip_serializing_if = "ToDevice::is_empty")]
    pub to_device: ToDevice,

    /// Information on E2E device updates.
    ///
    /// Only present on an incremental sync.
    #[serde(default, skip_serializing_if = "DeviceLists::is_empty")]
    pub device_lists: DeviceLists,

    /// For each key algorithm, the number of unclaimed one-time keys
    /// currently held on the server for a device.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub device_one_time_keys_count: BTreeMap<DeviceKeyAlgorithm, UInt>,

    /// For each key algorithm, the number of unclaimed one-time keys
    /// currently held on the server for a device.
    ///
    /// The presence of this field indicates that the server supports
    /// fallback keys.
    #[serde(rename = "org.matrix.msc2732.device_unused_fallback_key_types")]
    pub device_unused_fallback_key_types: Option<Vec<DeviceKeyAlgorithm>>,
}

#[derive(Debug)]
pub struct SonicBot {
    data: StorageData,
    host: String,
    me: UserId,
    agent: Agent,
    joined_rooms: Vec<ruma::RoomId>,
    since: Option<String>,
    last_response_time: Instant,
    starting: bool,
    ctrlc_handler: ctrlc_handler::CtrlCHandler,
    cleanup_on_ctrlc: bool,
    prefix: String,
    owner: UserId,
}
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum Instructions {
    UpdateLastResponseTime(Instant),
    AddRoom(ruma::RoomId),
    Quit(bool),
    DelRoom(ruma::RoomId),
    SetSince(String),
    SendMessage(RoomId, String)
}

#[derive(PartialEq, Eq, Debug, Clone)]
pub struct MessageInfo {
    pub message: String,
    pub words: Vec<String>,
    pub args: Vec<String>,
    pub sender: UserId,
    pub room_id: RoomId,
}
impl SonicBot {
    pub fn new(host: impl Into<String>, username: impl Into<String>, server_name: impl Into<String>, cleanup_on_ctrlc: bool, prefix: impl Into<String>, owner: impl Into<String>) -> Self {
        Self {
            data: StorageData::default(),
            host: host.into().trim_end_matches("/").to_string(),
            me: UserId::try_from(format!("@{}:{}",  username.into(), server_name.into()).as_str()).unwrap(),
            agent: AgentBuilder::new().timeout_read(Duration::from_secs(3)).build(),
            joined_rooms: Vec::new(),
            since: None,
            //last_event: EventResponse::default(),
            last_response_time: Instant::now(),
            starting: true,
            ctrlc_handler: ctrlc_handler::CtrlCHandler::new(),
            cleanup_on_ctrlc: cleanup_on_ctrlc,
            prefix: prefix.into(),
            owner: UserId::try_from(owner.into()).unwrap(),
        }
    }
    fn login(&self, password: String) -> String {
        let content = json!({
            "type": "m.login.password",
            "identifier": {
                "type": "m.id.user",
                "user": self.me.localpart()
            },
            "password": password
        });
        let val: Value = self.post("login", content, None).unwrap().into_json().unwrap();
        println!("{:?}", val);
        val["access_token"].as_str().unwrap().to_string()
    }
    fn post(&self, url_ext: impl Into<String>, content: Value, query_pairs: Option<Vec<(String, String)>>) -> Result<ureq::Response, ureq::Transport> {
        let mut r = self.agent.post(format!("{}{}{}", self.host, BASE, url_ext.into()).as_str()).set("Authorization", format!("Bearer {}", self.data.auth_token).as_str());
        if let Some(pairs) = query_pairs {
            for pair in pairs {
                r = r.query(pair.0.as_str(), pair.1.as_str());
            }
        }
        r.send_json(content).or_any_status()
    }
    fn put(&self, url_ext: impl Into<String>, content: Value, query_pairs: Option<Vec<(String, String)>>) -> Result<ureq::Response, ureq::Transport> {
        let mut r = self.agent.put(format!("{}{}{}", self.host, BASE, url_ext.into()).as_str()).set("Authorization", format!("Bearer {}", self.data.auth_token).as_str());
        if let Some(pairs) = query_pairs {
            for pair in pairs {
                r = r.query(pair.0.as_str(), pair.1.as_str());
            }
        }
        r.send_json(content).or_any_status()
    }
    fn get(&self, url_ext: impl Into<String>, query_pairs: Option<Vec<(String, String)>>) -> Result<ureq::Response, ureq::Transport> {
        let mut r = self.agent.get(format!("{}{}{}", self.host, BASE, url_ext.into()).as_str()).set("Authorization", format!("Bearer {}", self.data.auth_token).as_str());
        if let Some(pairs) = query_pairs {
            for pair in pairs {
                r = r.query(pair.0.as_str(), pair.1.as_str());
            }
        }
        r.call().or_any_status()
    }
    fn join_room_id(&self, room_id: ruma::RoomId) -> Value {
        //let room_string = room_id_or_alias.into();
        //let serv_name = server_name.into();
        let rid = room_id.to_string();
        let room = urlencoding::encode(rid.as_str());
        let content = json!({});
        self.post(format!("rooms/{}/join", room).as_str(), content, None).unwrap().into_json().unwrap()
    }
    fn sync(&self) -> Result<EventResponse, Value> {
        //let mut r = self.get("sync")
        let presence = self.calculate_presence();
        let req: ureq::Response;
        if let Some(start) = self.since.clone() {
            req = self.get("sync", Some(vec![("since".to_string(), start), ("full_state".to_string(), "false".to_string()), ("set_presence".to_string(), format!("{}", presence)), ("timeout".to_string(), "3000".to_string())])).unwrap();
        } else {
            req = self.get("sync", Some(vec![("full_state".to_string(), "true".to_string()), ("set_presence".to_string(), format!("{}", presence)), ("timeout".to_string(), "3000".to_string())])).unwrap();
        }
        let val: Value = req.into_json().unwrap();
        println!("{}", val.to_string());
        if val.clone().as_object().unwrap().contains_key("error") {
            Err(val)
        } else {
            Ok(serde_json::from_str::<Raw<EventResponse>>(val.to_string().as_str()).unwrap().deserialize().unwrap())
        }
    }
    fn calculate_presence(&self) -> PresenceState {
        if self.last_response_time.elapsed() > TIME_TO_IDLE {
            PresenceState::Unavailable
        } else {
            PresenceState::Online
        }
    }
    fn process_instructions(&mut self, instructions: Vec<Instructions>) -> Option<String> {
        if instructions.contains(&Instructions::Quit(false)) {
            std::process::exit(0);
        }
        for instruction in instructions {
            match instruction {
                Instructions::Quit(_x) => {
                    return Some("QUIT".to_string());
                },
                Instructions::DelRoom(x) => {
                    self.joined_rooms.retain(|z| z == &x);
                },
                Instructions::AddRoom(x) => {
                    if !self.joined_rooms.contains(&x) {
                        self.joined_rooms.push(x.clone());
                        self.join_room_id(x);
                    }
                },
                Instructions::UpdateLastResponseTime(x) => {
                    self.last_response_time = x;
                },
                Instructions::SetSince(x) => {
                    self.since = Some(x);
                },
                Instructions::SendMessage(room_id, message) => {
                    self.send_message(room_id, message);
                }
            }
        }
        None
    }
    pub fn start(&mut self, password: impl Into<String>, room_ids: Vec<impl Into<String>>) {
        let pass = password.into();
        self.data.auth_token = self.login(pass);
        let mut instructions: Vec<Instructions> = self.generate_instructions(self.sync().unwrap());
        let mut processed_instructions = self.process_instructions(instructions);
        self.starting = false;
        for this_room in room_ids {
            let this_room_string = this_room.into();
            let this_room_id_val: Value = self.get(format!("directory/room/{}", urlencoding::encode(this_room_string.as_str()).to_string().as_str()), None).unwrap().into_json().unwrap();
            let room_id = ruma::RoomId::try_from(this_room_id_val["room_id"].as_str().unwrap()).unwrap();
            if !self.joined_rooms.contains(&room_id) {
                self.join_room_id(room_id);
            }
        }
        while processed_instructions.is_none() && self.ctrlc_handler.should_continue() {
            instructions = self.generate_instructions(self.sync().unwrap());
            processed_instructions = self.process_instructions(instructions);
        }
    }
    fn send_message(&self, room_id: RoomId, message: impl Into<String>) {
        let msg = message.into();
        let txid = Uuid::new_v4().to_simple().encode_lower(&mut Uuid::encode_buffer()).to_string();
        self.put(format!("rooms/{}/send/m.room.message/{}", room_id.clone(), txid).as_str(), json!({"body": msg, "msgtype": "m.text"}), None).unwrap();
    }
    fn generate_instructions(&self, event: EventResponse) -> Vec<Instructions> {
        let mut instructions: Vec<Instructions> = Vec::new();
        instructions.push(Instructions::SetSince(event.next_batch));
        //instructions.append()
        //if let Some(rooms) = event.rooms {
        handle_these_rooms!(self, instructions, RoomTypeData::Joined(event.rooms.join), RoomTypeData::Left(event.rooms.leave), RoomTypeData::Invited(event.rooms.invite));
        instructions
    }
}