private ServerResponse connectHTTP(String monkeyId, String encriptedKeys, JSONArray ignore_params)
      throws JSONException, IOException {

    // Create a new HttpClient and Post Header
    HttpClient httpclient = MonkeyHttpClient.newClient();
    HttpPost httppost =
        MonkeyHttpClient.newPost(
            MonkeyKitSocketService.Companion.getHttpsURL() + "/user/connect", urlUser, urlPass);

    JSONObject localJSONObject1 = new JSONObject();

    localJSONObject1.put("usk", encriptedKeys);
    localJSONObject1.put("monkey_id", monkeyId);
    localJSONObject1.put("ignore_params", ignore_params);

    JSONObject params = new JSONObject();
    params.put("data", localJSONObject1.toString());
    Log.d("connectHTTP", "Req: " + params.toString());

    JSONObject finalResult = MonkeyHttpClient.getResponse(httpclient, httppost, params.toString());
    Log.d("connectHTTP", finalResult.toString());
    finalResult = finalResult.getJSONObject("data");

    prefs.edit().putString("sdomain", finalResult.getString("sdomain")).apply();
    prefs.edit().putString("sport", finalResult.getString("sport")).apply();

    final String domain = finalResult.getString("sdomain");
    final int port = finalResult.getInt("sport");
    return new ServerResponse(monkeyId, domain, port);
  }
  public void getUsersInfo(final String monkeyIds) {

    String endpoint = "/users/info";

    try {
      JSONObject localJSONObject1 = new JSONObject();
      localJSONObject1.put("monkey_ids", monkeyIds);

      Map<String, Object> params = new HashMap<String, Object>();
      params.put("data", localJSONObject1.toString());

      aq.auth(handle)
          .ajax(
              MonkeyKitSocketService.Companion.getHttpsURL() + endpoint,
              params,
              JSONObject.class,
              new AjaxCallback<JSONObject>() {
                @Override
                public void callback(String url, JSONObject response, AjaxStatus status) {

                  MonkeyKitSocketService service = serviceRef.get();
                  if (service == null) return;

                  if (response != null) {
                    try {
                      ArrayList<MOKUser> mokUserArrayList = new ArrayList<MOKUser>();
                      for (int i = 0; i < response.getJSONArray("data").length(); i++) {
                        JSONObject jsonObject = response.getJSONArray("data").getJSONObject(i);
                        JsonParser jsonParser = new JsonParser();
                        JsonObject gsonObject =
                            (JsonObject) jsonParser.parse(jsonObject.toString());
                        mokUserArrayList.add(
                            new MOKUser(gsonObject.get("monkey_id").getAsString(), gsonObject));
                      }

                      service.processMessageFromHandler(
                          CBTypes.onGetUsersInfo, new Object[] {mokUserArrayList, null});
                    } catch (Exception e) {
                      e.printStackTrace();
                      service.processMessageFromHandler(
                          CBTypes.onGetUsersInfo, new Object[] {null, e});
                    }
                  } else {
                    service.processMessageFromHandler(
                        CBTypes.onGetUsersInfo,
                        new Object[] {
                          new Exception(
                              "Error code:"
                                  + status.getCode()
                                  + " -  Error msg:"
                                  + status.getMessage())
                        });
                  }
                }
              });
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void deleteConversation(final String monkeyid, final String conversation_id) {

    try {
      String urlconnect =
          MonkeyKitSocketService.Companion.getHttpsURL() + "/user/delete/conversation";

      JSONObject localJSONObject1 = new JSONObject();
      localJSONObject1.put("conversation_id", conversation_id);
      localJSONObject1.put("monkey_id", monkeyid);

      Map<String, Object> params = new HashMap<String, Object>();
      params.put("data", localJSONObject1.toString());

      aq.auth(handle)
          .ajax(
              urlconnect,
              params,
              JSONObject.class,
              new AjaxCallback<JSONObject>() {
                @Override
                public void callback(String url, JSONObject response, AjaxStatus status) {

                  MonkeyKitSocketService service = serviceRef.get();
                  if (service == null) return;

                  if (response != null)
                    try {
                      service.processMessageFromHandler(
                          CBTypes.onDeleteConversation,
                          new Object[] {
                            response.getJSONObject("data").getString("conversation"), null
                          });
                    } catch (JSONException e) {
                      e.printStackTrace();
                      service.processMessageFromHandler(
                          CBTypes.onDeleteConversation, new Object[] {conversation_id, e});
                    }
                  else {
                    service.processMessageFromHandler(
                        CBTypes.onDeleteConversation,
                        new Object[] {
                          conversation_id,
                          new Exception(
                              "Error code:"
                                  + status.getCode()
                                  + " -  Error msg:"
                                  + status.getMessage())
                        });
                  }
                }
              });
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  private ServerResponse userSync(final String monkeyId) throws Exception {

    // Create a new HttpClient and Post Header
    RSAUtil rsaUtil = new RSAUtil();
    rsaUtil.generateKeys();

    HttpClient httpclient = MonkeyHttpClient.newClient();
    HttpPost httppost =
        MonkeyHttpClient.newPost(
            MonkeyKitSocketService.Companion.getHttpsURL() + "/user/key/sync", urlUser, urlPass);

    JSONObject localJSONObject1 = new JSONObject();

    localJSONObject1.put("monkey_id", monkeyId);
    localJSONObject1.put(
        "public_key",
        "-----BEGIN PUBLIC KEY-----\n" + rsaUtil.getPublicKey() + "\n-----END PUBLIC KEY-----");
    // System.out.println("-----BEGIN PUBLIC KEY-----\n" + rsaUtil.pubKeyStr + "\n-----END PUBLIC
    // KEY-----");
    JSONObject params = new JSONObject();
    params.put("data", localJSONObject1.toString());
    Log.d("userSyncMS", "Req: " + params.toString());

    JSONObject finalResult = MonkeyHttpClient.getResponse(httpclient, httppost, params.toString());
    Log.d("userSyncMS", finalResult.toString());
    finalResult = finalResult.getJSONObject("data");

    final String keys = finalResult.getString("keys");
    final long lastSync = finalResult.getLong("last_time_synced");
    String decriptedKey = rsaUtil.desencrypt(keys);
    KeyStoreCriptext.putString(ctxRef.get(), monkeyId, decriptedKey);
    KeyStoreCriptext.setLastSync(ctxRef.get(), lastSync);

    try {
      aesUtil = new AESUtil(ctxRef.get(), monkeyId);
    } catch (Exception ex) {
      ex.printStackTrace();
      // Como fallo algo con esas keys las encero y creo unas nuevas
      KeyStoreCriptext.putString(ctxRef.get(), monkeyId, "");
      aesUtil = new AESUtil(ctxRef.get(), monkeyId);
      return getSessionHTTP(this.urlUser, this.urlPass, this.userInfo, this.ignore_params);
    }

    final String domain = finalResult.getString("sdomain");
    final int port = finalResult.getInt("sport");
    return new ServerResponse(monkeyId, domain, port);
  }
  public void updateUserData(final String monkeyId, JSONObject info) {

    try {
      String urlconnect = MonkeyKitSocketService.Companion.getHttpsURL() + "/user/update";

      JSONObject localJSONObject1 = new JSONObject();
      localJSONObject1.put("monkeyId", monkeyId);
      localJSONObject1.put("params", info);

      Map<String, Object> params = new HashMap<String, Object>();
      params.put("data", localJSONObject1.toString());

      aq.auth(handle)
          .ajax(
              urlconnect,
              params,
              JSONObject.class,
              new AjaxCallback<JSONObject>() {
                @Override
                public void callback(String url, JSONObject response, AjaxStatus status) {

                  MonkeyKitSocketService service = serviceRef.get();
                  if (service == null) return;

                  if (response != null)
                    service.processMessageFromHandler(
                        CBTypes.onUpdateUserData, new Object[] {monkeyId, null});
                  else
                    service.processMessageFromHandler(
                        CBTypes.onUpdateUserData,
                        new Object[] {
                          monkeyId,
                          new Exception(
                              "Error code:"
                                  + status.getCode()
                                  + " -  Error msg:"
                                  + status.getMessage())
                        });
                }
              });

    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
  public void getUserInfoById(final String monkeyid) {

    String endpoint = "/user/info/" + monkeyid;

    aq.auth(handle)
        .ajax(
            MonkeyKitSocketService.Companion.getHttpsURL() + endpoint,
            JSONObject.class,
            new AjaxCallback<JSONObject>() {
              @Override
              public void callback(String url, JSONObject response, AjaxStatus status) {

                MonkeyKitSocketService service = serviceRef.get();
                if (service == null) return;

                if (response != null) {
                  try {
                    JsonParser jsonParser = new JsonParser();
                    JsonObject gsonObject =
                        (JsonObject) jsonParser.parse(response.getJSONObject("data").toString());
                    service.processMessageFromHandler(
                        CBTypes.onGetUserInfo,
                        new Object[] {new MOKUser(monkeyid, gsonObject), null});
                  } catch (Exception e) {
                    e.printStackTrace();
                    service.processMessageFromHandler(
                        CBTypes.onGetUserInfo, new Object[] {new MOKUser(monkeyid), e});
                  }
                } else {
                  service.processMessageFromHandler(
                      CBTypes.onGetUserInfo,
                      new Object[] {
                        new MOKUser(monkeyid),
                        "Error code:" + status.getCode() + " -  Error msg:" + status.getMessage()
                      });
                }
              }
            });
  }
  private ServerResponse getSessionHTTP(
      String urlUser, String urlPass, JSONObject userInfo, JSONArray ignore_params)
      throws JSONException, UnsupportedEncodingException, ClientProtocolException, IOException {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = MonkeyHttpClient.newClient();
    HttpPost httppost =
        MonkeyHttpClient.newPost(
            MonkeyKitSocketService.Companion.getHttpsURL() + "/user/session", urlUser, urlPass);

    JSONObject localJSONObject1 = new JSONObject();

    localJSONObject1.put("username", urlUser);
    localJSONObject1.put("password", urlPass);
    localJSONObject1.put("monkey_id", myOldMonkeyId);
    localJSONObject1.put("expiring", "0");
    localJSONObject1.put("user_info", userInfo);

    JSONObject params = new JSONObject();
    params.put("data", localJSONObject1.toString());
    Log.d("getSessionHTTP", "Req: " + params.toString());

    JSONObject finalResult = MonkeyHttpClient.getResponse(httpclient, httppost, params.toString());

    Log.d("getSesssionHTTP", finalResult.toString());
    finalResult = finalResult.getJSONObject("data");

    String monkeyId = finalResult.getString("monkeyId");
    String pubKey = finalResult.getString("publicKey");
    pubKey =
        pubKey
            .replace("-----BEGIN PUBLIC KEY-----\n", "")
            .replace("\n-----END PUBLIC KEY-----", "");

    String encriptedKeys = storeKeysIV(monkeyId, pubKey);

    // retornar el session solo despues del connect exitoso
    return connectHTTP(finalResult.getString("monkeyId"), encriptedKeys, ignore_params);
  }
  public void getConversationMessages(
      String monkeyid,
      final String conversationId,
      int numberOfMessages,
      String lastTimeStamp,
      final AsyncConnSocket asyncConnSocket) {

    String newlastTimeStamp = lastTimeStamp;
    if (lastTimeStamp == null || lastTimeStamp.length() == 0 || lastTimeStamp.equals("0"))
      newlastTimeStamp = "";

    String urlconnect =
        MonkeyKitSocketService.Companion.getHttpsURL()
            + "/conversation/messages/"
            + monkeyid
            + "/"
            + conversationId
            + "/"
            + numberOfMessages
            + "/"
            + newlastTimeStamp;
    aq.auth(handle)
        .ajax(
            urlconnect,
            JSONObject.class,
            new AjaxCallback<JSONObject>() {
              @Override
              public void callback(String url, final JSONObject response, AjaxStatus status) {

                final MonkeyKitSocketService service = serviceRef.get();
                if (service == null) return;

                if (response != null) {

                  new AsyncTask<Object, String, Exception>() {

                    List<MOKMessage> messageList = new ArrayList<MOKMessage>();

                    @Override
                    protected Exception doInBackground(Object... p) {

                      try {
                        JsonParser parser = new JsonParser();
                        JsonObject props = new JsonObject(), params = new JsonObject();
                        JSONArray jsonArrayMessages =
                            response.getJSONObject("data").getJSONArray("messages");
                        JsonArray array = (JsonArray) parser.parse(jsonArrayMessages.toString());
                        MOKMessage remote;
                        for (int i = 0; i < array.size(); i++) {
                          JsonObject currentMessage = null;
                          try {
                            JsonElement jsonMessage = array.get(i);
                            currentMessage = jsonMessage.getAsJsonObject();
                            // init params props
                            if (currentMessage.has("params")
                                && !currentMessage.get("params").isJsonNull()
                                && !parser
                                    .parse(currentMessage.get("params").getAsString())
                                    .isJsonNull())
                              if (parser.parse(currentMessage.get("params").getAsString())
                                  instanceof JsonObject)
                                params =
                                    (JsonObject)
                                        parser.parse(currentMessage.get("params").getAsString());
                            if (currentMessage.has("props")
                                && !currentMessage.get("props").isJsonNull()
                                && !parser
                                    .parse(currentMessage.get("props").getAsString())
                                    .isJsonNull())
                              props =
                                  (JsonObject)
                                      parser.parse(currentMessage.get("props").getAsString());

                            if (currentMessage.has("type")
                                && (currentMessage
                                            .get("type")
                                            .getAsString()
                                            .compareTo(MessageTypes.MOKText)
                                        == 0
                                    || currentMessage
                                            .get("type")
                                            .getAsString()
                                            .compareTo(MessageTypes.MOKFile)
                                        == 0)) {

                              remote =
                                  asyncConnSocket.createMOKMessageFromJSON(
                                      currentMessage, params, props, true);
                              if (remote.getProps().has("encr")
                                  && remote.getProps().get("encr").getAsString().compareTo("1")
                                      == 0) {
                                remote = decryptMessage(remote);

                              } else if (remote.getProps().has("encoding")
                                  && !remote.getType().equals(MessageTypes.MOKFile)) {
                                if (remote
                                    .getProps()
                                    .get("encoding")
                                    .getAsString()
                                    .equals("base64"))
                                  remote.setMsg(
                                      new String(
                                          Base64.decode(
                                              remote.getMsg().getBytes(), Base64.NO_WRAP)));
                              }
                              if (remote != null) messageList.add(remote);
                            } else {
                              remote =
                                  new MOKMessage(
                                      currentMessage.get("id").getAsString(),
                                      currentMessage.get("sid").getAsString(),
                                      currentMessage.get("rid").getAsString(),
                                      currentMessage.get("msg").getAsString(),
                                      currentMessage.get("datetime").getAsString(),
                                      currentMessage.get("type").getAsString(),
                                      params,
                                      props);
                              remote.setDatetimeorder(Long.parseLong(remote.getDatetime()) * 1000);
                              messageList.add(remote);
                            }
                          } catch (Exception ex) {
                            ex.printStackTrace();
                          }
                        }

                      } catch (JSONException e) {
                        e.printStackTrace();
                        return e;
                      }

                      return null;
                    }

                    @Override
                    protected void onPostExecute(Exception e) {
                      service.processMessageFromHandler(
                          CBTypes.onGetConversationMessages,
                          new Object[] {conversationId, messageList, null});
                    }
                  }.execute("");

                } else
                  service.processMessageFromHandler(
                      CBTypes.onGetConversationMessages,
                      new Object[] {
                        new ArrayList<MOKMessage>(),
                        new Exception(
                            "Error code:"
                                + status.getCode()
                                + " -  Error msg:"
                                + status.getMessage())
                      });
              }
            });
  }