subscribe method

  1. @override
void subscribe([
  1. bool force = false
])
override

Subscribes to the private channel.

Implementation

@override
void subscribe([bool force = false]) async {
  if (!client.connected ||
      (subscribed && !force) ||
      client.socketId == null) {
    return;
  }

  subscribed = false;

  options.log("SUBSCRIBE", name);

  final payload = {
    "channel_name": name,
    "socket_id": client.socketId,
  };

  final response = await http.post(
    Uri.parse(authOptions.endpoint),
    body: payload,
    headers: authOptions.headers,
  );

  options.log(
    "AUTH_RESPONSE",
    name,
    "options: $authOptions\n  payload: $payload\n  response: ${response.body}",
  );

  if (response.statusCode == 200) {
    // try {
    final data = jsonDecode(response.body);

    if (data is! Map) {
      throw Exception(
        "Invalid auth response data [$data], excepted Map got ${data.runtimeType}",
      );
    } else if (!data.containsKey("auth")) {
      throw Exception(
        "Invalid auth response data [$data], auth key is missing",
      );
    }
    authData = AuthData.fromJson(data);
    userId = authData!.channelData?.userId;
    client.sendEvent("pusher:subscribe", {
      "channel": name,
      "auth": authData!.auth,
      "channel_data": authData!.channelData?.toJsonString(),
    });
    // } catch (e) {
    //   handleEvent("pusher:error", e);
    // }
  } else {
    handleEvent(
      "pusher:error",
      "Unable to authenticate channel $name, status code: ${response.statusCode}",
    );
  }
}