Skip to content

Commit

Permalink
Adjusting bot features for Weesac
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielramosalv committed Aug 11, 2024
1 parent a3c6cab commit 46f02a1
Show file tree
Hide file tree
Showing 58 changed files with 1,243 additions and 947 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,17 @@ protected ResponseEntity post(AuthenticatedUser authenticatedUser, Map<String, O
return responseEntity.status(HttpServletResponse.SC_BAD_REQUEST).message(
"The 'username' and 'password' parameters are empty or do not exist.");
}
boolean isDefaultHost = false;

if (host == null || host.isEmpty()) {
host = DEFAULT_HOST;
isDefaultHost = true;
}

SSHExecutor sshExecutor = new SSHExecutor(username, password, host);
if (sshExecutor.test()) {
String jwt = JWT.create().withSubject(username).sign(JWT_ALGORITHM);
Date date = new Date(System.currentTimeMillis() + EXPIRATION_TIME);
Executor executor;
if (isDefaultHost) {
if (host.equals(DEFAULT_HOST)) {
executor = new RuntimeExecutor();
} else {
executor = new SSHExecutor(username, password, host);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ protected ResponseEntity get(AuthenticatedUser authenticatedUser, Map<String, Ob
return null;
}

protected ResponseEntity delete(Map<String, Object> parameters) {
return null;
}

protected ResponseEntity get(Map<String, Object> parameters) {
return null;
}
Expand Down Expand Up @@ -66,8 +70,8 @@ private Map<String, Object> getParameters(HttpServletRequest request) {
parameters.put(parameterName, request.getParameter(parameterName));
}
try {
String dataString = new BufferedReader(new InputStreamReader(request.getInputStream())).lines().collect(
Collectors.joining());
String dataString = new BufferedReader(new InputStreamReader(request.getInputStream())).lines()
.collect(Collectors.joining());
parameters.put("data", dataString);
} catch (IOException e) {
throw new RuntimeException(e);
Expand Down Expand Up @@ -105,14 +109,12 @@ private void flush(HttpServletResponse resp, ResponseEntity responseEntity) {
ReturnedFile masReturnedFile = ((ReturnedFile) data);

resp.setContentType("application/octet-stream");
resp.setHeader("Content-disposition",
String.format("attachment; filename=\"%s.zip\"", masReturnedFile.getFileName()));
resp.setHeader("Content-disposition", String.format("attachment; filename=\"%s.zip\"", masReturnedFile.getFileName()));

ResponseUtil.writeBinary(resp, masReturnedFile.getInputStream());
} else {
resp.setCharacterEncoding(HttpEncoding.UTF_8.getType());
resp.setHeader("Content-Type",
HttpContent.JSON.getType() + "; charset=" + HttpEncoding.ISO_8859_1.getType());
resp.setHeader("Content-Type", HttpContent.JSON.getType() + "; charset=" + HttpEncoding.ISO_8859_1.getType());
ResponseUtil.writeText(resp, JsonManager.get().toJson(responseEntity));
}
try {
Expand Down Expand Up @@ -150,8 +152,13 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) {

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
AuthenticatedUser authenticatedUser = (AuthenticatedUser) req.getAttribute("user");
ResponseEntity responseEntity = this.delete(authenticatedUser, this.getParameters(req));
ResponseEntity responseEntity;
if (this.userLogged) {
AuthenticatedUser authenticatedUser = (AuthenticatedUser) req.getAttribute("user");
responseEntity = this.delete(authenticatedUser, this.getParameters(req));
} else {
responseEntity = this.delete(this.getParameters(req));
}
this.flush(resp, responseEntity);
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package group.chon.ide.api.api.controller.development.firmware;

import group.chon.ide.api.api.controller.ApiController;
import group.chon.ide.api.api.authentication.AuthenticatedUser;
import group.chon.ide.api.api.controller.ApiController;
import group.chon.ide.api.api.controller.ResponseEntity;
import group.chon.ide.api.domain.script.FirmwareScriptManager;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@WebServlet("/api/sketchs/deploy")
Expand All @@ -15,8 +16,8 @@ public class DeploySketch extends ApiController {
protected ResponseEntity post(AuthenticatedUser authenticatedUser, Map<String, Object> parameters) {
String boardName = parameters.get("boardName").toString();
String serialPort = parameters.get("serialPort").toString();
return ResponseEntity.get().data(authenticatedUser.getExecutor()
.execute(FirmwareScriptManager.mountArduinoDeploySketchScript(boardName, serialPort), true));
return ResponseEntity.get().status(HttpServletResponse.SC_OK).data(authenticatedUser.getExecutor()
.execute(FirmwareScriptManager.mountArduinoDeploySketchScript(boardName, serialPort), true));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,17 @@ public class ConnectApNetwork extends ApiController {
protected ResponseEntity post(AuthenticatedUser authenticatedUser, Map<String, Object> parameters) {
String essid = (String) parameters.get("essid");
String password = (String) parameters.get("password");
boolean restart = false;
if (parameters.containsKey("restart")) {
restart = Boolean.parseBoolean((String) parameters.get("restart"));
}

String command = !password.isEmpty() ? ConnectionScriptManager.mountWifiAPModeScript(essid, password) :
ConnectionScriptManager.mountWifiAPModaScript(essid);
if (restart) {
command += " --reboot";
}

authenticatedUser.getExecutor().execute(command, false);
return ResponseEntity.get().status(HttpServletResponse.SC_OK);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,16 @@ public class ConnectClientNetwork extends ApiController {
protected ResponseEntity post(AuthenticatedUser authenticatedUser, Map<String, Object> parameters) {
String essid = (String) parameters.get("essid");
String password = (String) parameters.get("password");
String command = !password.isEmpty() ? ConnectionScriptManager.mountWifiClientModeScript(essid, password) :
ConnectionScriptManager.mountWifiClientModeScript(essid);
boolean restart = false;
if (parameters.containsKey("restart")) {
restart = Boolean.parseBoolean((String) parameters.get("restart"));
}

String command = !password.isEmpty() ? ConnectionScriptManager.mountWifiClientModeScript(essid, password) : ConnectionScriptManager.mountWifiClientModeScript(essid);
if (restart) {
command += " --reboot";
}

authenticatedUser.getExecutor().execute(command, false);
return ResponseEntity.get().status(HttpServletResponse.SC_OK);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@
@WebServlet("/api/networks")
public class GetNetworks extends ApiController {

@Override
protected ResponseEntity delete(AuthenticatedUser authenticatedUser, Map<String, Object> parameters) {
authenticatedUser.getExecutor().execute(ConnectionScriptManager.WIFI_FORGET, false);
return ResponseEntity.get().status(HttpServletResponse.SC_OK);
}

@Override
protected ResponseEntity get(AuthenticatedUser authenticatedUser, Map<String, Object> parameters) {
String allNetworksResponse = authenticatedUser.getExecutor().execute(ConnectionScriptManager.WIFI_SCAN_LIST,
Expand Down Expand Up @@ -51,9 +57,9 @@ protected ResponseEntity get(AuthenticatedUser authenticatedUser, Map<String, Ob
}
String[] quality = networkJsonElement.get("quality").getAsString().split("/");
networkJsonElement.remove("quality");
Double qualityValue;
double qualityValue;
try {
qualityValue = Double.valueOf(Double.parseDouble(quality[0]) / Double.parseDouble(quality[1]));
qualityValue = Double.parseDouble(quality[0]) / Double.parseDouble(quality[1]);
} catch (Exception ignored) {
qualityValue = 0.0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import group.chon.ide.api.api.controller.ApiController;
import group.chon.ide.api.api.controller.ResponseEntity;
import group.chon.ide.api.domain.model.RuntimeExecutor;
import group.chon.ide.api.domain.script.NeighborsScriptManager;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletResponse;
Expand All @@ -15,9 +16,16 @@ public Neighbors() {
super(false);
}

@Override
protected ResponseEntity delete(Map<String, Object> parameters) {
String execute = new RuntimeExecutor().execute(NeighborsScriptManager.FORGET, false);
return ResponseEntity.get().status(HttpServletResponse.SC_OK)
.data(execute);
}

@Override
protected ResponseEntity get(Map<String, Object> parameters) {
return ResponseEntity.get().status(HttpServletResponse.SC_OK)
.data(new RuntimeExecutor().execute("chonos-neighbors --list", false));
.data(new RuntimeExecutor().execute(NeighborsScriptManager.LIST, false));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/system/attributes")
Expand All @@ -15,17 +20,43 @@ public SystemAttributes() {
super(false);
}

private List<String> getUsers() {
List<String> users = new ArrayList<>();
try {
// Comando para obter informações dos usuários
String[] command = {"bash", "-c", "cat /etc/passwd | grep bash | cut -d ':' -f 1"};

// Executa o comando
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();

// Lê a saída do comando
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
users.add(line);
}

// Aguarda o término do processo
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return users;
}

@Override
protected ResponseEntity get(Map<String, Object> parameters) {
return ResponseEntity.get().status(HttpServletResponse.SC_OK)
.data(new Attributes(System.getProperty("user.name")));
return ResponseEntity.get().status(HttpServletResponse.SC_OK).data(new Attributes(this.getUsers()));
}

@AllArgsConstructor
private static class Attributes {

/** Usuário do computador. */
private final String username;
/**
* Usuário do computador.
*/
private final List<String> users;

}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
package group.chon.ide.api.api.controller.system;

import group.chon.ide.api.api.authentication.AuthenticatedUser;
import group.chon.ide.api.api.controller.ApiController;
import group.chon.ide.api.api.controller.ResponseEntity;
import group.chon.ide.api.domain.model.RuntimeExecutor;
import group.chon.ide.api.domain.script.SystemScriptManager;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@WebServlet("/system/configuration")
@WebServlet("/api/system/configuration")
public class SystemConfiguration extends ApiController {

public SystemConfiguration() {
super(false);
}

@Override
protected ResponseEntity get(Map<String, Object> parameters) {
protected ResponseEntity get(AuthenticatedUser authenticatedUser, Map<String, Object> parameters) {
String execute = authenticatedUser.getExecutor()
.execute(SystemScriptManager.GET_CONFIGURATION, false);
return ResponseEntity.get().status(HttpServletResponse.SC_OK)
.data(new RuntimeExecutor().execute(SystemScriptManager.GET_CONFIGURATION, false));
.data(execute);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public static void deleteLibrary(String libName, Executor executor) {
}

public static boolean isValidSubmittedLibrary(Part submittedLibrary) {
return submittedLibrary.getSize() > 0 && submittedLibrary.getSubmittedFileName().endsWith(
return submittedLibrary.getSubmittedFileName().endsWith(
FileUtils.COMPACTED_FILE_EXTENSION);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ private synchronized String executeInRemote(String command) {
@Override
public String execute(String command, boolean mantainLineBreak) {
String output = this.executeInRemote(command);
if (!mantainLineBreak) {
if (!mantainLineBreak && output != null) {
return output.replace(FileUtils.BREAK_LINE, "");
}
return output;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class ConnectionScriptManager {
private static final String DDNS_MANAGER_COMMAND = "chonosDDNSManager ";

/** Script para configurar o domínio DDNS de acesso ao sistema. */
private static final String DDNS_CONF = DDNS_MANAGER_COMMAND + "-o conf -d %s -u %s -t %s";
private static final String DDNS_CONF = DDNS_MANAGER_COMMAND + "--conf -d %s -u %s -t %s";

/** Script para status do domínio atual. */
public static final String DDNS_STATUS = DDNS_MANAGER_COMMAND + "--status";
Expand All @@ -33,10 +33,10 @@ public class ConnectionScriptManager {
private static final String WIFI_AP_MODE_WITHOUT_ENCRIPTION = WIFI_CONF_COMMAND + "-m ap -e %s -k NONE";

/** Script para realizar conexão em modo cliente com encriptação do sistema. */
private static final String WIFI_CLIENT_MODE_WITH_ENCRIPTION = WIFI_CONF_COMMAND + "-m client -e %s -k %s --reboot";
private static final String WIFI_CLIENT_MODE_WITH_ENCRIPTION = WIFI_CONF_COMMAND + "-m client -e %s -k %s";

/** Script para realizar conexão em modo cliente sem encriptação do sistema. */
private static final String WIFI_CLIENT_MODE_WITHOUT_ENCRIPTION = WIFI_CONF_COMMAND + "-m client -e %s --reboot";
private static final String WIFI_CLIENT_MODE_WITHOUT_ENCRIPTION = WIFI_CONF_COMMAND + "-m client -e %s";

/** Comando para interação de conexão wi-fi. */
private static final String WIFI_CONN_COMMAND = "chonosWifiConn ";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@
public class FirmwareScriptManager {

/** Comando para interação com o(s) firmware(s) do sistema. */
private static final String FIRMWARE_MANAGER_COMMAND = "chonosFirmwareManager ";
private static final String FIRMWARE_MANAGER_COMMAND = "sudo chonosFirmwareManager ";

/** Script para listar as placas do sistema. */
public static final String ARDUINO_LIST_BOARDS = FIRMWARE_MANAGER_COMMAND + "--list";
public static final String ARDUINO_LIST_BOARDS = FIRMWARE_MANAGER_COMMAND + "--listBoards";

/** Script para listar as bibliotecas das placas do sistema. */
public static final String ARDUINO_LIST_LIBRARIES = FIRMWARE_MANAGER_COMMAND + "--listLibraries";

/** Script para importação biblioteca para as placas do sistema. */
private static final String ARDUINO_IMPORT_LIBRARY = FIRMWARE_MANAGER_COMMAND + "-i '%s'";
private static final String ARDUINO_IMPORT_LIBRARY = FIRMWARE_MANAGER_COMMAND + "--importLibrary -f %s";

/** Script para compilar um sketch para uma placa. */
private static final String ARDUINO_COMPILE_SKETCH = FIRMWARE_MANAGER_COMMAND + "-s tempSketchSysConf -f %s -b %s";
Expand All @@ -24,7 +24,7 @@ public class FirmwareScriptManager {
private static final String ARDUINO_DEPLOY_SKETCH = FIRMWARE_MANAGER_COMMAND + "-d tempSketchSysConf -b %s -p %s";

/** Script para remover uma bilbioteca. */
private static final String ARDUINO_REMOVE_LIBRARY = FIRMWARE_MANAGER_COMMAND + "--removeLibrary '%s'";
private static final String ARDUINO_REMOVE_LIBRARY = FIRMWARE_MANAGER_COMMAND + "--removeLibrary %s";

/**
* Retorna o script formatado para importação de biblioteca.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package group.chon.ide.api.domain.script;

/**
* Scripts relativos aos vizinhos do robo.
*/
public class NeighborsScriptManager {

/** Lista todos os vizinhos. */
public static final String LIST = "sudo chonos-neighbors --list";

/** Esquece todos os vizinhos. */
public static final String FORGET = "sudo chonos-neighbors --forget";

}

This file was deleted.

Loading

0 comments on commit 46f02a1

Please sign in to comment.