requestInvoke method

Future<Map> requestInvoke(
  1. String method, {
  2. Map? parameters,
  3. required int clientId,
  4. bool isVoid = false,
  5. Duration? delayDuration,
  6. Duration? invokeTimeOut,
  7. String? extra,
  8. bool? isAutoGetChat,
  9. FutureOr<String> onGenerateExtraInvoke(
    1. int client_id,
    2. TdlibBase libTdJson
    )?,
  10. FutureOr<Map> onGetInvokeData(
    1. String extra,
    2. int client_id,
    3. TdlibBase libTdJson
    )?,
  11. bool? isInvokeThrowOnError,
  12. bool isAutoExtendMessage = false,
  13. bool? isUseCache,
  14. Duration? durationCacheExpire,
})

Implementation

Future<Map> requestInvoke(
  String method, {
  Map? parameters,
  required int clientId,
  bool isVoid = false,
  Duration? delayDuration,
  Duration? invokeTimeOut,
  String? extra,
  bool? isAutoGetChat,
  FutureOr<String> Function(int client_id, TdlibBase libTdJson)?
      onGenerateExtraInvoke,
  FutureOr<Map> Function(String extra, int client_id, TdlibBase libTdJson)?
      onGetInvokeData,
  bool? isInvokeThrowOnError,
  bool isAutoExtendMessage = false,
  bool? isUseCache,
  Duration? durationCacheExpire,
}) async {
  //
  parameters ??= {};

  isAutoGetChat ??= false;
  if (parameters["chat_id"] is String &&
      RegExp(r"^(@)?[a-z0-9_]+", caseSensitive: false)
          .hashData(parameters["chat_id"])) {
    isAutoGetChat = false;
    var search_public_chat = await invoke(
      "searchPublicChat",
      parameters: {
        "username": parameters["chat_id"],
      },
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
      clientId: clientId,
      extra: extra,
      delayDuration: delayDuration,
      invokeTimeOut: invokeTimeOut,
      isInvokeThrowOnError: isInvokeThrowOnError ?? false,
      onGenerateExtraInvoke: onGenerateExtraInvoke,
      onGetInvokeData: onGetInvokeData,
    );
    if (search_public_chat["@type"] == "chat") {
      parameters["chat_id"] = search_public_chat["id"];
    }
  }
  if (parameters["user_id"] is String &&
      RegExp(r"^(@)?[a-z0-9_]+", caseSensitive: false)
          .hashData(parameters["user_id"])) {
    isAutoGetChat = false;
    var search_public_chat = await invoke(
      "searchPublicChat",
      parameters: {
        "username": parameters["user_id"],
      },
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
      clientId: clientId,
      extra: extra,
      delayDuration: delayDuration,
      invokeTimeOut: invokeTimeOut,
      isInvokeThrowOnError: isInvokeThrowOnError ?? false,
      onGenerateExtraInvoke: onGenerateExtraInvoke,
      onGetInvokeData: onGetInvokeData,
    );
    if (search_public_chat["@type"] == "chat") {
      parameters["user_id"] = search_public_chat["id"];
    }
  }
  String regexMethodSend =
      r"^(sendMessage|sendPhoto|sendVideo|sendAudio|sendVoice|sendDocument|sendSticker|sendAnimation)$";
  if (RegExp(regexMethodSend, caseSensitive: false).hashData(method)) {
    Map result_request = {
      "ok": false,
    };
    result_request = await invoke(
      (RegExp("editMessageText", caseSensitive: false).hashData(method))
          ? method
          : "sendMessage",
      parameters: makeParametersApi(
        {
          "@type": method,
          ...parameters,
        },
      ),
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
      clientId: clientId,
      isVoid: isVoid,
      extra: extra,
      isAutoGetChat: isAutoGetChat,
      delayDuration: delayDuration,
      invokeTimeOut: invokeTimeOut,
      isInvokeThrowOnError: isInvokeThrowOnError ?? false,
      onGenerateExtraInvoke: onGenerateExtraInvoke,
      onGetInvokeData: onGetInvokeData,
    );
    if (isVoid) {
      return {
        "@type": "ok",
      };
    }
    if (result_request["ok"] == false) {
      throw result_request;
    }
    result_request.remove("ok");
    if (!parameters.containsKey("as_api")) {
      return result_request;
    }

    Completer<Map> completer = Completer<Map>();

    var listen = on(event_update, (UpdateTd update) async {
      if (update.client_id != clientId) {
        return;
      }
      Map updateOrigin = update.raw;
      if (!["updateMessageSendSucceeded", "updateMessageSendFailed"]
          .contains(updateOrigin["@type"])) {
        return;
      }

      if (updateOrigin["message"] is Map &&
          updateOrigin["message"]["chat_id"] == result_request["chat_id"] &&
          updateOrigin["old_message_id"] == result_request["id"]) {
        // updateOrigin.printPretty(2);
        //
        completer.complete(updateOrigin);
        // result = updateOrigin;
      }

      // if (updateOrigin["old_message_id"] == result_request["id"]) {
      //   updateOrigin.printPretty(2);
      //   Map json_message = await jsonMessage(
      //     updateOrigin["message"],
      //     clientId: clientId,
      //     is_detail: true,
      //     is_skip_reply_message: true,
      //   );
      //   if (json_message["ok"] == true) {
      //     json_message["result"]["@type"] = "updateNewMessage";
      //     result = json_message["result"];
      //   } else {
      //     json_message["result"]["@type"] = "error";
      //     result = json_message["result"];
      //   }
      // } else if (updateOrigin["message_ids"] is List && (updateOrigin["message_ids"] as List).contains(result_request["id"])) {
      //   result["@type"] = "error";
      // }
    });

    Map result = await completer.future.timeout(
      Duration(minutes: 1),
      onTimeout: () {
        return {
          "@type": "error",
        };
      },
    );

    event_emitter.off(listener: listen);
    if (result["@type"] is String) {
      // task_decrease();
      if (result["@type"] == "error") {
        throw result;
      }
      result.remove("@type");
      if (result["message"] is Map) {
        Map json_message = await jsonMessage(
          result["message"],
          clientId: clientId,
          is_detail: false,
          is_skip_reply_message: true,
          is_from_send_message: true,
          is_super_detail: true,
          isUseCache: isUseCache,
          durationCacheExpire: durationCacheExpire,
        );
        if (json_message["result"] is Map) {
          if (json_message["ok"] == true) {
            json_message["result"]["@type"] = "message";
            result = json_message["result"];
          } else {
            json_message["result"]["@type"] = "error";
            result = json_message["result"];
          }
        }
      }

      return {
        "ok": true,
        "result": result,
      };
    }
    throw result;
  }
  if (RegExp(r"^addChatMember$", caseSensitive: false).hashData(method)) {
    return await invoke(
      "addChatMember",
      parameters: {
        "chat_id": parameters["chat_id"],
        "user_id": parameters["user_id"],
      },
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
      clientId: clientId,
      isVoid: isVoid,
      extra: extra,
      isAutoGetChat: isAutoGetChat,
      delayDuration: delayDuration,
      invokeTimeOut: invokeTimeOut,
      isInvokeThrowOnError: isInvokeThrowOnError ?? false,
      onGenerateExtraInvoke: onGenerateExtraInvoke,
      onGetInvokeData: onGetInvokeData,
    );
  }
  if (RegExp(r"^editMessageText$", caseSensitive: false).hashData(method)) {
    return await editMessageText(
      chat_id: parameters["chat_id"],
      message_id: parameters["message_id"],
      text: parameters["text"],
      inline_message_id: parameters["inline_message_id"],
      parse_mode: (parameters["parse_mode"] is String)
          ? parameters["parse_mode"]
          : "html",
      entities:
          (parameters["entities"] is List) ? parameters["entities"] : [],
      disable_web_page_preview:
          (parameters["disable_web_page_preview"] is bool)
              ? parameters["disable_web_page_preview"]
              : false,
      reply_markup: parameters["reply_markup"],
      clientId: clientId,
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
    );
  }
  if (RegExp(r"^editMessageCaption$", caseSensitive: false)
      .hashData(method)) {
    return await editMessageCaption(
      chat_id: parameters["chat_id"],
      message_id: parameters["message_id"],
      caption: parameters["caption"],
      inline_message_id: parameters["inline_message_id"],
      parse_mode: (parameters["parse_mode"] is String)
          ? parameters["parse_mode"]
          : "html",
      entities:
          (parameters["entities"] is List) ? parameters["entities"] : [],
      disable_web_page_preview:
          (parameters["disable_web_page_preview"] is bool)
              ? parameters["disable_web_page_preview"]
              : false,
      reply_markup: parameters["reply_markup"],
      clientId: clientId,
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
    );
  }
  if (RegExp(r"^joinChat$", caseSensitive: false).hashData(method)) {
    return await invoke(
      "joinChat",
      parameters: {
        "chat_id": parameters["chat_id"],
      },
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
      clientId: clientId,
      isVoid: isVoid,
      extra: extra,
      isAutoGetChat: isAutoGetChat,
      delayDuration: delayDuration,
      invokeTimeOut: invokeTimeOut,
      isInvokeThrowOnError: isInvokeThrowOnError ?? false,
      onGenerateExtraInvoke: onGenerateExtraInvoke,
      onGetInvokeData: onGetInvokeData,
    );
  }
  if (RegExp(r"^joinChatByInviteLink$", caseSensitive: false)
      .hashData(method)) {
    return await invoke(
      "joinChatByInviteLink",
      parameters: {
        "invite_link": parameters["invite_link"],
      },
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
      clientId: clientId,
      isVoid: isVoid,
      extra: extra,
      delayDuration: delayDuration,
      invokeTimeOut: invokeTimeOut,
      isInvokeThrowOnError: isInvokeThrowOnError ?? false,
      onGenerateExtraInvoke: onGenerateExtraInvoke,
      onGetInvokeData: onGetInvokeData,
    );
  }

  if (RegExp(r"^getChatMember$", caseSensitive: false).hashData(method)) {
    return await getChatMember(
      parameters["chat_id"],
      parameters["user_id"],
      clientId: clientId,
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
    );
  }
  if (RegExp(r"^getMe$", caseSensitive: false).hashData(method)) {
    return await getMe(
      clientId: clientId,
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
    );
  }
  if (RegExp(r"^getChat$", caseSensitive: false).hashData(method)) {
    return await getChat(
      parameters["chat_id"],
      is_detail: true,
      clientId: clientId,
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
      is_super_detail: (parameters["is_super_detail"] == true),
      is_more_detail: (parameters["is_more_detail"] == true),
      is_skip_reply_message: true,
    );
  }
  if (RegExp(r"^getChats$", caseSensitive: false).hashData(method)) {
    var getChats = await invoke(
      "getChats",
      parameters: {
        "limit": (parameters["limit"] is int) ? parameters["limit"] : 10,
      },
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
      clientId: clientId,
      extra: extra,
      delayDuration: delayDuration,
      invokeTimeOut: invokeTimeOut,
      isInvokeThrowOnError: isInvokeThrowOnError ?? false,
      onGenerateExtraInvoke: onGenerateExtraInvoke,
      onGetInvokeData: onGetInvokeData,
    );
    if (getChats["@type"] == "chats") {
      List chat_ids = getChats["chat_ids"];
      List array_chat = [];
      for (var i = 0; i < chat_ids.length; i++) {
        await Future.delayed(Duration(milliseconds: 1));
        try {
          var get_chat = await getChat(
            chat_ids[i],
            is_detail: true,
            is_super_detail: true,
            clientId: clientId,
            isUseCache: isUseCache,
            durationCacheExpire: durationCacheExpire,
            is_skip_reply_message: true,
          );
          if (get_chat["ok"] == true) {
            array_chat.add(get_chat["result"]);
          }
        } catch (e) {}
      }
      return {"ok": true, "result": array_chat};
    }
  }

  if (RegExp(r"^getUser$", caseSensitive: false).hashData(method)) {
    return await getUser(
      parameters["chat_id"],
      clientId: clientId,
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
    );
  }
  if (RegExp(r"^answerCallbackQuery$", caseSensitive: false)
      .hashData(method)) {
    return await answerCallbackQuery(
      parameters["callback_query_id"],
      text: parameters["text"],
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
      show_alert: parameters["show_alert"] ?? false,
      url: parameters["url"],
      cache_time: parameters["cache_time"],
      clientId: clientId,
    );
  }

  if (parameters["is_sync"] != null) {
    return invokeSync(
      parameters: makeParametersApi({
        "@type": method,
        ...parameters,
      }),
      isThrowOnError: isInvokeThrowOnError ?? false,
    );
  } else {
    return await invoke(
      method,
      parameters: makeParametersApi({
        "@type": method,
        ...parameters,
      }),
      isUseCache: isUseCache,
      durationCacheExpire: durationCacheExpire,
      delayDuration: delayDuration,
      invokeTimeOut: invokeTimeOut,
      clientId: clientId,
      extra: extra,
      isAutoGetChat: isAutoGetChat,
      isInvokeThrowOnError: isInvokeThrowOnError ?? false,
      onGenerateExtraInvoke: onGenerateExtraInvoke,
      onGetInvokeData: onGetInvokeData,
    );
  }
}