src/commands.rs

432 lines · 15238 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_cancel(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
137    if !desc.arg.text.is_empty() {
138        return Result::Err(CommandError::InvalidArgument);
139    }
140
141    let ract = IambAction::from(MessageAction::Cancel);
142    let step = CommandStep::Continue(ract.into(), ctx.context.take());
143
144    return Ok(step);
145}
146
147fn iamb_reply(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
148    if !desc.arg.text.is_empty() {
149        return Result::Err(CommandError::InvalidArgument);
150    }
151
152    let ract = IambAction::from(MessageAction::Reply);
153    let step = CommandStep::Continue(ract.into(), ctx.context.take());
154
155    return Ok(step);
156}
157
158fn iamb_rooms(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::RoomList));
164    let step = CommandStep::Continue(open, ctx.context.take());
165
166    return Ok(step);
167}
168
169fn iamb_spaces(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
170    if !desc.arg.text.is_empty() {
171        return Result::Err(CommandError::InvalidArgument);
172    }
173
174    let open = ctx.switch(OpenTarget::Application(IambId::SpaceList));
175    let step = CommandStep::Continue(open, ctx.context.take());
176
177    return Ok(step);
178}
179
180fn iamb_welcome(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
181    if !desc.arg.text.is_empty() {
182        return Result::Err(CommandError::InvalidArgument);
183    }
184
185    let open = ctx.switch(OpenTarget::Application(IambId::Welcome));
186    let step = CommandStep::Continue(open, ctx.context.take());
187
188    return Ok(step);
189}
190
191fn iamb_join(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
192    let mut args = desc.arg.filenames()?;
193
194    if args.len() != 1 {
195        return Result::Err(CommandError::InvalidArgument);
196    }
197
198    let open = ctx.switch(args.remove(0));
199    let step = CommandStep::Continue(open, ctx.context.take());
200
201    return Ok(step);
202}
203
204fn iamb_set(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
205    let mut args = desc.arg.strings()?;
206
207    if args.len() != 2 {
208        return Result::Err(CommandError::InvalidArgument);
209    }
210
211    let field = args.remove(0);
212    let value = args.remove(0);
213
214    let act: IambAction = match field.as_str() {
215        "room.name" => RoomAction::Set(SetRoomField::Name(value)).into(),
216        "room.topic" => RoomAction::Set(SetRoomField::Topic(value)).into(),
217        _ => {
218            return Result::Err(CommandError::InvalidArgument);
219        },
220    };
221
222    let step = CommandStep::Continue(act.into(), ctx.context.take());
223
224    return Ok(step);
225}
226
227fn iamb_upload(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
228    let mut args = desc.arg.strings()?;
229
230    if args.len() != 1 {
231        return Result::Err(CommandError::InvalidArgument);
232    }
233
234    let sact = SendAction::Upload(args.remove(0));
235    let iact = IambAction::from(sact);
236    let step = CommandStep::Continue(iact.into(), ctx.context.take());
237
238    return Ok(step);
239}
240
241fn iamb_download(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
242    let mut args = desc.arg.strings()?;
243
244    if args.len() > 1 {
245        return Result::Err(CommandError::InvalidArgument);
246    }
247
248    let mact = MessageAction::Download(args.pop(), desc.bang);
249    let iact = IambAction::from(mact);
250    let step = CommandStep::Continue(iact.into(), ctx.context.take());
251
252    return Ok(step);
253}
254
255fn add_iamb_commands(cmds: &mut ProgramCommands) {
256    cmds.add_command(ProgramCommand { names: vec!["cancel".into()], f: iamb_cancel });
257    cmds.add_command(ProgramCommand { names: vec!["dms".into()], f: iamb_dms });
258    cmds.add_command(ProgramCommand { names: vec!["download".into()], f: iamb_download });
259    cmds.add_command(ProgramCommand { names: vec!["invite".into()], f: iamb_invite });
260    cmds.add_command(ProgramCommand { names: vec!["join".into()], f: iamb_join });
261    cmds.add_command(ProgramCommand { names: vec!["members".into()], f: iamb_members });
262    cmds.add_command(ProgramCommand { names: vec!["reply".into()], f: iamb_reply });
263    cmds.add_command(ProgramCommand { names: vec!["rooms".into()], f: iamb_rooms });
264    cmds.add_command(ProgramCommand { names: vec!["set".into()], f: iamb_set });
265    cmds.add_command(ProgramCommand { names: vec!["spaces".into()], f: iamb_spaces });
266    cmds.add_command(ProgramCommand { names: vec!["upload".into()], f: iamb_upload });
267    cmds.add_command(ProgramCommand { names: vec!["verify".into()], f: iamb_verify });
268    cmds.add_command(ProgramCommand { names: vec!["welcome".into()], f: iamb_welcome });
269}
270
271pub fn setup_commands() -> ProgramCommands {
272    let mut cmds = ProgramCommands::default();
273
274    add_iamb_commands(&mut cmds);
275
276    return cmds;
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282    use matrix_sdk::ruma::user_id;
283    use modalkit::editing::action::WindowAction;
284
285    #[test]
286    fn test_cmd_verify() {
287        let mut cmds = setup_commands();
288        let ctx = ProgramContext::default();
289
290        let res = cmds.input_cmd(":verify", ctx.clone()).unwrap();
291        let act = WindowAction::Switch(OpenTarget::Application(IambId::VerifyList));
292        assert_eq!(res, vec![(act.into(), ctx.clone())]);
293
294        let res = cmds.input_cmd(":verify request @user1:example.com", ctx.clone()).unwrap();
295        let act = IambAction::VerifyRequest("@user1:example.com".into());
296        assert_eq!(res, vec![(act.into(), ctx.clone())]);
297
298        let res = cmds
299            .input_cmd(":verify accept @user1:example.com/FOOBAR", ctx.clone())
300            .unwrap();
301        let act = IambAction::Verify(VerifyAction::Accept, "@user1:example.com/FOOBAR".into());
302        assert_eq!(res, vec![(act.into(), ctx.clone())]);
303
304        let res = cmds
305            .input_cmd(":verify mismatch @user2:example.com/QUUXBAZ", ctx.clone())
306            .unwrap();
307        let act = IambAction::Verify(VerifyAction::Mismatch, "@user2:example.com/QUUXBAZ".into());
308        assert_eq!(res, vec![(act.into(), ctx.clone())]);
309
310        let res = cmds
311            .input_cmd(":verify cancel @user3:example.com/MYDEVICE", ctx.clone())
312            .unwrap();
313        let act = IambAction::Verify(VerifyAction::Cancel, "@user3:example.com/MYDEVICE".into());
314        assert_eq!(res, vec![(act.into(), ctx.clone())]);
315
316        let res = cmds
317            .input_cmd(":verify confirm @user4:example.com/GOODDEV", ctx.clone())
318            .unwrap();
319        let act = IambAction::Verify(VerifyAction::Confirm, "@user4:example.com/GOODDEV".into());
320        assert_eq!(res, vec![(act.into(), ctx.clone())]);
321
322        let res = cmds.input_cmd(":verify confirm", ctx.clone());
323        assert_eq!(res, Err(CommandError::InvalidArgument));
324
325        let res = cmds.input_cmd(":verify cancel @user4:example.com MYDEVICE", ctx.clone());
326        assert_eq!(res, Err(CommandError::InvalidArgument));
327
328        let res = cmds.input_cmd(":verify mismatch a b c d e f", ctx.clone());
329        assert_eq!(res, Err(CommandError::InvalidArgument));
330    }
331
332    #[test]
333    fn test_cmd_join() {
334        let mut cmds = setup_commands();
335        let ctx = ProgramContext::default();
336
337        let res = cmds.input_cmd("join #foobar:example.com", ctx.clone()).unwrap();
338        let act = WindowAction::Switch(OpenTarget::Name("#foobar:example.com".into()));
339        assert_eq!(res, vec![(act.into(), ctx.clone())]);
340
341        let res = cmds.input_cmd("join #", ctx.clone()).unwrap();
342        let act = WindowAction::Switch(OpenTarget::Alternate);
343        assert_eq!(res, vec![(act.into(), ctx.clone())]);
344
345        let res = cmds.input_cmd("join", ctx.clone());
346        assert_eq!(res, Err(CommandError::InvalidArgument));
347
348        let res = cmds.input_cmd("join foo bar", ctx.clone());
349        assert_eq!(res, Err(CommandError::InvalidArgument));
350    }
351
352    #[test]
353    fn test_cmd_set() {
354        let mut cmds = setup_commands();
355        let ctx = ProgramContext::default();
356
357        let res = cmds
358            .input_cmd("set room.topic \"Lots of fun discussion!\"", ctx.clone())
359            .unwrap();
360        let act = IambAction::Room(SetRoomField::Topic("Lots of fun discussion!".into()).into());
361        assert_eq!(res, vec![(act.into(), ctx.clone())]);
362
363        let res = cmds
364            .input_cmd("set room.topic The\\ Discussion\\ Room", ctx.clone())
365            .unwrap();
366        let act = IambAction::Room(SetRoomField::Topic("The Discussion Room".into()).into());
367        assert_eq!(res, vec![(act.into(), ctx.clone())]);
368
369        let res = cmds.input_cmd("set room.topic Development", ctx.clone()).unwrap();
370        let act = IambAction::Room(SetRoomField::Topic("Development".into()).into());
371        assert_eq!(res, vec![(act.into(), ctx.clone())]);
372
373        let res = cmds.input_cmd("set room.name Development", ctx.clone()).unwrap();
374        let act = IambAction::Room(SetRoomField::Name("Development".into()).into());
375        assert_eq!(res, vec![(act.into(), ctx.clone())]);
376
377        let res = cmds
378            .input_cmd("set room.name \"Application Development\"", ctx.clone())
379            .unwrap();
380        let act = IambAction::Room(SetRoomField::Name("Application Development".into()).into());
381        assert_eq!(res, vec![(act.into(), ctx.clone())]);
382
383        let res = cmds.input_cmd("set", ctx.clone());
384        assert_eq!(res, Err(CommandError::InvalidArgument));
385
386        let res = cmds.input_cmd("set room.name", ctx.clone());
387        assert_eq!(res, Err(CommandError::InvalidArgument));
388
389        let res = cmds.input_cmd("set room.topic", ctx.clone());
390        assert_eq!(res, Err(CommandError::InvalidArgument));
391
392        let res = cmds.input_cmd("set room.topic A B C", ctx.clone());
393        assert_eq!(res, Err(CommandError::InvalidArgument));
394    }
395
396    #[test]
397    fn test_cmd_invite() {
398        let mut cmds = setup_commands();
399        let ctx = ProgramContext::default();
400
401        let res = cmds.input_cmd("invite accept", ctx.clone()).unwrap();
402        let act = IambAction::Room(RoomAction::InviteAccept);
403        assert_eq!(res, vec![(act.into(), ctx.clone())]);
404
405        let res = cmds.input_cmd("invite reject", ctx.clone()).unwrap();
406        let act = IambAction::Room(RoomAction::InviteReject);
407        assert_eq!(res, vec![(act.into(), ctx.clone())]);
408
409        let res = cmds.input_cmd("invite send @user:example.com", ctx.clone()).unwrap();
410        let act =
411            IambAction::Room(RoomAction::InviteSend(user_id!("@user:example.com").to_owned()));
412        assert_eq!(res, vec![(act.into(), ctx.clone())]);
413
414        let res = cmds.input_cmd("invite", ctx.clone());
415        assert_eq!(res, Err(CommandError::InvalidArgument));
416
417        let res = cmds.input_cmd("invite foo", ctx.clone());
418        assert_eq!(res, Err(CommandError::InvalidArgument));
419
420        let res = cmds.input_cmd("invite accept @user:example.com", ctx.clone());
421        assert_eq!(res, Err(CommandError::InvalidArgument));
422
423        let res = cmds.input_cmd("invite reject @user:example.com", ctx.clone());
424        assert_eq!(res, Err(CommandError::InvalidArgument));
425
426        let res = cmds.input_cmd("invite send", ctx.clone());
427        assert_eq!(res, Err(CommandError::InvalidArgument));
428
429        let res = cmds.input_cmd("invite @user:example.com", ctx.clone());
430        assert_eq!(res, Err(CommandError::InvalidArgument));
431    }
432}