1357 lines
54 KiB
Java
Executable File
1357 lines
54 KiB
Java
Executable File
package ir.peeco.pline.plineServer;
|
|
|
|
import ir.peeco.pline.configuration.FixedSizeList;
|
|
import ir.peeco.pline.coreController.events.Events;
|
|
import ir.peeco.pline.plineServer.tools.GlobalTools;
|
|
import lombok.Getter;
|
|
import lombok.Setter;
|
|
import org.apache.logging.log4j.Logger;
|
|
import org.apache.logging.log4j.LogManager;
|
|
import org.asteriskjava.live.*;
|
|
import org.asteriskjava.manager.ManagerConnection;
|
|
import org.asteriskjava.manager.ManagerConnectionFactory;
|
|
import org.asteriskjava.manager.ManagerConnectionState;
|
|
import org.asteriskjava.manager.action.CommandAction;
|
|
import org.asteriskjava.manager.response.CommandResponse;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.context.annotation.Scope;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
|
import ir.peeco.pline.models.network.NetworkInterfaceIpAddressInfo;
|
|
import ir.peeco.pline.models.network.NetworkInterfacePhyInfo;
|
|
import ir.peeco.pline.models.network.NetworkSpeed;
|
|
import ir.peeco.pline.models.network.RouteInfo;
|
|
import ir.peeco.pline.plineServer.tools.dialPlan.DialPlanConfiguration;
|
|
import ir.peeco.pline.plineServer.tools.infoFile.InfoConfiguration;
|
|
import jakarta.annotation.PreDestroy;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.File;
|
|
import java.io.IOException;
|
|
import java.io.InputStreamReader;
|
|
import java.io.PrintWriter;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
import java.nio.file.Paths;
|
|
import java.nio.file.StandardOpenOption;
|
|
import java.util.*;
|
|
import java.util.concurrent.ArrayBlockingQueue;
|
|
import java.util.concurrent.Executors;
|
|
import java.util.concurrent.ScheduledExecutorService;
|
|
import java.util.concurrent.Semaphore;
|
|
import java.util.concurrent.TimeUnit;
|
|
import java.util.concurrent.atomic.AtomicInteger;
|
|
|
|
@Component
|
|
@Scope("singleton")
|
|
public class PlineTools {
|
|
|
|
private static final int DEFAULT_AMI_COMMAND_CONNECTIONS = 4;
|
|
private static final long AMI_COMMAND_TIMEOUT_MS = 5000;
|
|
private static final long AMI_RELOAD_TIMEOUT_MS = 60_000;
|
|
private static final long DEFAULT_AMI_COMMAND_IDLE_TIMEOUT_MS = 30_000;
|
|
private static final long AMI_COMMAND_POOL_SWEEP_INTERVAL_SECONDS = 10;
|
|
private static final long ASTERISK_CLI_TIMEOUT_SECONDS = 10;
|
|
private static final long ASTERISK_RELOAD_CLI_TIMEOUT_SECONDS = 60;
|
|
private final Object amiCommandPoolLock = new Object();
|
|
private final AtomicInteger amiCommandConnectionsCreated = new AtomicInteger();
|
|
private final ArrayBlockingQueue<IdleAmiCommandConnection> idleAmiCommandConnections =
|
|
new ArrayBlockingQueue<>(DEFAULT_AMI_COMMAND_CONNECTIONS);
|
|
private final Semaphore amiCommandSlots = new Semaphore(DEFAULT_AMI_COMMAND_CONNECTIONS, true);
|
|
private final Semaphore localCliFallbackSlots = new Semaphore(2, true);
|
|
private final ScheduledExecutorService amiCommandPoolMaintenance =
|
|
Executors.newSingleThreadScheduledExecutor(runnable -> {
|
|
Thread thread = new Thread(runnable, "ami-command-pool-maintenance");
|
|
thread.setDaemon(true);
|
|
return thread;
|
|
});
|
|
|
|
@Value("${pline.ami-command-idle-timeout-ms:" + DEFAULT_AMI_COMMAND_IDLE_TIMEOUT_MS + "}")
|
|
private long amiCommandIdleTimeoutMs = DEFAULT_AMI_COMMAND_IDLE_TIMEOUT_MS;
|
|
|
|
private AppSettingsService appSettingsService;
|
|
|
|
@Autowired
|
|
public void setAppSettingsService(AppSettingsService appSettingsService) {
|
|
this.appSettingsService = appSettingsService;
|
|
}
|
|
|
|
@Getter
|
|
private String amiPlineHost = "127.0.0.1";
|
|
|
|
@Getter
|
|
private int amiPlinePort = 2342;
|
|
|
|
@Getter
|
|
private String amiPlineUsername = "pline";
|
|
|
|
@Getter
|
|
private String amiPlinePassword = "pline-core-password";
|
|
|
|
@Getter
|
|
private int agiPlinePort = 6377;
|
|
|
|
@Getter
|
|
private List<String> allSipUsersContext;
|
|
|
|
@Getter
|
|
@Value("${pline.core}")
|
|
private String core;
|
|
|
|
@Getter
|
|
@Value("${pline.version}")
|
|
private String version;
|
|
|
|
@Value("${pline.debug}")
|
|
private boolean debug;
|
|
|
|
@Value("${pline.call_record_path}")
|
|
private String callRecordPath;
|
|
|
|
@Value("${asterisk.docker-mode:false}")
|
|
private boolean asteriskDockerMode;
|
|
|
|
@Value("${asterisk.container-name:asterisk}")
|
|
private String asteriskContainerName;
|
|
|
|
@Value("${asterisk.base-path:/opt/cti}")
|
|
private String asteriskBasePath;
|
|
|
|
@Setter
|
|
private String callRecordPathInNas;
|
|
|
|
@Setter
|
|
private String faxPathInNas;
|
|
|
|
@Setter
|
|
private String backupPathInNas;
|
|
|
|
@Setter
|
|
@Getter
|
|
private String deleteOldFilesAfterPercentUserValue;
|
|
|
|
@Value("${pline.owner_group_folders}")
|
|
private String ownerGroupFolders;
|
|
|
|
@Getter
|
|
@Value("${pline.app_name}")
|
|
private String appName;
|
|
|
|
@Getter
|
|
@Value("${pline.app_footer}")
|
|
private String appFooter;
|
|
|
|
@Getter
|
|
@Value("${pline.app_website}")
|
|
private String appWebsite;
|
|
|
|
private final Logger logger;
|
|
|
|
@Setter
|
|
@Getter
|
|
private List<String> internalDialPattern = new ArrayList<>();
|
|
|
|
@Getter
|
|
private final FixedSizeList menuTokens;
|
|
|
|
@Getter
|
|
private DefaultAsteriskServer plineServer = null;
|
|
|
|
@Getter
|
|
private ManagerConnection managerConnection = null;
|
|
|
|
private final Timer tmrTryConnect;
|
|
private final Timer tmrCheckCdr;
|
|
|
|
public boolean getDialContacts() {
|
|
return appSettingsService.getAppSettings().isDialContacts();
|
|
}
|
|
|
|
public String getBanner() {
|
|
var banner = "\n;#########################################\n"
|
|
+ ";# #\n"
|
|
+ ";# Name: [P-Line] #\n"
|
|
+ ";# Website: https://raymandcti.com/ #\n"
|
|
+ ";# Support: support@raymandcti.com #\n"
|
|
+ ";# Powered by: Asterisk-Core 16 #\n"
|
|
+ ";# #\n"
|
|
+ ";#########################################\n"
|
|
+ ";version: (" + version + ")\n\n";
|
|
|
|
return banner.replace("raymandcti", getCore());
|
|
|
|
}
|
|
|
|
public String getCallRecordPath() {
|
|
if (callRecordPathInNas != null && !callRecordPathInNas.isEmpty()) {
|
|
if (callRecordPathInNas.endsWith("/"))
|
|
return callRecordPathInNas + "call_record/";
|
|
return callRecordPathInNas + "/call_record/";
|
|
}
|
|
if (callRecordPath == null)
|
|
return getAsteriskHostPath("/var/spool/" + core + "/monitor/");
|
|
if (callRecordPath.endsWith("/"))
|
|
return getAsteriskHostPath(callRecordPath);
|
|
return getAsteriskHostPath(callRecordPath + "/");
|
|
}
|
|
|
|
/** Path used by Asterisk itself for MixMonitor/recording commands. */
|
|
public String getCallRecordRuntimePath() {
|
|
if (callRecordPathInNas != null && !callRecordPathInNas.isEmpty())
|
|
return getCallRecordPath();
|
|
if (asteriskDockerMode)
|
|
return "/var/spool/" + core + "/monitor/";
|
|
return getCallRecordPath();
|
|
}
|
|
|
|
public String getFaxDir() {
|
|
if (faxPathInNas != null && !faxPathInNas.isEmpty()) {
|
|
if (faxPathInNas.endsWith("/"))
|
|
return faxPathInNas + "fax_files";
|
|
return faxPathInNas + "/fax_files";
|
|
}
|
|
if (asteriskDockerMode)
|
|
return normalizeBasePath() + "/base/fax";
|
|
return GlobalTools.getBaseDir();
|
|
}
|
|
|
|
/** Path used by Asterisk itself for ReceiveFAX/SendFax commands. */
|
|
public String getFaxRuntimeDir() {
|
|
if (faxPathInNas != null && !faxPathInNas.isEmpty())
|
|
return getFaxDir();
|
|
if (asteriskDockerMode)
|
|
return "/var/spool/" + core + "/fax";
|
|
return getFaxDir();
|
|
}
|
|
|
|
public String getBackupPath() {
|
|
if (backupPathInNas != null && !backupPathInNas.isEmpty()) {
|
|
if (backupPathInNas.endsWith("/"))
|
|
return backupPathInNas + "backup/";
|
|
return backupPathInNas + "/backup/";
|
|
}
|
|
return GlobalTools.getBaseDir() + "/download/";
|
|
}
|
|
|
|
public boolean isBackupOnNas() {
|
|
return backupPathInNas != null && !backupPathInNas.isEmpty();
|
|
}
|
|
|
|
public String getCallRecordNasRoot() {
|
|
return storageRoot(callRecordPathInNas);
|
|
}
|
|
|
|
public String getFaxNasRoot() {
|
|
return storageRoot(faxPathInNas);
|
|
}
|
|
|
|
private String storageRoot(String path) {
|
|
if (path == null || path.trim().isEmpty())
|
|
return null;
|
|
String normalized = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
|
|
return normalized;
|
|
}
|
|
|
|
private void ConnectSocketToCore() {
|
|
if (amiPlineHost == null || amiPlineHost.trim().equals("0.0.0.0")) {
|
|
amiPlineHost = "127.0.0.1";
|
|
amiPlinePort = 2342;
|
|
amiPlineUsername = "pline";
|
|
amiPlinePassword = "UUEXFYgd87356386jHFDjgfsjs";
|
|
}
|
|
|
|
if (agiPlinePort == 0)
|
|
agiPlinePort = 6377;
|
|
|
|
ManagerConnectionFactory factory = new ManagerConnectionFactory(amiPlineHost, amiPlinePort,
|
|
amiPlineUsername, amiPlinePassword);
|
|
try {
|
|
managerConnection = factory.createManagerConnection();
|
|
managerConnection.setKeepAliveAfterAuthenticationFailure(true);
|
|
managerConnection.addEventListener(new Events());
|
|
managerConnection.login("all");
|
|
plineServer = new DefaultAsteriskServer(managerConnection);
|
|
// plineServer.addChainListener(x -> {
|
|
// //#####
|
|
// });
|
|
plineServer.initialize();
|
|
} catch (Exception ex) {
|
|
this.plineLogger(ex.getMessage());
|
|
}
|
|
}
|
|
|
|
/** Retry the AMI connection after an externally started Asterisk instance becomes ready. */
|
|
public synchronized void reconnectToCore() {
|
|
if (managerConnection == null || managerConnection.getState() == ManagerConnectionState.DISCONNECTED)
|
|
ConnectSocketToCore();
|
|
}
|
|
|
|
public PlineTools() {
|
|
|
|
this.allSipUsersContext = new ArrayList<>();
|
|
|
|
this.logger = LogManager.getLogger(PlineTools.class);
|
|
ConnectSocketToCore();
|
|
amiCommandPoolMaintenance.scheduleWithFixedDelay(
|
|
this::expireIdleAmiCommandConnections,
|
|
AMI_COMMAND_POOL_SWEEP_INTERVAL_SECONDS,
|
|
AMI_COMMAND_POOL_SWEEP_INTERVAL_SECONDS,
|
|
TimeUnit.SECONDS);
|
|
tmrTryConnect = new Timer();
|
|
tmrTryConnect.scheduleAtFixedRate(new TimerTask() {
|
|
@Override
|
|
public void run() {
|
|
if (managerConnection == null
|
|
|| managerConnection.getState() == ManagerConnectionState.DISCONNECTED) {
|
|
ConnectSocketToCore();
|
|
}
|
|
}
|
|
}, 10000, 10000);
|
|
|
|
menuTokens = new FixedSizeList();
|
|
|
|
TimerTask task = null;
|
|
try {
|
|
var network = Arrays.stream(getListOfNetwork())
|
|
.filter(x -> x.getLink_type() != null && x.getLink_type().equalsIgnoreCase("ether")).toList();
|
|
oldTxBytes = new long[network.size()];
|
|
oldRxBytes = new long[network.size()];
|
|
networkSpeeds = new NetworkSpeed[network.size()];
|
|
|
|
for (int i = 0; i < network.size(); i++) {
|
|
oldTxBytes[i] = 0;
|
|
oldRxBytes[i] = 0;
|
|
var n = new NetworkSpeed();
|
|
n.setIfName(network.get(i).getIfname());
|
|
n.setRx(0);
|
|
n.setTx(0);
|
|
networkSpeeds[i] = n;
|
|
}
|
|
task = new TimerTask() {
|
|
public void run() {
|
|
for (int i = 0; i < network.size(); i++) {
|
|
networkSpeeds[i] = networkSpeed(i, network.get(i).getIfname());
|
|
}
|
|
}
|
|
};
|
|
timerNetwork = new Timer();
|
|
timerNetwork.scheduleAtFixedRate(task, 1000L, 1000L);
|
|
} catch (Exception ex) {
|
|
networkSpeeds = new NetworkSpeed[]{};
|
|
plineLogger(ex.getMessage());
|
|
}
|
|
|
|
// watch dog foe monitor cdr to connect to cdr database
|
|
tmrCheckCdr = new Timer();
|
|
tmrCheckCdr.scheduleAtFixedRate(new TimerTask() {
|
|
@Override
|
|
public void run() {
|
|
String result = execCoreCommandStringResult("cdr show pgsql status");
|
|
if (result == null || result.contains("cdr show pgsql status' failed")) {
|
|
loadModuleInVoIPServer("cdr_pgsql.so");
|
|
}
|
|
}
|
|
}, 15 * 1000, 60 * 1000);
|
|
}
|
|
|
|
public String getConfigPath() {
|
|
String path;
|
|
if (asteriskDockerMode)
|
|
path = normalizeBasePath() + "/base/etc/" + this.core + "/";
|
|
else if (debug)
|
|
path = System.getProperty("user.home") + "/etc/" + this.core + "/";
|
|
else
|
|
path = "/etc/" + this.core + "/";
|
|
File file = new File(path);
|
|
if (!file.exists())
|
|
file.mkdirs();
|
|
return path;
|
|
}
|
|
|
|
public void plineLogger(String message) {
|
|
logger.info(message);
|
|
}
|
|
|
|
public void plineLogger(String message, Object... args) {
|
|
logger.info(message, args);
|
|
}
|
|
|
|
public void plineLogger(StackTraceElement[] message) {
|
|
for (StackTraceElement stackTraceElement : message) {
|
|
logger.info(stackTraceElement.toString());
|
|
}
|
|
}
|
|
|
|
public String execLinuxCli(String command, String[] parameters, boolean wantResult) {
|
|
StringBuilder cmd = new StringBuilder(command.trim());
|
|
for (String x : parameters) {
|
|
cmd.append(" ").append(x.trim());
|
|
}
|
|
|
|
try {
|
|
this.plineLogger("Exec: " + cmd);
|
|
Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd.toString()});
|
|
if (wantResult) {
|
|
BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
|
|
StringBuilder result = new StringBuilder();
|
|
String line = "";
|
|
while ((line = buf.readLine()) != null) {
|
|
result.append(line).append("\n");
|
|
}
|
|
buf.close();
|
|
return result.toString();
|
|
}
|
|
return "";
|
|
} catch (Exception ex) {
|
|
this.plineLogger(ex.getLocalizedMessage());
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public String execLinuxCliHA(String command, String[] parameters, boolean wantResult) {
|
|
try {
|
|
List<String> cmd = new ArrayList<>();
|
|
cmd.add("/bin/bash");
|
|
cmd.add(command);
|
|
if (parameters != null) {
|
|
cmd.addAll(Arrays.asList(parameters));
|
|
}
|
|
ProcessBuilder pb = new ProcessBuilder(cmd);
|
|
pb.redirectErrorStream(true);
|
|
Process p = pb.start();
|
|
StringBuilder result = new StringBuilder();
|
|
if (wantResult) {
|
|
try (BufferedReader reader = new BufferedReader(
|
|
new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
|
|
String line;
|
|
while ((line = reader.readLine()) != null) {
|
|
result.append(line).append("\n");
|
|
}
|
|
}
|
|
}
|
|
p.waitFor();
|
|
return result.toString();
|
|
} catch (Exception ex) {
|
|
this.plineLogger(ex.getLocalizedMessage());
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Execute CLI through AMI, using the local Asterisk CLI only when no AMI action was sent. */
|
|
public String execAsteriskCli(String command, boolean wantResult) {
|
|
List<String> result = executeAsteriskCommand(command);
|
|
if (result == null)
|
|
return null;
|
|
return wantResult ? String.join("\n", result) + (result.isEmpty() ? "" : "\n") : "";
|
|
}
|
|
|
|
private record IdleAmiCommandConnection(ManagerConnection connection, long returnedAtNanos) { }
|
|
|
|
private record AmiCommandAttempt(boolean actionSent, List<String> output) { }
|
|
|
|
private AmiCommandAttempt executeAmiCommand(String command, long timeoutMs) {
|
|
if (!amiCommandSlots.tryAcquire()) {
|
|
plineLogger("AMI command pool is busy; using local Asterisk CLI fallback");
|
|
return new AmiCommandAttempt(false, null);
|
|
}
|
|
|
|
ManagerConnection connection = null;
|
|
boolean actionSent = false;
|
|
boolean reusable = false;
|
|
try {
|
|
connection = borrowAmiCommandConnection();
|
|
if (connection == null)
|
|
return new AmiCommandAttempt(false, null);
|
|
|
|
if (connection.getState() != ManagerConnectionState.CONNECTED)
|
|
connection.login("off");
|
|
|
|
// Once sendAction starts, a timeout has an uncertain outcome. Never retry it
|
|
// through the CLI, since the first execution might already have completed.
|
|
actionSent = true;
|
|
var response = connection.sendAction(new CommandAction(command), timeoutMs);
|
|
reusable = connection.getState() == ManagerConnectionState.CONNECTED;
|
|
if (response instanceof CommandResponse commandResponse)
|
|
return new AmiCommandAttempt(true, commandResponse.getResult());
|
|
plineLogger("AMI returned an unexpected response for a CLI command");
|
|
return new AmiCommandAttempt(true, null);
|
|
} catch (Exception ex) {
|
|
plineLogger("AMI command error (fallback " + (actionSent ? "suppressed" : "allowed") + "): "
|
|
+ ex.getMessage());
|
|
return new AmiCommandAttempt(actionSent, null);
|
|
} finally {
|
|
if (connection != null) {
|
|
if (reusable && connection.getState() == ManagerConnectionState.CONNECTED
|
|
&& idleAmiCommandConnections.offer(
|
|
new IdleAmiCommandConnection(connection, System.nanoTime()))) {
|
|
// Keep healthy connections warm for the next command.
|
|
} else {
|
|
discardAmiCommandConnection(connection);
|
|
}
|
|
}
|
|
amiCommandSlots.release();
|
|
}
|
|
}
|
|
|
|
private ManagerConnection borrowAmiCommandConnection() {
|
|
IdleAmiCommandConnection idle;
|
|
while ((idle = idleAmiCommandConnections.poll()) != null) {
|
|
ManagerConnection connection = idle.connection();
|
|
if (isAmiCommandConnectionExpired(idle)
|
|
|| connection.getState() != ManagerConnectionState.CONNECTED) {
|
|
discardAmiCommandConnection(connection);
|
|
continue;
|
|
}
|
|
return connection;
|
|
}
|
|
|
|
synchronized (amiCommandPoolLock) {
|
|
if (amiCommandConnectionsCreated.get() >= DEFAULT_AMI_COMMAND_CONNECTIONS)
|
|
return null;
|
|
amiCommandConnectionsCreated.incrementAndGet();
|
|
}
|
|
|
|
ManagerConnection connection = null;
|
|
try {
|
|
ManagerConnectionFactory factory = new ManagerConnectionFactory(amiPlineHost, amiPlinePort,
|
|
amiPlineUsername, amiPlinePassword);
|
|
connection = factory.createManagerConnection();
|
|
connection.setKeepAliveAfterAuthenticationFailure(true);
|
|
connection.login("off");
|
|
return connection;
|
|
} catch (Exception ex) {
|
|
if (connection != null) {
|
|
try {
|
|
connection.logoff();
|
|
} catch (Exception ignored) {
|
|
// Best effort cleanup after an unsuccessful AMI login.
|
|
}
|
|
}
|
|
amiCommandConnectionsCreated.decrementAndGet();
|
|
plineLogger("Could not open pooled AMI command connection: " + ex.getMessage());
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private boolean isAmiCommandConnectionExpired(IdleAmiCommandConnection idle) {
|
|
long idleTimeoutMs = Math.max(1, amiCommandIdleTimeoutMs);
|
|
long idleNanos = System.nanoTime() - idle.returnedAtNanos();
|
|
return idleNanos >= TimeUnit.MILLISECONDS.toNanos(idleTimeoutMs);
|
|
}
|
|
|
|
private void expireIdleAmiCommandConnections() {
|
|
try {
|
|
List<IdleAmiCommandConnection> keep = new ArrayList<>();
|
|
IdleAmiCommandConnection idle;
|
|
while ((idle = idleAmiCommandConnections.poll()) != null) {
|
|
if (isAmiCommandConnectionExpired(idle))
|
|
discardAmiCommandConnection(idle.connection());
|
|
else
|
|
keep.add(idle);
|
|
}
|
|
for (IdleAmiCommandConnection connection : keep) {
|
|
if (!idleAmiCommandConnections.offer(connection))
|
|
discardAmiCommandConnection(connection.connection());
|
|
}
|
|
} catch (Exception ex) {
|
|
plineLogger("AMI command pool idle cleanup failed: " + ex.getMessage());
|
|
}
|
|
}
|
|
|
|
private void discardAmiCommandConnection(ManagerConnection connection) {
|
|
try {
|
|
if (connection.getState() == ManagerConnectionState.CONNECTED)
|
|
connection.logoff();
|
|
} catch (Exception ignored) {
|
|
// The connection is already unusable; dropping it is the intended cleanup.
|
|
} finally {
|
|
amiCommandConnectionsCreated.updateAndGet(count -> Math.max(0, count - 1));
|
|
}
|
|
}
|
|
|
|
@PreDestroy
|
|
public void closeAmiCommandConnections() {
|
|
amiCommandPoolMaintenance.shutdownNow();
|
|
IdleAmiCommandConnection idle;
|
|
while ((idle = idleAmiCommandConnections.poll()) != null)
|
|
discardAmiCommandConnection(idle.connection());
|
|
}
|
|
|
|
public record AsteriskCliExecution(List<String> output, String transport) { }
|
|
|
|
public AsteriskCliExecution executeAsteriskCliCommand(String command) {
|
|
return executeAsteriskCliCommand(command, AMI_COMMAND_TIMEOUT_MS, ASTERISK_CLI_TIMEOUT_SECONDS);
|
|
}
|
|
|
|
private AsteriskCliExecution executeAsteriskCliCommand(String command, long amiTimeoutMs,
|
|
long cliTimeoutSeconds) {
|
|
if (command == null || command.isBlank() || command.length() > 4096
|
|
|| command.indexOf('\n') >= 0 || command.indexOf('\r') >= 0 || command.indexOf('\0') >= 0) {
|
|
plineLogger("Rejected invalid Asterisk CLI command input");
|
|
return new AsteriskCliExecution(null, "NONE");
|
|
}
|
|
AmiCommandAttempt amiAttempt = executeAmiCommand(command, amiTimeoutMs);
|
|
if (amiAttempt.actionSent()) {
|
|
if (amiAttempt.output() == null)
|
|
plineLogger("AMI command was sent but its result is unknown");
|
|
else
|
|
plineLogger("Asterisk CLI command completed through AMI");
|
|
return new AsteriskCliExecution(amiAttempt.output(), "AMI");
|
|
}
|
|
|
|
String cliOutput = executeAsteriskCliFallback(command, cliTimeoutSeconds);
|
|
if (cliOutput == null)
|
|
return new AsteriskCliExecution(null, "CLI");
|
|
List<String> lines = cliOutput.isEmpty() ? List.of() : cliOutput.lines().toList();
|
|
plineLogger("Asterisk CLI command completed through local CLI fallback");
|
|
return new AsteriskCliExecution(lines, "CLI");
|
|
}
|
|
|
|
private List<String> executeAsteriskCommand(String command) {
|
|
return executeAsteriskCliCommand(command).output();
|
|
}
|
|
|
|
private String executeAsteriskCliFallback(String command, long timeoutSeconds) {
|
|
if (!localCliFallbackSlots.tryAcquire()) {
|
|
plineLogger("Local Asterisk CLI fallback is busy; rejecting this execution without queueing");
|
|
return null;
|
|
}
|
|
Path outputFile = null;
|
|
Process process = null;
|
|
try {
|
|
List<String> cmd = new ArrayList<>();
|
|
if (asteriskDockerMode) {
|
|
cmd.add("docker");
|
|
cmd.add("exec");
|
|
cmd.add(asteriskContainerName);
|
|
}
|
|
cmd.add("/usr/sbin/" + core);
|
|
cmd.add("-x");
|
|
cmd.add(command);
|
|
outputFile = Files.createTempFile("pline-asterisk-cli-", ".out");
|
|
this.plineLogger("Starting local Asterisk CLI fallback");
|
|
ProcessBuilder pb = new ProcessBuilder(cmd).redirectErrorStream(true)
|
|
.redirectOutput(outputFile.toFile());
|
|
process = pb.start();
|
|
if (!process.waitFor(timeoutSeconds, TimeUnit.SECONDS)) {
|
|
process.destroyForcibly();
|
|
process.waitFor();
|
|
plineLogger("Asterisk CLI fallback timed out after " + timeoutSeconds + " seconds");
|
|
return null;
|
|
}
|
|
if (process.exitValue() != 0) {
|
|
plineLogger("Asterisk CLI fallback exited with status " + process.exitValue());
|
|
return null;
|
|
}
|
|
return Files.readString(outputFile, StandardCharsets.UTF_8);
|
|
} catch (Exception ex) {
|
|
if (process != null)
|
|
process.destroyForcibly();
|
|
this.plineLogger("Asterisk CLI fallback error: " + ex.getLocalizedMessage());
|
|
return null;
|
|
} finally {
|
|
if (outputFile != null) {
|
|
try {
|
|
Files.deleteIfExists(outputFile);
|
|
} catch (IOException ignored) {
|
|
// Temporary output is best-effort cleanup.
|
|
}
|
|
}
|
|
localCliFallbackSlots.release();
|
|
}
|
|
}
|
|
|
|
public boolean isAsteriskDockerMode() {
|
|
return asteriskDockerMode;
|
|
}
|
|
|
|
public String getAsteriskContainerName() {
|
|
return asteriskContainerName;
|
|
}
|
|
|
|
private String normalizeBasePath() {
|
|
if (asteriskBasePath == null || asteriskBasePath.trim().isEmpty())
|
|
return "/opt/cti";
|
|
String path = asteriskBasePath.trim();
|
|
return path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
|
|
}
|
|
|
|
/** Convert an Asterisk container path to its host-mounted path when Docker is enabled. */
|
|
private String getAsteriskHostPath(String path) {
|
|
if (!asteriskDockerMode || path == null)
|
|
return path;
|
|
String normalized = path.startsWith("/") ? path : "/" + path;
|
|
// Only translate paths belonging to the Asterisk filesystem mounts.
|
|
// NAS/custom application paths must remain untouched.
|
|
if (!(normalized.startsWith("/etc/")
|
|
|| normalized.startsWith("/var/lib/")
|
|
|| normalized.startsWith("/var/log/")
|
|
|| normalized.startsWith("/var/spool/")))
|
|
return path;
|
|
return normalizeBasePath() + "/base" + normalized;
|
|
}
|
|
|
|
public List<String> execCoreCommand(String command) {
|
|
return executeAsteriskCommand(command);
|
|
}
|
|
|
|
public void loadModuleInVoIPServer(String module) {
|
|
execCoreCommand("module load " + module);
|
|
}
|
|
|
|
public void reloadModuleInVoIPServer(String module) {
|
|
execCoreCommand("module reload " + module);
|
|
}
|
|
|
|
public String execCoreCommandStringResult(String command) {
|
|
List<String> result = executeAsteriskCommand(command);
|
|
return result == null ? null : String.join("\n", result) + (result.isEmpty() ? "" : "\n");
|
|
}
|
|
|
|
public boolean reloadConfigurations() {
|
|
// Apply rewrites Asterisk configuration only. Recursively changing the
|
|
// owner of the spool/lib trees walks recordings and voicemail data and
|
|
// can make a routine Apply take minutes on a live PBX.
|
|
execLinuxCli("/usr/bin/chown", new String[]{
|
|
this.ownerGroupFolders,
|
|
"-R",
|
|
this.getConfigPath()
|
|
}, true);
|
|
|
|
// The global module reload below also applies manager.conf changes,
|
|
// including allowmultiplelogin, during in-place upgrades.
|
|
// A full module reload also reloads the manager module. Send one reload
|
|
// request, allow it longer than ordinary CLI commands, and surface an
|
|
// in-progress reload instead of reporting Apply as successful.
|
|
AsteriskCliExecution execution = executeAsteriskCliCommand("module reload", AMI_RELOAD_TIMEOUT_MS,
|
|
ASTERISK_RELOAD_CLI_TIMEOUT_SECONDS);
|
|
if (execution.output() == null) {
|
|
plineLogger("Asterisk reload did not return a result; it may still be running. Check Asterisk logs.");
|
|
return false;
|
|
}
|
|
String output = String.join("\n", execution.output());
|
|
if (output.toLowerCase(Locale.ROOT).contains("the previous reload command didn't finish yet")) {
|
|
plineLogger("Asterisk rejected the reload because a previous reload is still running.");
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public boolean checkSipUid(String uid) {
|
|
var pattern = "/^[a-zA-Z0-9_.-]*$/";
|
|
return uid.matches(pattern);
|
|
}
|
|
|
|
public void deleteAllFileInFolder(String path) {
|
|
try {
|
|
File folder = new File(path);
|
|
File[] listOfFiles = folder.listFiles();
|
|
|
|
assert listOfFiles != null;
|
|
for (File listOfFile : listOfFiles) {
|
|
if (listOfFile.isFile()) {
|
|
listOfFile.delete();
|
|
}
|
|
}
|
|
} catch (Exception ex) {
|
|
this.plineLogger("Error Delete file in folder: " + path);
|
|
}
|
|
}
|
|
|
|
public boolean writeInfoFile(String folder, String filename, InfoConfiguration iniConfiguration) {
|
|
|
|
List<InfoConfiguration> list = new ArrayList<>();
|
|
list.add(iniConfiguration);
|
|
return writeInfoFile(folder, filename, list, false);
|
|
}
|
|
|
|
public boolean writeInfoFile(String folder, String filename, InfoConfiguration iniConfiguration, boolean append) {
|
|
|
|
List<InfoConfiguration> list = new ArrayList<>();
|
|
list.add(iniConfiguration);
|
|
return writeInfoFile(folder, filename, list, append);
|
|
}
|
|
|
|
public boolean writeInfoFile(String folder, String filename, List<InfoConfiguration> iniConfigurations) {
|
|
return writeInfoFile(folder, filename, iniConfigurations, false);
|
|
}
|
|
|
|
public boolean writeInfoFile(String folder, String filename, List<InfoConfiguration> iniConfigurations,
|
|
boolean append) {
|
|
try {
|
|
this.plineLogger("Start write info file: " + filename);
|
|
if (!filename.endsWith(".conf")) {
|
|
filename += ".conf";
|
|
}
|
|
|
|
if (!folder.endsWith("/")) {
|
|
folder = folder + "/";
|
|
}
|
|
String path = this.getConfigPath() + folder;
|
|
|
|
if (!new File(path).exists()) {
|
|
var r = new File(path).mkdirs();
|
|
System.out.println(r);
|
|
}
|
|
|
|
File infoFile = new File(path + filename);
|
|
if (!append && infoFile.exists()) {
|
|
infoFile.delete();
|
|
this.plineLogger("Delete info file: " + filename);
|
|
}
|
|
|
|
if (infoFile.createNewFile()) {
|
|
this.plineLogger("Create info file: " + filename);
|
|
}
|
|
|
|
StringBuilder oldText = new StringBuilder();
|
|
if (append) {
|
|
List<String> allLines = Files.readAllLines(Paths.get(path + filename));
|
|
for (String str : allLines) {
|
|
oldText.append(str).append("\n");
|
|
}
|
|
}
|
|
|
|
PrintWriter fileWriter = new PrintWriter(infoFile);
|
|
|
|
if (append) {
|
|
fileWriter.print(oldText);
|
|
}
|
|
|
|
boolean bannerSetInFirst = false;
|
|
for (InfoConfiguration ic : iniConfigurations) {
|
|
|
|
if (ic.isBanner() && !bannerSetInFirst) {
|
|
fileWriter.println(this.getBanner());
|
|
bannerSetInFirst = true;
|
|
}
|
|
if (!ic.getDescription().isEmpty()) {
|
|
String[] descs = ic.getDescription().split("\n");
|
|
fileWriter.println();
|
|
for (String desc : descs) {
|
|
fileWriter.println(";" + desc);
|
|
}
|
|
fileWriter.println();
|
|
}
|
|
|
|
// if context empty only write banner and description
|
|
if (ic.getContext() != null) {
|
|
if (!ic.getTemplate().isEmpty())
|
|
if (ic.getTemplates().size() == 1) {
|
|
fileWriter.println("[" + ic.getContext() + "](" + ic.getTemplate() + ")");
|
|
} else {
|
|
StringBuilder temp = new StringBuilder();
|
|
for (String t : ic.getTemplates()) {
|
|
temp.append(t).append(",");
|
|
}
|
|
if (!temp.isEmpty()) {
|
|
temp = new StringBuilder(temp.substring(0, temp.length() - 1));
|
|
}
|
|
fileWriter.println("[" + ic.getContext() + "](" + temp + ")");
|
|
}
|
|
else
|
|
fileWriter.println("[" + ic.getContext() + "]");
|
|
}
|
|
|
|
ic.getElements().forEach((e) -> {
|
|
if (e.getKey().equals("include")) {
|
|
fileWriter.println("include => " + e.getValue());
|
|
} else {
|
|
fileWriter.println(e.getKey() + " " + e.getAssignMark() + " " + e.getValue());
|
|
}
|
|
});
|
|
|
|
fileWriter.println();
|
|
}
|
|
fileWriter.flush();
|
|
fileWriter.close();
|
|
this.plineLogger("Create info file successful: " + filename);
|
|
return true;
|
|
} catch (Exception ex) {
|
|
this.plineLogger("Error in write info file: " + ex.getMessage());
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public void IncludeConfigFile(String folder, String filename, String include) {
|
|
List<String> lst = new ArrayList<>();
|
|
lst.add(include);
|
|
IncludeConfigFile(folder, filename, lst);
|
|
}
|
|
|
|
public void IncludeConfigFile(String folder, String filename, List<String> includes) {
|
|
try {
|
|
if (!filename.endsWith(".conf")) {
|
|
filename += ".conf";
|
|
}
|
|
this.plineLogger("Start write info file: " + filename);
|
|
|
|
if (!folder.endsWith("/")) {
|
|
folder = folder + "/";
|
|
}
|
|
String path = this.getConfigPath() + folder;
|
|
|
|
if (!new File(path).exists()) {
|
|
new File(path).mkdirs();
|
|
}
|
|
|
|
File infoFile = new File(path + filename);
|
|
if (!infoFile.exists() && infoFile.createNewFile()) {
|
|
this.plineLogger("Create info file: " + filename);
|
|
}
|
|
|
|
includes.forEach(x -> {
|
|
try {
|
|
Files.write(Paths.get(infoFile.getPath()), ("#include \"" + x.trim() + "\"\n").getBytes(),
|
|
StandardOpenOption.APPEND);
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
});
|
|
Files.write(Paths.get(infoFile.getPath()), "\n".getBytes(), StandardOpenOption.APPEND);
|
|
} catch (Exception ignored) {
|
|
}
|
|
|
|
}
|
|
|
|
public boolean writeDialPlanFile(String folder, String filename, DialPlanConfiguration dialPlanConfiguration) {
|
|
List<DialPlanConfiguration> dialPlanConfigurations = new ArrayList<>();
|
|
dialPlanConfigurations.add(dialPlanConfiguration);
|
|
return writeDialPlanFile(folder, filename, dialPlanConfigurations);
|
|
}
|
|
|
|
public boolean writeDialPlanFile(String folder, String filename,
|
|
List<DialPlanConfiguration> dialPlanConfigurations) {
|
|
try {
|
|
dialPlanConfigurations.forEach(dc -> {
|
|
dc.getDialPlanExtensions().forEach(ext -> {
|
|
if (ext.getFunctions().size() >= 2) {
|
|
var last = ext.getFunctions().get(ext.getFunctions().size() - 1);
|
|
var before = ext.getFunctions().get(ext.getFunctions().size() - 2);
|
|
if (last.equals(before) || last.toString().equalsIgnoreCase(before.toString())) {
|
|
ext.getFunctions().remove(ext.getFunctions().size() - 1);
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
this.plineLogger("Start write info file: " + filename);
|
|
if (!filename.endsWith(".conf")) {
|
|
filename += ".conf";
|
|
}
|
|
|
|
if (!folder.endsWith("/")) {
|
|
folder = folder + "/";
|
|
}
|
|
|
|
String path = this.getConfigPath() + folder;
|
|
|
|
if (!new File(path).exists()) {
|
|
var r = new File(path).mkdirs();
|
|
System.out.println(r);
|
|
}
|
|
|
|
File dialPlanFile = new File(path + filename);
|
|
if (dialPlanFile.exists()) {
|
|
dialPlanFile.delete();
|
|
this.plineLogger("Delete info file: " + filename);
|
|
}
|
|
|
|
if (dialPlanFile.createNewFile()) {
|
|
this.plineLogger("Create info file: " + filename);
|
|
}
|
|
|
|
PrintWriter fileWriter = new PrintWriter(dialPlanFile);
|
|
|
|
boolean bannerSetInFirst = false;
|
|
for (DialPlanConfiguration dpc : dialPlanConfigurations) {
|
|
|
|
if (dpc.isBanner() && !bannerSetInFirst) {
|
|
fileWriter.println(this.getBanner());
|
|
bannerSetInFirst = true;
|
|
}
|
|
if (!dpc.getDescription().isEmpty()) {
|
|
String[] descs = dpc.getDescription().split("\n");
|
|
fileWriter.println();
|
|
for (String desc : descs) {
|
|
fileWriter.println(";" + desc);
|
|
}
|
|
// fileWriter.println();
|
|
}
|
|
// if (dpc.getDescription() != null && !dpc.getDescription().isEmpty()) {
|
|
// String[] desc = dpc.getDescription().split("\n");
|
|
// for (var d : desc) {
|
|
// fileWriter.println("; " + d);
|
|
// }
|
|
// }
|
|
fileWriter.println("[" + dpc.getContext() + "]");
|
|
// fileWriter.println();
|
|
|
|
dpc.getDialPlanExtensions().forEach(func -> {
|
|
String exten = func.getExten();
|
|
if (!func.isForceExten()
|
|
&& (exten.toLowerCase().startsWith("x") ||
|
|
exten.toLowerCase().startsWith("z") ||
|
|
exten.toLowerCase().startsWith("n") ||
|
|
exten.toLowerCase().startsWith("[") ||
|
|
exten.toLowerCase().startsWith("*") ||
|
|
exten.toLowerCase().startsWith("#") ||
|
|
exten.toLowerCase().startsWith("!") ||
|
|
exten.toLowerCase().startsWith("+") ||
|
|
exten.toLowerCase().startsWith("0") ||
|
|
exten.toLowerCase().startsWith("1") ||
|
|
exten.toLowerCase().startsWith("2") ||
|
|
exten.toLowerCase().startsWith("3") ||
|
|
exten.toLowerCase().startsWith("4") ||
|
|
exten.toLowerCase().startsWith("5") ||
|
|
exten.toLowerCase().startsWith("6") ||
|
|
exten.toLowerCase().startsWith("7") ||
|
|
exten.toLowerCase().startsWith("8") ||
|
|
exten.toLowerCase().startsWith("9"))) {
|
|
exten = "_" + exten;
|
|
}
|
|
if (func.getFirstLine() == null) {
|
|
if (func.getDescription() != null && !func.getDescription().trim().isEmpty()) {
|
|
fileWriter.println("; " + func.getDescription());
|
|
}
|
|
fileWriter.println("exten => " + exten + ",1,NoOp(Match Pattern ${EXTEN})");
|
|
} else {
|
|
if (func.getDescription() != null && !func.getDescription().trim().isEmpty()) {
|
|
fileWriter.println("; " + func.getDescription());
|
|
}
|
|
String priority = func.getFirstLine().isForceTag() ? func.getFirstLine().getTag() : "1";
|
|
fileWriter.println(
|
|
"exten => " + exten + "," + priority + "," + func.getFirstLine().getFunction());
|
|
}
|
|
func.getFunctions().forEach(f -> {
|
|
String priority;
|
|
if (f.isForceTag())
|
|
priority = f.getTag();
|
|
else
|
|
priority = (f.getTag() == null ? "n," : "n(" + f.getTag() + "),");
|
|
fileWriter.println("\tsame => " + priority + f.getFunction());
|
|
});
|
|
fileWriter.println();
|
|
});
|
|
fileWriter.println();
|
|
}
|
|
fileWriter.flush();
|
|
fileWriter.close();
|
|
this.plineLogger("Create Dial Plan file successful: " + filename);
|
|
return true;
|
|
} catch (Exception ex) {
|
|
this.plineLogger("Error in write Dial Plan file: " + ex.getMessage());
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public String CreateWebRtcCert() {
|
|
this.deleteAllFileInFolder(this.getConfigPath() + "keys/");
|
|
String result = this.execLinuxCli("./tools/pline_tls_cert", new String[]{
|
|
"-C cti.raymandcti.com",
|
|
"-O \"Raymand\"",
|
|
"-d " + this.getConfigPath() + "keys",
|
|
// "-f " + this.getConfigPath() + "keys/",
|
|
"-o p-line"},
|
|
true);
|
|
this.execLinuxCli("/usr/bin/rm", new String[]{this.getConfigPath() + "keys/ca*"}, true);
|
|
this.execLinuxCli("/usr/bin/rm", new String[]{this.getConfigPath() + "keys/tmp*"}, true);
|
|
return result;
|
|
}
|
|
|
|
public String getLibPath() {
|
|
return getAsteriskHostPath("/var/lib/" + this.core + "/");
|
|
}
|
|
|
|
public String getSpoolPath() {
|
|
return getAsteriskHostPath("/var/spool/" + this.core);
|
|
}
|
|
|
|
public String getSoundsPath() {
|
|
// return "/var/lib/" + this.core + "/sounds";
|
|
File f = new File(GlobalTools.getBaseDir() + "/voices-box/sounds/");
|
|
if (!f.exists())
|
|
f.mkdirs();
|
|
return GlobalTools.getBaseDir() + "/voices-box/sounds";
|
|
}
|
|
|
|
public String getDefaultMusicOnHoldPath() {
|
|
return getAsteriskHostPath("/var/lib/" + this.core + "/moh");
|
|
}
|
|
|
|
public String getMusicOnHoldPath() {
|
|
File f = new File(GlobalTools.getBaseDir() + "/voices-box/music-on-holds/");
|
|
if (!f.exists())
|
|
f.mkdirs();
|
|
return GlobalTools.getBaseDir() + "/voices-box/music-on-holds";
|
|
}
|
|
|
|
public NetworkInterfaceIpAddressInfo[] getListOfNetworkIpAddress() {
|
|
try {
|
|
var json = this.execLinuxCli("/usr/bin/ip", new String[]{"-j", "address show"}, true);
|
|
ObjectMapper objectMapper = new ObjectMapper();
|
|
return objectMapper.readValue(json,
|
|
NetworkInterfaceIpAddressInfo[].class);
|
|
} catch (Exception ex) {
|
|
try {
|
|
plineLogger(ex.getStackTrace());
|
|
String tmp = """
|
|
[
|
|
{
|
|
"ifindex": 1,
|
|
"ifname": "lo",
|
|
"flags": [
|
|
"LOOPBACK",
|
|
"UP",
|
|
"LOWER_UP"
|
|
],
|
|
"mtu": 65536,
|
|
"qdisc": "noqueue",
|
|
"operstate": "UNKNOWN",
|
|
"group": "default",
|
|
"txqlen": 1000,
|
|
"link_type": "loopback",
|
|
"address": "00:00:00:00:00:00",
|
|
"broadcast": "00:00:00:00:00:00",
|
|
"addr_info": [
|
|
{
|
|
"family": "inet",
|
|
"local": "127.0.0.1",
|
|
"prefixlen": 8,
|
|
"scope": "host",
|
|
"label": "lo",
|
|
"valid_life_time": 4294967295,
|
|
"preferred_life_time": 4294967295
|
|
},
|
|
{
|
|
"family": "inet6",
|
|
"local": "::1",
|
|
"prefixlen": 128,
|
|
"scope": "host",
|
|
"valid_life_time": 4294967295,
|
|
"preferred_life_time": 4294967295
|
|
}
|
|
]
|
|
}
|
|
]
|
|
""";
|
|
ObjectMapper objectMapper = new ObjectMapper();
|
|
return objectMapper.readValue(tmp,
|
|
NetworkInterfaceIpAddressInfo[].class);
|
|
} catch (Exception ignored) {
|
|
return new NetworkInterfaceIpAddressInfo[]{};
|
|
}
|
|
}
|
|
}
|
|
|
|
public NetworkInterfacePhyInfo[] getListOfNetwork() {
|
|
try {
|
|
var json = this.execLinuxCli("/usr/bin/ip", new String[]{"-j", "link show"}, true);
|
|
ObjectMapper objectMapper = new ObjectMapper();
|
|
return objectMapper.readValue(json, NetworkInterfacePhyInfo[].class);
|
|
} catch (Exception ex) {
|
|
plineLogger(ex.getMessage());
|
|
return new NetworkInterfacePhyInfo[]{};
|
|
}
|
|
}
|
|
|
|
public RouteInfo[] getListOfNetworkRoutes() {
|
|
try {
|
|
var json = this.execLinuxCli("/usr/bin/ip", new String[]{"-j", "route show"}, true);
|
|
ObjectMapper objectMapper = new ObjectMapper();
|
|
return objectMapper.readValue(json, RouteInfo[].class);
|
|
} catch (Exception ex) {
|
|
plineLogger(ex.getMessage());
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private long[] oldTxBytes;
|
|
private long[] oldRxBytes;
|
|
@Getter
|
|
NetworkSpeed[] networkSpeeds;
|
|
Timer timerNetwork;
|
|
|
|
private NetworkSpeed networkSpeed(int index, String ifName) {
|
|
NetworkSpeed speed = new NetworkSpeed();
|
|
speed.setIfName(ifName);
|
|
try {
|
|
Process process = Runtime.getRuntime()
|
|
.exec(new String[]{"/bin/sh", "-c",
|
|
"/usr/bin/cat /sys/class/net/" + ifName + "/statistics/rx_bytes"});
|
|
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
|
String line = reader.readLine();
|
|
if (line != null) {
|
|
long rxBytes = Long.parseLong(line);
|
|
long out = rxBytes - oldRxBytes[index];
|
|
oldRxBytes[index] = rxBytes;
|
|
speed.setRx(((int) out) * 8);
|
|
}
|
|
reader.close();
|
|
|
|
process = Runtime.getRuntime().exec(
|
|
new String[]{"/bin/sh", "-c", "/usr/bin/cat /sys/class/net/" + ifName + "/statistics/tx_bytes"});
|
|
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
|
line = reader.readLine();
|
|
if (line != null) {
|
|
long txBytes = Long.parseLong(line);
|
|
long out = txBytes - oldTxBytes[index];
|
|
oldTxBytes[index] = txBytes;
|
|
speed.setTx(((int) out) * 8);
|
|
}
|
|
reader.close();
|
|
} catch (IOException e) {
|
|
this.plineLogger(e.getMessage());
|
|
}
|
|
return speed;
|
|
}
|
|
|
|
public String ariCryptoPassCalc(String plainPass) throws Exception {
|
|
List<String> r = this.execCoreCommand("ari mkpasswd " + plainPass);
|
|
if (r == null || r.isEmpty())
|
|
throw new Exception("There was an error in calculating SHA-512. Please try again");
|
|
var data = r.stream().filter(line -> line.trim().startsWith("password =")).findFirst();
|
|
if (data.isPresent()) {
|
|
return data.get().substring("password =".length());
|
|
} else {
|
|
throw new Exception("There was an error in calculating SHA-512. Please try again");
|
|
}
|
|
}
|
|
|
|
public void removeOldRecordFiles() {
|
|
try {
|
|
String script = """
|
|
#!/bin/bash
|
|
|
|
TARGET_DIR="$1"
|
|
MAX_USED="$2"
|
|
LOG_DIR="$3/log"
|
|
LOG_FILE="$LOG_DIR/deleted_audio_files.log"
|
|
|
|
mkdir -p "$LOG_DIR"
|
|
|
|
# Log Rotation
|
|
if [ -f "$LOG_FILE" ]; then
|
|
if [ $(stat -c%s "$LOG_FILE" 2>/dev/null || echo 0) -ge $((100*1024*1024)) ]; then
|
|
timestamp=$(date '+%Y%m%d_%H%M%S')
|
|
mv "$LOG_FILE" "${LOG_FILE%.log}_$timestamp.log"
|
|
find "$LOG_DIR" -name "deleted_audio_files_*.log" -type f | sort | head -n -30 | xargs -r rm -f
|
|
fi
|
|
fi
|
|
|
|
get_used_space_percent() {
|
|
df -P "$TARGET_DIR" | awk 'NR==2 {gsub("%","",$5); print $5}'
|
|
}
|
|
|
|
find_oldest_audio_file() {
|
|
find "$TARGET_DIR" -type f \\
|
|
\\( -iname "*.mp3" -o -iname "*.wav" -o -iname "*.gsm" -o -iname "*.ogg" -o -iname "*.alaw" -o -iname "*.ulaw" -o -iname "*.sln" \\) \\
|
|
-printf "%T@ %p\\n" 2>/dev/null | sort -n | head -n 1 | cut -d' ' -f2-
|
|
}
|
|
|
|
delete_empty_dirs() {
|
|
find "$TARGET_DIR" -type d -regex '.*/[0-9]\\{4\\}/[0-9]\\{2\\}/[0-9]\\{2\\}$' -empty -delete 2>/dev/null
|
|
}
|
|
|
|
echo "==== Audio Cleanup Started at $(date) ====" >> "$LOG_FILE"
|
|
|
|
loop_count=0
|
|
deleted_count=0
|
|
while true; do
|
|
used_space=$(get_used_space_percent)
|
|
echo "Current disk usage: $used_space% (Deleted: $deleted_count files)"
|
|
|
|
if [ "$used_space" -le "$MAX_USED" ]; then
|
|
echo "Disk usage is under $MAX_USED%. Cleanup finished."
|
|
echo "Cleanup completed at $(date). Disk usage: $used_space%. Total deleted: $deleted_count files." >> "$LOG_FILE"
|
|
break
|
|
fi
|
|
|
|
oldest_file=$(find_oldest_audio_file)
|
|
if [ -z "$oldest_file" ]; then
|
|
echo "No more audio files found to delete."
|
|
echo "No audio files left at $(date). Total deleted: $deleted_count files." >> "$LOG_FILE"
|
|
break
|
|
fi
|
|
|
|
echo "$(date '+%Y-%m-%d %H:%M:%S') - Deleting: $oldest_file" >> "$LOG_FILE"
|
|
rm -f "$oldest_file"
|
|
((deleted_count++))
|
|
|
|
if [ $((deleted_count % 10)) -eq 0 ]; then
|
|
delete_empty_dirs
|
|
fi
|
|
|
|
((loop_count++))
|
|
[ "$loop_count" -ge 1000 ] && {
|
|
echo "Reached maximum loop count (1000). Stopping."
|
|
echo "Stopped after maximum loop count at $(date)." >> "$LOG_FILE"
|
|
break
|
|
}
|
|
sleep 0.1
|
|
done
|
|
|
|
delete_empty_dirs
|
|
|
|
echo "==== Audio Cleanup Ended at $(date) ====" >> "$LOG_FILE"
|
|
echo "Total files deleted: $deleted_count"
|
|
""";
|
|
PrintWriter printWriter = new PrintWriter(GlobalTools.getBaseDir() + "/tools/auto_remove_files.sh");
|
|
printWriter.print(script);
|
|
printWriter.flush();
|
|
printWriter.close();
|
|
|
|
this.execLinuxCli("", new String[]{
|
|
"+x",
|
|
GlobalTools.getBaseDir() + "/tools/auto_remove_files.sh",
|
|
}, true);
|
|
|
|
String max = this.getDeleteOldFilesAfterPercentUserValue();
|
|
if (max == null || max.equals("0"))
|
|
return;
|
|
this.execLinuxCli(GlobalTools.getBaseDir() + "/tools/auto_remove_files.sh", new String[]{
|
|
this.getCallRecordPath(),
|
|
max,
|
|
GlobalTools.getBaseDir(),
|
|
}, true);
|
|
} catch (Exception ex) {
|
|
this.plineLogger("Auto Remove: Error: " + ex.getMessage());
|
|
}
|
|
}
|
|
|
|
public String getQueueLogPath() {
|
|
return "/var/log/" + getCore();
|
|
}
|
|
|
|
public String getDialParameterString(String exten) {
|
|
if (!appSettingsService.getAppSettings().isDialContacts())
|
|
return "PJSIP/" + exten;
|
|
|
|
var items = exten.replace("PJSIP/", "").split("[&|]");
|
|
StringBuilder result = new StringBuilder();
|
|
for (var item : items) {
|
|
result.append("${PJSIP_DIAL_CONTACTS(").append(item).append(")}&");
|
|
}
|
|
if (!result.isEmpty()) {
|
|
result = new StringBuilder(result.substring(0, result.length() - 1));
|
|
}
|
|
return result.toString();
|
|
}
|
|
|
|
public void writeFileAtomically(String path, String content) throws java.io.IOException {
|
|
java.nio.file.Path target = java.nio.file.Paths.get(path);
|
|
java.nio.file.Path tmp = java.nio.file.Paths.get(path + ".tmp-" + System.nanoTime());
|
|
java.nio.file.Files.writeString(tmp, content, java.nio.charset.StandardCharsets.UTF_8,
|
|
java.nio.file.StandardOpenOption.CREATE,
|
|
java.nio.file.StandardOpenOption.TRUNCATE_EXISTING);
|
|
java.nio.file.Files.move(tmp, target,
|
|
java.nio.file.StandardCopyOption.REPLACE_EXISTING,
|
|
java.nio.file.StandardCopyOption.ATOMIC_MOVE);
|
|
}
|
|
|
|
}
|