subscribe method

Future<CtrlMessage> subscribe(
  1. GetQuery getParams,
  2. SetParams? setParams
)

Implementation

Future<CtrlMessage> subscribe(
    GetQuery getParams, SetParams? setParams) async {
  // If the topic is already subscribed, return resolved promise
  if (isSubscribed) {
    return Future.error(Exception('topic is already subscribed'));
  }

  // Send subscribe message, handle async response.
  // If topic name is explicitly provided, use it. If no name, then it's a new group topic, use "new".
  var response = await _tinodeService.subscribe(
      name ?? topic_names.TOPIC_NEW, getParams, setParams);
  var ctrl = response is CtrlMessage ? response : null;
  var meta = response is MetaMessage ? response : null;

  if (meta != null) {
    return Future.value(CtrlMessage());
  }

  if (ctrl == null) {
    return Future.value(CtrlMessage());
  }

  if (ctrl.code! >= 300) {
    // Do nothing if the topic is already subscribed to.
    return ctrl;
  }

  _subscribed = true;
  acs = (ctrl.params != null && ctrl.params['acs'] != null)
      ? AccessMode(ctrl.params['acs'])
      : acs;

  // Set topic name for new topics and add it to cache.
  if (_new) {
    _new = false;

    // Name may change new123456 -> grpAbCdEf
    name = ctrl.topic!;
    created = ctrl.ts!;
    updated = ctrl.ts!;
    // Don't assign touched, otherwise topic will be put on top of the list on subscribe.

    if (name != topic_names.TOPIC_ME && name != topic_names.TOPIC_FND) {
      // Add the new topic to the list of contacts maintained by the 'me' topic.
      var me = _tinodeService.getTopic(topic_names.TOPIC_ME) as TopicMe?;
      if (me != null) {
        me.processMetaSub([
          TopicSubscription(
            noForwarding: true,
            topic: name,
            created: ctrl.ts,
            updated: ctrl.ts,
            acs: acs,
          )
        ]);
      }
    }

    if (setParams != null && setParams.desc != null) {
      setParams.desc!.noForwarding = true;
      processMetaDesc(setParams.desc!);
    }
  }
  return ctrl;
}