Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 38 additions & 6 deletions .github/workflows/portainer-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,9 @@ jobs:
if not all([url, username, password, stack_id]):
sys.exit("Portainer secrets are not configured")

base = url.rstrip("/")
auth_request = request.Request(
f"{url.rstrip('/')}/api/auth",
f"{base}/api/auth",
data=json.dumps({"Username": username, "Password": password}).encode(),
headers={"Content-Type": "application/json"},
)
Expand All @@ -110,11 +111,42 @@ jobs:
if not token:
sys.exit("Failed to obtain Portainer JWT token")

headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}

# Get stack details (includes EndpointId)
inspect_request = request.Request(f"{base}/api/stacks/{stack_id}", headers=headers)
try:
with request.urlopen(inspect_request) as resp:
stack = json.loads(resp.read().decode())
except error.HTTPError as exc:
exit_with_http_details(exc)
endpoint_id = stack.get("EndpointId")
if endpoint_id is None:
sys.exit("Stack response missing EndpointId")

# Get current stack file content
file_request = request.Request(f"{base}/api/stacks/{stack_id}/file", headers=headers)
try:
with request.urlopen(file_request) as resp:
file_data = json.loads(resp.read().decode())
except error.HTTPError as exc:
exit_with_http_details(exc)
stack_file_content = file_data.get("StackFileContent") or file_data.get("stackFileContent", "")
env = file_data.get("Env") or file_data.get("env") or []

# Redeploy via PUT (Portainer has no POST .../deploy endpoint)
payload = {
"endpointId": endpoint_id,
"stackFileContent": stack_file_content,
"env": env,
"prune": True,
"pullImage": True,
}
deploy_request = request.Request(
f"{url.rstrip('/')}/api/stacks/{stack_id}/deploy",
data=json.dumps({"prune": True, "pullImage": True}).encode(),
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
method="POST",
f"{base}/api/stacks/{stack_id}",
data=json.dumps(payload).encode(),
headers=headers,
method="PUT",
)
try:
with request.urlopen(deploy_request) as resp:
Expand All @@ -123,5 +155,5 @@ jobs:
except error.HTTPError as exc:
exit_with_http_details(exc)
except error.URLError as exc:
sys.exit(f"Failed to reach Portainer deploy endpoint: {exc.reason}")
sys.exit(f"Failed to reach Portainer stack update endpoint: {exc.reason}")
PY
10 changes: 8 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
target/
!.mvn/wrapper/maven-wrapper.jar

### VS Code ###
.vscode/

