executeFuture method

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

Implementation

Future<String?> executeFuture(String _method, SellonMethod sellonMethod,
    Parameter _parameter, OnSuccessListener _onSuccessListener,{bool? encryption}) 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");
    }

    Map<String,String> headerSport = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    };

    await Preferences.getTokenSport().then((tokenSport) async {
      if (tokenSport != null){
        headerSport = {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $tokenSport',
        };
      }
    });

    final http.Response response = await http.get(Uri.parse('${_getUrl(_method)}?$requestParams'),headers: headerSport).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{

      }
    }

  }
  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 == "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"){

                }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();
    if (encryption!){
      await Helper().checksodium().then((sodium) async {
        ParameterRegisterNew par = await Helper().encryparamater(sodium, _parameter.getJson(),"apikey");

        paramnew.set("nvidia", par.postData);
        paramnew.set("samsung", par.bla1);
        paramnew.set("fullhd", 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) + ''));

    await Preferences.getTokenSport().then((tokenSport) async {
      if (tokenSport != null){
        Map<String,String> headerSport = {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $tokenSport',
        };
        request.headers.addAll(headerSport);
      }
    });




    if (Config.openApi) {
      // print("request param method${_method} ${requestParams} ");
      // print("request ${_getUrl(_method)}?${requestParams}");
      // print("request2 ${request.url.toString()}");
    }
    print("request ${_getUrl(_method)}?${requestParams}");
    print("request2 ${request.url.toString()}");

    if (encryption){
      paramnew.data?.forEach((key, value) {
        request.fields[key] = '$value';
      });
    }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("response connection $_method ==> ${response.statusCode}");
      }

      if (response != null) {
        if (response.statusCode == 200) {
          return body;
        }
        else {
          this._onErrorListener!(
              new Error(this, response.statusCode, "${body}"));
          _handleResponseError(response.statusCode.toString(), body, _method,
              _parameter, _onSuccessListener);
        }
      } else {
        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";
}