connect function

Future<void> connect(
  1. String token,
  2. MethodChannel channel,
  3. Function? onMessage
)

Implementation

@pragma('vm:entry-point')
Future<void> connect(
    String token, MethodChannel channel, Function? onMessage) async {
  if (!connected) {
    await channel.invokeMethod<dynamic>("unlock");
    return;
  }
  if (active) return;
  await addLog(channel, "Connecting");
  active = true;
  try {
    await subs?.cancel();
    webChannel?.sink.close();
    webChannel = WebSocketChannel.connect(
      Uri.parse('wss://sub.pushed.ru/v1/$token'),
    );
    await webChannel?.ready;
    await setNewStatus(channel, ServiceStatus.active);
    subs = webChannel?.stream.listen((event) async {
      await channel.invokeMethod<dynamic>("lock");
      var message = utf8.decode(event);
      await addLog(channel, "MESSAGE: $message");
      if (message != "ONLINE") {
        var payload = json.decode(message);
        var response =
            json.encode(<String, dynamic>{"messageId": payload["messageId"]});
        webChannel?.sink.add(utf8.encode(response));
        try {
          var data = json.decode(payload["data"]);
          payload["data"] = data;
        } catch (_) {}
        Map<String, dynamic> data = {"type": "message", "message": payload};
        var res = await channel.invokeMethod<dynamic>("data", data) ?? false;
        if (!res && onMessage != null) await onMessage(payload);
      }
      await Future.delayed(const Duration(seconds: 5));
      await channel.invokeMethod<dynamic>("unlock");
    }, onDone: () async {
      await channel.invokeMethod<dynamic>("lock");
      await addLog(channel, "Closed");
      active = false;
      await setNewStatus(channel, ServiceStatus.disconnected);
      await Future.delayed(const Duration(seconds: 1));
      connect(token, channel, onMessage);
    });
  } catch (e) {
    await channel.invokeMethod<dynamic>("lock");
    await addLog(channel, "Error: $e");
    await setNewStatus(channel, ServiceStatus.disconnected);
    await subs?.cancel();
    active = false;
    await Future.delayed(const Duration(seconds: 1));
    connect(token, channel, onMessage);
  }
}