src/commands.rs

408 lines · 14402 bytes

  1use std::convert::TryFrom;
  2
  3use matrix_sdk::ruma::OwnedUserId;
  4
  5use modalkit::{
  6    editing::base::OpenTarget,
  7    env::vim::command::{CommandContext, CommandDescription},
  8    input::commands::{CommandError, CommandResult, CommandStep},
  9    input::InputContext,
 10};
 11
 12use crate::base::{
 13    IambAction,
 14    IambId,
 15    MessageAction,
 16    ProgramCommand,
 17    ProgramCommands,
 18    ProgramContext,
 19    RoomAction,
 20    SendAction,
 21    SetRoomField,
 22    VerifyAction,
 23};
 24
 25type ProgContext = CommandContext<ProgramContext>;
 26type ProgResult = CommandResult<ProgramCommand>;
 27
 28fn iamb_invite(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
 29    let args = desc.arg.strings()?;
 30
 31    if args.is_empty() {
 32        return Err(CommandError::InvalidArgument);
 33    }
 34
 35    let ract = match args[0].as_str() {
 36        "accept" => {
 37            if args.len() != 1 {
 38                return Err(CommandError::InvalidArgument);
 39            }
 40
 41            RoomAction::InviteAccept
 42        },
 43        "reject" => {
 44            if args.len() != 1 {
 45                return Err(CommandError::InvalidArgument);
 46            }
 47
 48            RoomAction::InviteReject
 49        },
 50        "send" => {
 51            if args.len() != 2 {
 52                return Err(CommandError::InvalidArgument);
 53            }
 54
 55            if let Ok(user) = OwnedUserId::try_from(args[1].as_str()) {
 56                RoomAction::InviteSend(user)
 57            } else {
 58                let msg = format!("Invalid user identifier: {}", args[1]);
 59                let err = CommandError::Error(msg);
 60
 61                return Err(err);
 62            }
 63        },
 64        _ => {
 65            return Err(CommandError::InvalidArgument);
 66        },
 67    };
 68
 69    let iact = IambAction::from(ract);
 70    let step = CommandStep::Continue(iact.into(), ctx.context.take());
 71
 72    return Ok(step);
 73}
 74
 75fn iamb_verify(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
 76    let mut args = desc.arg.strings()?;
 77
 78    match args.len() {
 79        0 => {
 80            let open = ctx.switch(OpenTarget::Application(IambId::VerifyList));
 81            let step = CommandStep::Continue(open, ctx.context.take());
 82
 83            return Ok(step);
 84        },
 85        1 => {
 86            return Result::Err(CommandError::InvalidArgument);
 87        },
 88        2 => {
 89            let act = match args[0].as_str() {
 90                "accept" => VerifyAction::Accept,
 91                "cancel" => VerifyAction::Cancel,
 92                "confirm" => VerifyAction::Confirm,
 93                "mismatch" => VerifyAction::Mismatch,
 94                "request" => {
 95                    let iact = IambAction::VerifyRequest(args.remove(1));
 96                    let step = CommandStep::Continue(iact.into(), ctx.context.take());
 97
 98                    return Ok(step);
 99                },
100                _ => return Result::Err(CommandError::InvalidArgument),
101            };
102
103            let vact = IambAction::Verify(act, args.remove(1));
104            let step = CommandStep::Continue(vact.into(), ctx.context.take());
105
106            return Ok(step);
107        },
108        _ => {
109            return Result::Err(CommandError::InvalidArgument);
110        },
111    }
112}
113
114fn iamb_dms(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
115    if !desc.arg.text.is_empty() {
116        return Result::Err(CommandError::InvalidArgument);
117    }
118
119    let open = ctx.switch(OpenTarget::Application(IambId::DirectList));
120    let step = CommandStep::Continue(open, ctx.context.take());
121
122    return Ok(step);
123}
124
125fn iamb_members(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
126    if !desc.arg.text.is_empty() {
127        return Result::Err(CommandError::InvalidArgument);
128    }
129
130    let open = IambAction::Room(RoomAction::Members(ctx.clone().into()));
131    let step = CommandStep::Continue(open.into(), ctx.context.take());
132
133    return Ok(step);
134}
135
136fn iamb_rooms(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
137    if !desc.arg.text.is_empty() {
138        return Result::Err(CommandError::InvalidArgument);
139    }
140
141    let open = ctx.switch(OpenTarget::Application(IambId::RoomList));
142    let step = CommandStep::Continue(open, ctx.context.take());
143
144    return Ok(step);
145}
146
147fn iamb_spaces(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
148    if !desc.arg.text.is_empty() {
149        return Result::Err(CommandError::InvalidArgument);
150    }
151
152    let open = ctx.switch(OpenTarget::Application(IambId::SpaceList));
153    let step = CommandStep::Continue(open, ctx.context.take());
154
155    return Ok(step);
156}
157
158fn iamb_welcome(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
159    if !desc.arg.text.is_empty() {
160        return Result::Err(CommandError::InvalidArgument);
161    }
162
163    let open = ctx.switch(OpenTarget::Application(IambId::Welcome));
164    let step = CommandStep::Continue(open, ctx.context.take());
165
166    return Ok(step);
167}
168
169fn iamb_join(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
170    let mut args = desc.arg.filenames()?;
171
172    if args.len() != 1 {
173        return Result::Err(CommandError::InvalidArgument);
174    }
175
176    let open = ctx.switch(args.remove(0));
177    let step = CommandStep::Continue(open, ctx.context.take());
178
179    return Ok(step);
180}
181
182fn iamb_set(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
183    let mut args = desc.arg.strings()?;
184
185    if args.len() != 2 {
186        return Result::Err(CommandError::InvalidArgument);
187    }
188
189    let field = args.remove(0);
190    let value = args.remove(0);
191
192    let act: IambAction = match field.as_str() {
193        "room.name" => RoomAction::Set(SetRoomField::Name(value)).into(),
194        "room.topic" => RoomAction::Set(SetRoomField::Topic(value)).into(),
195        _ => {
196            return Result::Err(CommandError::InvalidArgument);
197        },
198    };
199
200    let step = CommandStep::Continue(act.into(), ctx.context.take());
201
202    return Ok(step);
203}
204
205fn iamb_upload(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
206    let mut args = desc.arg.strings()?;
207
208    if args.len() != 1 {
209        return Result::Err(CommandError::InvalidArgument);
210    }
211
212    let sact = SendAction::Upload(args.remove(0));
213    let iact = IambAction::from(sact);
214    let step = CommandStep::Continue(iact.into(), ctx.context.take());
215
216    return Ok(step);
217}
218
219fn iamb_download(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
220    let mut args = desc.arg.strings()?;
221
222    if args.len() > 1 {
223        return Result::Err(CommandError::InvalidArgument);
224    }
225
226    let mact = MessageAction::Download(args.pop(), desc.bang);
227    let iact = IambAction::from(mact);
228    let step = CommandStep::Continue(iact.into(), ctx.context.take());
229
230    return Ok(step);
231}
232
233fn add_iamb_commands(cmds: &mut ProgramCommands) {
234    cmds.add_command(ProgramCommand { names: vec!["dms".into()], f: iamb_dms });
235    cmds.add_command(ProgramCommand { names: vec!["download".into()], f: iamb_download });
236    cmds.add_command(ProgramCommand { names: vec!["invite".into()], f: iamb_invite });
237    cmds.add_command(ProgramCommand { names: vec!["join".into()], f: iamb_join });
238    cmds.add_command(ProgramCommand { names: vec!["members".into()], f: iamb_members });
239    cmds.add_command(ProgramCommand { names: vec!["rooms".into()], f: iamb_rooms });
240    cmds.add_command(ProgramCommand { names: vec!["set".into()], f: iamb_set });
241    cmds.add_command(ProgramCommand { names: vec!["spaces".into()], f: iamb_spaces });
242    cmds.add_command(ProgramCommand { names: vec!["upload".into()], f: iamb_upload });
243    cmds.add_command(ProgramCommand { names: vec!["verify".into()], f: iamb_verify });
244    cmds.add_command(ProgramCommand { names: vec!["welcome".into()], f: iamb_welcome });
245}
246
247pub fn setup_commands() -> ProgramCommands {
248    let mut cmds = ProgramCommands::default();
249
250    add_iamb_commands(&mut cmds);
251
252    return cmds;
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use matrix_sdk::ruma::user_id;
259    use modalkit::editing::action::WindowAction;
260
261    #[test]
262    fn test_cmd_verify() {
263        let mut cmds = setup_commands();
264        let ctx = ProgramContext::default();
265
266        let res = cmds.input_cmd(":verify", ctx.clone()).unwrap();
267        let act = WindowAction::Switch(OpenTarget::Application(IambId::VerifyList));
268        assert_eq!(res, vec![(act.into(), ctx.clone())]);
269
270        let res = cmds.input_cmd(":verify request @user1:example.com", ctx.clone()).unwrap();
271        let act = IambAction::VerifyRequest("@user1:example.com".into());
272        assert_eq!(res, vec![(act.into(), ctx.clone())]);
273
274        let res = cmds
275            .input_cmd(":verify accept @user1:example.com/FOOBAR", ctx.clone())
276            .unwrap();
277        let act = IambAction::Verify(VerifyAction::Accept, "@user1:example.com/FOOBAR".into());
278        assert_eq!(res, vec![(act.into(), ctx.clone())]);
279
280        let res = cmds
281            .input_cmd(":verify mismatch @user2:example.com/QUUXBAZ", ctx.clone())
282            .unwrap();
283        let act = IambAction::Verify(VerifyAction::Mismatch, "@user2:example.com/QUUXBAZ".into());
284        assert_eq!(res, vec![(act.into(), ctx.clone())]);
285
286        let res = cmds
287            .input_cmd(":verify cancel @user3:example.com/MYDEVICE", ctx.clone())
288            .unwrap();
289        let act = IambAction::Verify(VerifyAction::Cancel, "@user3:example.com/MYDEVICE".into());
290        assert_eq!(res, vec![(act.into(), ctx.clone())]);
291
292        let res = cmds
293            .input_cmd(":verify confirm @user4:example.com/GOODDEV", ctx.clone())
294            .unwrap();
295        let act = IambAction::Verify(VerifyAction::Confirm, "@user4:example.com/GOODDEV".into());
296        assert_eq!(res, vec![(act.into(), ctx.clone())]);
297
298        let res = cmds.input_cmd(":verify confirm", ctx.clone());
299        assert_eq!(res, Err(CommandError::InvalidArgument));
300
301        let res = cmds.input_cmd(":verify cancel @user4:example.com MYDEVICE", ctx.clone());
302        assert_eq!(res, Err(CommandError::InvalidArgument));
303
304        let res = cmds.input_cmd(":verify mismatch a b c d e f", ctx.clone());
305        assert_eq!(res, Err(CommandError::InvalidArgument));
306    }
307
308    #[test]
309    fn test_cmd_join() {
310        let mut cmds = setup_commands();
311        let ctx = ProgramContext::default();
312
313        let res = cmds.input_cmd("join #foobar:example.com", ctx.clone()).unwrap();
314        let act = WindowAction::Switch(OpenTarget::Name("#foobar:example.com".into()));
315        assert_eq!(res, vec![(act.into(), ctx.clone())]);
316
317        let res = cmds.input_cmd("join #", ctx.clone()).unwrap();
318        let act = WindowAction::Switch(OpenTarget::Alternate);
319        assert_eq!(res, vec![(act.into(), ctx.clone())]);
320
321        let res = cmds.input_cmd("join", ctx.clone());
322        assert_eq!(res, Err(CommandError::InvalidArgument));
323
324        let res = cmds.input_cmd("join foo bar", ctx.clone());
325        assert_eq!(res, Err(CommandError::InvalidArgument));
326    }
327
328    #[test]
329    fn test_cmd_set() {
330        let mut cmds = setup_commands();
331        let ctx = ProgramContext::default();
332
333        let res = cmds
334            .input_cmd("set room.topic \"Lots of fun discussion!\"", ctx.clone())
335            .unwrap();
336        let act = IambAction::Room(SetRoomField::Topic("Lots of fun discussion!".into()).into());
337        assert_eq!(res, vec![(act.into(), ctx.clone())]);
338
339        let res = cmds
340            .input_cmd("set room.topic The\\ Discussion\\ Room", ctx.clone())
341            .unwrap();
342        let act = IambAction::Room(SetRoomField::Topic("The Discussion Room".into()).into());
343        assert_eq!(res, vec![(act.into(), ctx.clone())]);
344
345        let res = cmds.input_cmd("set room.topic Development", ctx.clone()).unwrap();
346        let act = IambAction::Room(SetRoomField::Topic("Development".into()).into());
347        assert_eq!(res, vec![(act.into(), ctx.clone())]);
348
349        let res = cmds.input_cmd("set room.name Development", ctx.clone()).unwrap();
350        let act = IambAction::Room(SetRoomField::Name("Development".into()).into());
351        assert_eq!(res, vec![(act.into(), ctx.clone())]);
352
353        let res = cmds
354            .input_cmd("set room.name \"Application Development\"", ctx.clone())
355            .unwrap();
356        let act = IambAction::Room(SetRoomField::Name("Application Development".into()).into());
357        assert_eq!(res, vec![(act.into(), ctx.clone())]);
358
359        let res = cmds.input_cmd("set", ctx.clone());
360        assert_eq!(res, Err(CommandError::InvalidArgument));
361
362        let res = cmds.input_cmd("set room.name", ctx.clone());
363        assert_eq!(res, Err(CommandError::InvalidArgument));
364
365        let res = cmds.input_cmd("set room.topic", ctx.clone());
366        assert_eq!(res, Err(CommandError::InvalidArgument));
367
368        let res = cmds.input_cmd("set room.topic A B C", ctx.clone());
369        assert_eq!(res, Err(CommandError::InvalidArgument));
370    }
371
372    #[test]
373    fn test_cmd_invite() {
374        let mut cmds = setup_commands();
375        let ctx = ProgramContext::default();
376
377        let res = cmds.input_cmd("invite accept", ctx.clone()).unwrap();
378        let act = IambAction::Room(RoomAction::InviteAccept);
379        assert_eq!(res, vec![(act.into(), ctx.clone())]);
380
381        let res = cmds.input_cmd("invite reject", ctx.clone()).unwrap();
382        let act = IambAction::Room(RoomAction::InviteReject);
383        assert_eq!(res, vec![(act.into(), ctx.clone())]);
384
385        let res = cmds.input_cmd("invite send @user:example.com", ctx.clone()).unwrap();
386        let act =
387            IambAction::Room(RoomAction::InviteSend(user_id!("@user:example.com").to_owned()));
388        assert_eq!(res, vec![(act.into(), ctx.clone())]);
389
390        let res = cmds.input_cmd("invite", ctx.clone());
391        assert_eq!(res, Err(CommandError::InvalidArgument));
392
393        let res = cmds.input_cmd("invite foo", ctx.clone());
394        assert_eq!(res, Err(CommandError::InvalidArgument));
395
396        let res = cmds.input_cmd("invite accept @user:example.com", ctx.clone());
397        assert_eq!(res, Err(CommandError::InvalidArgument));
398
399        let res = cmds.input_cmd("invite reject @user:example.com", ctx.clone());
400        assert_eq!(res, Err(CommandError::InvalidArgument));
401
402        let res = cmds.input_cmd("invite send", ctx.clone());
403        assert_eq!(res, Err(CommandError::InvalidArgument));
404
405        let res = cmds.input_cmd("invite @user:example.com", ctx.clone());
406        assert_eq!(res, Err(CommandError::InvalidArgument));
407    }
408}