- public int handleCommand(final Namespace ns, final Manager m) {
- if (!m.isRegistered()) {
- System.err.println("User is not registered.");
- return 1;
- }
- double timeout = 5;
- if (ns.getDouble("timeout") != null) {
- timeout = ns.getDouble("timeout");
- }
- boolean returnOnTimeout = true;
- if (timeout < 0) {
- returnOnTimeout = false;
- timeout = 3600;
+ public void handleCommand(
+ final Namespace ns,
+ final Manager m,
+ final OutputWriter outputWriter
+ ) throws CommandException {
+ Shutdown.installHandler();
+ final var timeout = ns.getDouble("timeout");
+ final var maxMessagesRaw = ns.getInt("max-messages");
+ final var ignoreAttachments = Boolean.TRUE.equals(ns.getBoolean("ignore-attachments"));
+ final var ignoreStories = Boolean.TRUE.equals(ns.getBoolean("ignore-stories"));
+ final var sendReadReceipts = Boolean.TRUE.equals(ns.getBoolean("send-read-receipts"));
+ m.setReceiveConfig(new ReceiveConfig(ignoreAttachments, ignoreStories, sendReadReceipts));
+ try {
+ final var handler = switch (outputWriter) {
+ case JsonWriter writer -> new JsonReceiveMessageHandler(m, writer);
+ case PlainTextWriter writer -> new ReceiveMessageHandler(m, writer);
+ };
+ final var duration = timeout < 0 ? null : Duration.ofMillis((long) (timeout * 1000));
+ final var maxMessages = maxMessagesRaw < 0 ? null : maxMessagesRaw;
+ Shutdown.registerShutdownListener(m::stopReceiveMessages);
+ m.receiveMessages(Optional.ofNullable(duration), Optional.ofNullable(maxMessages), handler);
+ } catch (IOException e) {
+ throw new IOErrorException("Error while receiving messages: " + e.getMessage(), e);
+ } catch (AlreadyReceivingException e) {
+ throw new UserErrorException("Receive command cannot be used if messages are already being received.", e);