sendMessage static method

WaitingMessage sendMessage(
  1. PubSub pubSub,
  2. String event,
  3. Map<String, dynamic> payload
)

Implementation

static WaitingMessage sendMessage(PubSub pubSub, String event, Map<String, dynamic> payload) {
  PhoenixChannel? phoenixChannel = channelByTopic[pubSub.getTopic()];
  WaitingMessage waitingMessage = WaitingMessage(event, payload);

  if (phoenixChannel == null) {
    // If the channel doesn't exist yet, enqueue the message to be sent later.
    MessageQueueSupervisor.yield(pubSub.getTopic()).enqueue(waitingMessage);
  } else {
    ChaCha20Key? key = keyByTopic[pubSub.getTopic()];
    if (key != null) {
      // Encrypt the payload if a key is available.
      String uuid = Uuid().v1();
      phoenixChannel.push("broadcast", {
        "event": event,
        "payload": PayloadCipher.encodePayload(payload, nonce: Nonce.fromString(uuid), chaCha20: ChaCha20(key)),
        "timestamp": DateTime.now().millisecondsSinceEpoch,
        "uuid": uuid,
        "channel": pubSub.getTopic()
      }).onReply("ok", (PushResponse pushResponse) {
        waitingMessage.resolve();
      });
    } else {
      // Send the payload as-is if no encryption key is present.
      phoenixChannel.push("broadcast", {
        "event": event,
        "payload": jsonEncode(payload),
        "timestamp": DateTime.now().millisecondsSinceEpoch,
        "uuid": Uuid().v1(),
        "channel": pubSub.getTopic()
      }).onReply("ok", (PushResponse pushResponse) {
        waitingMessage.resolve();
      });
    }
  }

  return waitingMessage;
}