### Maven (keep wrapper, ignore local config) ###
.mvn/*
!.mvn/wrapper/

### STS ###
.apt_generated
Expand All @@ -10,7 +16,7 @@ target/
.springBeans

### IntelliJ IDEA ###
.idea
.idea/
*.iws
*.iml
*.ipr
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public static void main(String[] args) {
}

@PostConstruct
private void init() {
public void init() {
bots.init();
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package ru.holyway.botplatform.config;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package ru.holyway.botplatform.core;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import ru.holyway.botplatform.core.data.DataHelper;
import ru.holyway.botplatform.core.handler.MessageHandler;

import javax.annotation.PostConstruct;
Expand All @@ -16,8 +17,7 @@
*/
public class CommonMessageHandler implements CommonHandler {

@Autowired
private DataHelper dataHelper;
private static final Logger LOGGER = LoggerFactory.getLogger(CommonMessageHandler.class);

@Autowired
@Qualifier("orderedMessageHandlers")
Expand All @@ -29,7 +29,7 @@ public class CommonMessageHandler implements CommonHandler {
@Value("${bot.config.silentPeriod}")
private String silentPeriodString;

private long srartTime = 0;
private long startTime = 0;
private long silentPeriod = TimeUnit.SECONDS.toMillis(60);


Expand All @@ -39,7 +39,7 @@ public CommonMessageHandler() {

@PostConstruct
public void postConstruct() {
srartTime = System.currentTimeMillis();
startTime = System.currentTimeMillis();
if (StringUtils.isNotEmpty(silentPeriodString)) {
silentPeriod = TimeUnit.SECONDS.toMillis(Long.parseLong(silentPeriodString));
}
Expand All @@ -56,7 +56,7 @@ public String generateAnswer(MessageEntity messageEntity) {
return message;
}
} catch (ProcessStopException e) {
System.out.println("Stop because: " + e.getMessage());
LOGGER.debug("Stop because: {}", e.getMessage());
break;
}
}
Expand All @@ -72,15 +72,14 @@ public void handleMessage(MessageEntity messageEntity) {
sendMessage(messageEntity, answer);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
LOGGER.error("Error handling message", e);
}

}

private void sendMessage(MessageEntity messageEntity, String text) {
long currentTime = System.currentTimeMillis();
if (currentTime - this.srartTime > silentPeriod) {
if (currentTime - this.startTime > silentPeriod) {
sendMessageInternal(messageEntity, text);
context.setLastStamp(System.currentTimeMillis());
context.incrementCount();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package ru.holyway.botplatform.core.education;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.holyway.botplatform.core.data.DataHelper;
Expand All @@ -17,6 +19,8 @@
@Component
public class EducationCache {

private static final Logger LOGGER = LoggerFactory.getLogger(EducationCache.class);

private ConcurrentMap<String, List<List<String>>> learningTokenizedDictionary = new ConcurrentHashMap<>();

private ConcurrentMap<String, List<String>> listCurrentLearning = new ConcurrentHashMap<>();
Expand All @@ -35,7 +39,7 @@ public class EducationCache {
private DataHelper dataHelper;

@PostConstruct
private void postConstruct() {
public void postConstruct() {
init();
}

Expand All @@ -55,7 +59,7 @@ public synchronized void init() {
simpleWords = dataHelper.getSimple();

} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Error loading learning data", e);
}
for (Map.Entry<String, List<String>> line : learnWords.entrySet()) {
final List<List<String>> tokenizedAnswers = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package ru.holyway.botplatform.core.handler;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.holyway.botplatform.core.MessageEntity;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package ru.holyway.botplatform.scripting;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

Expand All @@ -8,6 +10,8 @@

public class TelegramScriptEntity {

private static final Logger LOGGER = LoggerFactory.getLogger(TelegramScriptEntity.class);

public TelegramScriptEntity() {

}
Expand All @@ -18,7 +22,7 @@ private Consumer<ScriptContext> send(String chatId, String text) {
s.message.messageEntity.getSender()
.execute(SendMessage.builder().text(text).chatId(chatId).build());
} catch (TelegramApiException e) {
e.printStackTrace();
LOGGER.error("Error sending message to chat {}", chatId, e);
}
};
}
Expand All @@ -29,7 +33,7 @@ private Consumer<ScriptContext> send(Long chatId, String text) {
s.message.messageEntity.getSender()
.execute(SendMessage.builder().text(text).chatId(String.valueOf(chatId)).build());
} catch (TelegramApiException e) {
e.printStackTrace();
LOGGER.error("Error sending message to chat {}", chatId, e);
}
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,13 +172,13 @@ public AbstractText group(final Integer group) {
});
}

public AbstractText split(final String deliniter, final Integer group) {
public AbstractText split(final String delimiter, final Integer group) {
return new Text(scriptContext -> {
String value = value().apply(scriptContext);
if (value == null) {
return null;
}
String[] splits = value.split(deliniter);
String[] splits = value.split(delimiter);
if (group < 0 || group >= splits.length) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ public ArrayEntity(Function<ScriptContext, List<String>> array) {
}

public Consumer<ScriptContext> forEachFrom(Consumer<ScriptContext> func, Function<ScriptContext, Number> startFrom) {
return scriptContext -> forEachFrom(func, Integer.parseInt(startFrom.apply(scriptContext).toString()));
return scriptContext -> forEachFrom(func, Integer.parseInt(startFrom.apply(scriptContext).toString())).accept(scriptContext);
}

public Consumer<ScriptContext> forEachLast(Consumer<ScriptContext> func, Function<ScriptContext, Number> last) {
return scriptContext -> forEachLast(func, Integer.parseInt(last.apply(scriptContext).toString()));
return scriptContext -> forEachLast(func, Integer.parseInt(last.apply(scriptContext).toString())).accept(scriptContext);
}

public Consumer<ScriptContext> forEachFrom(Consumer<ScriptContext> func, int startFrom) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package ru.holyway.botplatform.scripting.entity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
Expand All @@ -12,6 +14,8 @@

public class MessageBuilder implements Function<ScriptContext, SendMessage> {

private static final Logger LOGGER = LoggerFactory.getLogger(MessageBuilder.class);

private Function<ScriptContext, String> text;
private Function<ScriptContext, String> chatId;
private Map<Function<ScriptContext, String>, Function<ScriptContext, String>> buttons = new LinkedHashMap<>();
Expand Down Expand Up @@ -56,7 +60,7 @@ public Consumer<ScriptContext> send() {
.execute(apply(s))
.getMessageId().toString());
} catch (TelegramApiException e) {
e.printStackTrace();
LOGGER.error("Error sending message", e);
}
};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package ru.holyway.botplatform.scripting.entity;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.support.CronTrigger;
import ru.holyway.botplatform.scripting.ScriptContext;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package ru.holyway.botplatform.security;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ public void run() {
}
} catch (InterruptedException e) {
LOGGER.error("Interrupt Error occurred during execution main: ", e);
Thread.currentThread().interrupt();
return;
} catch (Exception e) {
LOGGER.error("Error occurred during execution main: ", e);
}
Expand Down
Loading
Loading