executeFuture method

Future<String?> executeFuture(
  1. String _method,
  2. SellonMethod sellonMethod,
  3. Parameter _parameter,
  4. OnSuccessListener _onSuccessListener, {
  5. bool? encryption,
  6. String? urlFix,
})

Implementation

Future<String?> executeFuture(String _method, SellonMethod sellonMethod,
    Parameter _parameter, OnSuccessListener _onSuccessListener,
    {bool? encryption, String? urlFix}) async {
  // String? token = await Preferences.getToken();
  // if (token == null) {
  //   token =
  //       'e233df41ffb1bf15236d40f2a524bd5596913449924c8476903182c49a83c7c5';
  // }

  // print("paaa ${_parameter.data.toString()}");

  if (sellonMethod == SellonMethod.get) {
    var requestParams = "";
    var index = 0;

    _parameter.data?.forEach((key, val) {
      index++;
      requestParams +=
          "$key=$val${index == _parameter.data?.length ? '' : '&'}";
    });
    if (Config.openApi) {
      print("request ${Config().baseUrl}${_method}?$requestParams");
    }

    final http.Response response = await http
        .get(Uri.parse('${_getUrl(_method, urlFix: urlFix)}?$requestParams'))
        .catchError((onError) {
      print("errornya apaan ${onError}");
    });
    if (Config.openApi) {
      print("bnor ${_method} ${response.body.toString()} get ");
    }

    if (response != null) {
      if (response.statusCode == 200) {
        if (response.body != null || response.body.toString() != '') {
          return response.body;
        } else {
          this._onErrorListener!(
              new Error(this, response.statusCode, "${response.body}"));
          _handleResponseError(response.statusCode.toString(), response.body,
              _method, _parameter, _onSuccessListener);
        }
      } else {
        this._onErrorListener!(
            new Error(this, response.statusCode, "${response.body}"));
        _handleResponseError(response.statusCode.toString(), response.body,
            _method, _parameter, _onSuccessListener);
      }
    } else {
      if (response.statusCode != null) {
        this._onErrorListener!(
            new Error(this, response.statusCode, "${response.body}"));
        _handleResponseError(response.statusCode.toString(), response.body,
            _method, _parameter, _onSuccessListener);
      } else {
        // untuk pindah domain
        // if (Config.mainCoreDomain){
        //   Config.mainCoreDomain = false;
        //   // print("print main core ${Config.mainCoreDomain}");
        //   // Future.delayed(Duration(seconds: 3)).then((value) {
        //     SellonRouter.makeFirst(context, SplashSellonScreen());
        //   // });
        // }
        // print("mainCoreDong ${Config.mainCoreDomain}");
        if (!Config.isMaintanceShutDown) {
          // SellonRouter.makeFirst(context, MaintanceScreen(isErrorApi: true,domainbefore: Config.domainMain == "sellon.net" ? "sellon.store" : "sellon.net" ,key: UniqueKey(),));
        }
        // this._onErrorListener(new Error(this, 9999, "Maintaince Page"));
        // _handleResponseError(9999.toString(), "Maintaince Page",
        //     _method, _parameter, _onSuccessListener);
      }
    }
  } else {
    var requestParams = "";
    var index = 0;

    _parameter.data?.forEach((key, val) {
      index++;
      if (val is File) {
      } else {
        if (val is String) {
          if (!val.toString().contains("#")) {
            if (!key.contains("watched_video")) {
              if (_method == "community/baru/" ||
                  _method == "community/edit/" ||
                  _method == "chat/send/" ||
                  _method == "community/add_discussion/" ||
                  _method == "produk/add_discussion/" ||
                  _method == "produk/baru/" ||
                  _method == "produk/edit/" ||
                  _method == "community/" ||
                  _method == "registerv2" ||
                  _method == "pelanggan/daftar/" ||
                  _method == "pelanggan/daftarv2/" ||
                  _method == "pelanggan/daftarv3" ||
                  _method == "pelanggan/login_sosmedv3") {
                // if (key.toString().contains("username")) {
                //   requestParams +=
                //   "$key=$val${index == _parameter.data.length ? '' : '&'}";
                // }
                // if (key.toString().contains("password")) {
                //   requestParams +=
                //   "$key=$val${index == _parameter.data.length ? '' : '&'}";
                // }
                // if (key.toString().contains("telp")) {
                //   requestParams +=
                //   "$key=$val${index == _parameter.data.length ? '' : '&'}";
                // }

                // if (_method == MethodsSellon.pelangganLoginSosmed3){
                //   if (key.toString().contains("apikey")) {
                //     // print("confi meth ${Config.postMethod}");
                //     // if (!Config.postMethod!){
                //     requestParams +=
                //     "$key=$val${index == _parameter.data?.length ? '' : '&'}";
                //     // }
                //   }
                // }

                if (!encryption!) {
                  if (key.toString().contains("apikey")) {
                    // print("confi meth ${Config.postMethod}");
                    // if (!Config.postMethod!){
                    requestParams +=
                        "$key=$val${index == _parameter.data?.length ? '' : '&'}";
                    // }
                  }
                  if (key.toString().contains("apisess")) {
                    if (val != null || val != "null") {
                      requestParams +=
                          "$key=$val${index == _parameter.data?.length ? '' : '&'}";
                    }
                  }
                }

                if (key.toString().contains("timezone")) {
                  requestParams +=
                      "$key=$val${index == _parameter.data?.length ? '' : '&'}";
                }
                if (key.toString().contains("nation_code")) {
                  requestParams +=
                      "$key=$val${index == _parameter.data?.length ? '' : '&'}";
                }
              } else {
                if (key == "bla1" ||
                    key == "bla2" ||
                    key == "bla3" ||
                    key == "samsung" ||
                    key == "fullhd" ||
                    key == "nvidia" ||
                    key == "baby" ||
                    key == "token" ||
                    key == "booom") {
                } else {
                  if (!encryption!) {
                    if (key.toString().contains("nation_code")) {
                      requestParams +=
                          "$key=$val${index == _parameter.data?.length ? '' : '&'}";
                    }
                  } else {
                    if (val != "Buy&Sell") {
                      requestParams +=
                          "$key=$val${index == _parameter.data?.length ? '' : '&'}";
                    }
                  }
                }
              }
            }
          }
        } else {
          requestParams +=
              "$key=$val${index == _parameter.data?.length ? '' : '&'}";
        }
      }
    });
    Parameter paramnew = Parameter();
    Parameter fileParam = Parameter();
    if (encryption!) {
      await Helper().checksodium().then((sodium) async {
        Parameter getParamNoFile = Parameter();
        _parameter.getData().forEach((key, value) {
          if (value is File) {
            fileParam.set(key, value);
          } else {
            getParamNoFile.set(key, value);
          }
        });

        ParameterRegisterNew par = await Helper().encryparamater(
            sodium,
            getParamNoFile.getJson(),
            urlFix != null && urlFix.contains("wallet")
                ? "clubWallet"
                : "apikey");

        paramnew.set("booom", par.postData);
        paramnew.set("baby", par.bla1);
        paramnew.set("token", par.bla2);

        // print("value key --> ${par.postData}");
        // print("value keyserver ${Config().keyapikey}");
        // print("public key mobile => ${par.bla1} nonce ==>${par.bla2}");
      });
    }

    // print("parame ${requestParams}");

    // if(_method == "community/"){
    //   print("resq ${requestParams}");
    // }
    // print("call Api ${_method}");

    var request = http.MultipartRequest("POST",
        Uri.parse(_getUrl(_method, urlFix: urlFix) + '?$requestParams'));
    // print("request ${_getUrl(_method, urlFix: urlFix)}?${requestParams}");
    // print("request2 ${request.url.toString()}");
    if (Config.openApi) {
      // print("request ${_getUrl(_method)}?${requestParams}");
      print("request2 ${request.url.toString()}");
    }

    if (encryption) {
      paramnew.data?.forEach((key, value) {
        request.fields[key] = '$value';
      });
      fileParam.data?.forEach((k, v) {
        if (v is File) {
          File file = v;
          if (file.existsSync()) {
            String basename = file.path
                .split('/')
                .last
                .toString()
                .split(".")
                .first
                .toString();

            // String basename = path.basename(
            //     pathh.substring(0, pathh.lastIndexOf(".") + 1) +
            //         getMimeType(pathh));
            // var stream = new http.ByteStream(Dele)
            // var stream = new http.ByteStream(DelegatingStream.typed(file.openRead()));
            var filestream = file.readAsBytes().asStream();
            var length = file.lengthSync();
            http.MultipartFile multipartFile = new http.MultipartFile(
                "$k", filestream, length,
                filename: basename);

            // var byet = file.readAsBytesSync();
            // final httpImage = http.MultipartFile.fromBytes('files.myimage', byet,
            //     contentType: MediaType.parse(mimeType), filename: 'myImage.png');
            request.files.add(multipartFile);
          }
        } else {
          request.fields[k] = '$v';
        }
      });
    } else {
      _parameter.data?.forEach((k, v) async {
        if (v is File) {
          File file = v;
          if (file.existsSync()) {
            String basename = file.path
                .split('/')
                .last
                .toString()
                .split(".")
                .first
                .toString();

            // String basename = path.basename(
            //     pathh.substring(0, pathh.lastIndexOf(".") + 1) +
            //         getMimeType(pathh));
            // var stream = new http.ByteStream(Dele)
            // var stream = new http.ByteStream(DelegatingStream.typed(file.openRead()));
            var filestream = file.readAsBytes().asStream();
            var length = file.lengthSync();
            http.MultipartFile multipartFile = new http.MultipartFile(
                "$k", filestream, length,
                filename: basename);

            // var byet = file.readAsBytesSync();
            // final httpImage = http.MultipartFile.fromBytes('files.myimage', byet,
            //     contentType: MediaType.parse(mimeType), filename: 'myImage.png');
            request.files.add(multipartFile);
          }
        } else {
          request.fields[k] = '$v';
        }
      });
    }

    try {
      var response = await request.send();
      // .timeout(timeoutDuration!, onTimeout: () async {
      //   _handleResponseError(
      //       null, null, _method, _parameter, _onSuccessListener);
      //   return null;
      //   // return "true";
      // });

      // print("ses ${response}");

      String body = await response.stream.bytesToString();

      if (Config.openApi) {
        print("post ${_method} ${body}");
      }

      if (response != null) {
        if (response.statusCode == 200) {
          return body;
        }
        // else if (response.statusCode == 404){
        //   Helper().goErrorModalButton(context,
        //       message: "Service is temporarily unavailable now, please try again later", oketitle: "Close", onOke: () {
        //         Navigator.of(context).pushReplacement(
        //           new MaterialPageRoute(
        //               builder: (context) => SplashSellonScreen()),
        //         );
        //       });
        // }
        else {
          this._onErrorListener!(
              new Error(this, response.statusCode, "${body}"));
          _handleResponseError(response.statusCode.toString(), body, _method,
              _parameter, _onSuccessListener);
        }
      } else {
        Config.ServerAlive = false;
        if (response.statusCode != null) {
          this._onErrorListener!(
              new Error(this, response.statusCode, "${body}"));
          _handleResponseError(response.statusCode.toString(), body, _method,
              _parameter, _onSuccessListener);
        } else {
          if (!Config.isMaintanceShutDown) {
            // SellonRouter.makeFirst(context, MaintanceScreen(isErrorApi: true,domainbefore: Config.domainMain == "sellon.net" ? "sellon.store" : "sellon.net" ,key: UniqueKey(),));
          }
        }
      }
    } catch (exp) {
      if (_onExceptionListener != null && exp is Exception) {
        _onExceptionListener!(exp);
      }
    }
  }
  //   return "true";
}