Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Added webhook support to rules RHS (#874)

Martin Peeters31733c88922a
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerAgent.java b/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerAgent.java
index 08aef78c7..d2bd9c9ec 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerAgent.java
@@ -21,6 +21,7 @@ package org.openremote.agent.protocol.http;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.http.HTTPMethod;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueType;
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerProtocol.java
index 5f57fd463..ee64cbf20 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerProtocol.java
@@ -38,6 +38,7 @@ import org.openremote.model.Container;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.attribute.Attribute;
+import org.openremote.model.http.HTTPMethod;
import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.TextUtil;
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgent.java b/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgent.java
index 092bd0f19..cc6a4476e 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgent.java
@@ -21,6 +21,7 @@ package org.openremote.agent.protocol.http;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
+import org.openremote.model.http.HTTPMethod;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueDescriptor;
import org.openremote.model.value.ValueType;
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgentLink.java
index f4c4bc3d7..ece9b6182 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgentLink.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgentLink.java
@@ -21,6 +21,7 @@ package org.openremote.agent.protocol.http;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.http.HTTPMethod;
import org.openremote.model.value.ValueType;
import java.util.List;
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
index c911ca657..5cd2b4bbc 100644
--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
@@ -43,6 +43,7 @@ import org.openremote.model.util.TextUtil;
import org.openremote.model.util.TimeUtil;
import org.openremote.model.util.ValueUtil;
import org.openremote.model.value.MetaItemType;
+import org.openremote.model.webhook.Webhook;
import org.quartz.CronExpression;
import org.shredzone.commons.suncalc.SunTimes;
@@ -61,6 +62,7 @@ import java.util.stream.Stream;
import static org.openremote.manager.rules.AssetQueryPredicate.groupIsEmpty;
import static org.openremote.model.query.filter.LocationAttributePredicate.getLocationPredicates;
+import static org.openremote.model.util.ValueUtil.LOG;
import static org.openremote.model.util.ValueUtil.distinctByKey;
public class JsonRulesBuilder extends RulesBuilder {
@@ -547,6 +549,7 @@ public class JsonRulesBuilder extends RulesBuilder {
final protected Assets assetsFacade;
final protected Users usersFacade;
final protected Notifications notificationsFacade;
+ final protected Webhooks webhooksFacade;
final protected HistoricDatapoints historicDatapointsFacade;
final protected PredictedDatapoints predictedDatapointsFacade;
final protected ScheduledExecutorService executorService;
@@ -557,7 +560,7 @@ public class JsonRulesBuilder extends RulesBuilder {
public JsonRulesBuilder(Ruleset ruleset, TimerService timerService,
AssetStorageService assetStorageService, ScheduledExecutorService executorService,
- Assets assetsFacade, Users usersFacade, Notifications notificationsFacade,
+ Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade,
HistoricDatapoints historicDatapoints, PredictedDatapoints predictedDatapoints,
BiConsumer<Runnable, Long> scheduledActionConsumer) throws Exception {
this.timerService = timerService;
@@ -566,6 +569,7 @@ public class JsonRulesBuilder extends RulesBuilder {
this.assetsFacade = assetsFacade;
this.usersFacade = usersFacade;
this.notificationsFacade = notificationsFacade;
+ this.webhooksFacade = webhooksFacade;
this.historicDatapointsFacade= historicDatapoints;
this.predictedDatapointsFacade = predictedDatapoints;
this.scheduledActionConsumer = scheduledActionConsumer;
@@ -590,7 +594,7 @@ public class JsonRulesBuilder extends RulesBuilder {
public void stop(RulesFacts facts) {
Arrays.stream(jsonRules).forEach(jsonRule ->
- executeRuleActions(jsonRule, jsonRule.onStop, "onStop", false, facts, null, assetsFacade, usersFacade, notificationsFacade, predictedDatapointsFacade, this.scheduledActionConsumer));
+ executeRuleActions(jsonRule, jsonRule.onStop, "onStop", false, facts, null, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, predictedDatapointsFacade, this.scheduledActionConsumer));
// Remove temporal fact for timer rule evaluation
String tempFactName = TIMER_TEMPORAL_FACT_NAME_PREFIX + jsonRuleset.getId();
@@ -602,7 +606,7 @@ public class JsonRulesBuilder extends RulesBuilder {
Arrays.stream(jsonRules).forEach(jsonRule -> {
hasTimeTrigger.set(hasTimeTrigger.get() || LogicGroup.getItemsRecursive(jsonRule.when).stream().anyMatch(RuleCondition::hasTimeTrigger));
- executeRuleActions(jsonRule, jsonRule.onStart, "onStart", false, facts, null, assetsFacade, usersFacade, notificationsFacade, predictedDatapointsFacade, this.scheduledActionConsumer);
+ executeRuleActions(jsonRule, jsonRule.onStart, "onStart", false, facts, null, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, predictedDatapointsFacade, this.scheduledActionConsumer);
});
// Initialise asset states
@@ -687,12 +691,12 @@ public class JsonRulesBuilder extends RulesBuilder {
try {
if (ruleState.thenMatched()) {
log(Level.FINER, "Triggered rule so executing 'then' actions for rule: " + rule.name);
- executeRuleActions(rule, rule.then, "then", false, facts, ruleState, assetsFacade, usersFacade, notificationsFacade, predictedDatapointsFacade, scheduledActionConsumer);
+ executeRuleActions(rule, rule.then, "then", false, facts, ruleState, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, predictedDatapointsFacade, scheduledActionConsumer);
}
if (rule.otherwise != null && ruleState.otherwiseMatched()) {
log(Level.FINER, "Triggered rule so executing 'otherwise' actions for rule: " + rule.name);
- executeRuleActions(rule, rule.otherwise, "otherwise", true, facts, ruleState, assetsFacade, usersFacade, notificationsFacade, predictedDatapointsFacade, scheduledActionConsumer);
+ executeRuleActions(rule, rule.otherwise, "otherwise", true, facts, ruleState, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, predictedDatapointsFacade, scheduledActionConsumer);
}
} catch (Exception e) {
log(Level.SEVERE, "Exception thrown during rule RHS execution", e);
@@ -734,7 +738,7 @@ public class JsonRulesBuilder extends RulesBuilder {
};
}
- public static void executeRuleActions(JsonRule rule, RuleAction[] ruleActions, String actionsName, boolean useUnmatched, RulesFacts facts, RuleState ruleState, Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, PredictedDatapoints predictedDatapointsFacade, BiConsumer<Runnable, Long> scheduledActionConsumer) {
+ public static void executeRuleActions(JsonRule rule, RuleAction[] ruleActions, String actionsName, boolean useUnmatched, RulesFacts facts, RuleState ruleState, Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade, PredictedDatapoints predictedDatapointsFacade, BiConsumer<Runnable, Long> scheduledActionConsumer) {
if (ruleActions != null && ruleActions.length > 0) {
@@ -754,6 +758,7 @@ public class JsonRulesBuilder extends RulesBuilder {
assetsFacade,
usersFacade,
notificationsFacade,
+ webhooksFacade,
predictedDatapointsFacade
);
@@ -781,7 +786,7 @@ public class JsonRulesBuilder extends RulesBuilder {
.collect(Collectors.toList());
}
- protected static RuleActionExecution buildRuleActionExecution(JsonRule rule, RuleAction ruleAction, String actionsName, int index, boolean useUnmatched, RulesFacts facts, RuleState ruleState, Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, PredictedDatapoints predictedDatapointsFacade) {
+ protected static RuleActionExecution buildRuleActionExecution(JsonRule rule, RuleAction ruleAction, String actionsName, int index, boolean useUnmatched, RulesFacts facts, RuleState ruleState, Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade, PredictedDatapoints predictedDatapointsFacade) {
if (ruleAction instanceof RuleActionNotification notificationAction) {
@@ -810,7 +815,7 @@ public class JsonRulesBuilder extends RulesBuilder {
if (body.contains(PLACEHOLDER_TRIGGER_ASSETS)) {
// Need to clone the notification
notification = ValueUtil.clone(notification);
- String triggeredAssetInfo = buildTriggeredAssetInfo(useUnmatched, ruleState, isHtml);
+ String triggeredAssetInfo = buildTriggeredAssetInfo(useUnmatched, ruleState, isHtml, false);
body = body.replace(PLACEHOLDER_TRIGGER_ASSETS, triggeredAssetInfo);
if (isEmail) {
@@ -861,6 +866,27 @@ public class JsonRulesBuilder extends RulesBuilder {
}
}
+ if (ruleAction instanceof RuleActionWebhook webhookAction) {
+ Webhook webhook = webhookAction.webhook;
+ if (webhook.getUrl() != null && webhook.getHttpMethod() != null) {
+
+ // Replace %TRIGGER_ASSETS% with the triggered assets in JSON format.
+ if (!TextUtil.isNullOrEmpty(webhook.getPayload()) && webhook.getPayload().contains(PLACEHOLDER_TRIGGER_ASSETS)) {
+ String triggeredAssetInfo = buildTriggeredAssetInfo(useUnmatched, ruleState, false, true);
+ webhook.setPayload(webhook.getPayload()
+ .replace(PLACEHOLDER_TRIGGER_ASSETS, triggeredAssetInfo)
+ .replace(('"' + PLACEHOLDER_TRIGGER_ASSETS + '"'), triggeredAssetInfo)
+ );
+ }
+
+ if(webhookAction.target == null) {
+ webhookAction.target = webhooksFacade.buildTarget(webhook);
+ }
+
+ return new RuleActionExecution(() -> webhooksFacade.send(webhook, webhookAction.target), 0);
+ }
+ }
+
if (ruleAction instanceof RuleActionWriteAttribute attributeAction) {
if (targetIsNotAssets(ruleAction.target)) {
@@ -1017,7 +1043,7 @@ public class JsonRulesBuilder extends RulesBuilder {
return null;
}
- private static String buildTriggeredAssetInfo(boolean useUnmatched, RuleState ruleEvaluationResult, boolean isHtml) {
+ private static String buildTriggeredAssetInfo(boolean useUnmatched, RuleState ruleEvaluationResult, boolean isHtml, boolean isJson) {
Set<String> assetIds = useUnmatched ? ruleEvaluationResult.otherwiseMatchedAssetIds : ruleEvaluationResult.thenMatchedAssetIds;
@@ -1053,6 +1079,12 @@ public class JsonRulesBuilder extends RulesBuilder {
sb.append("</td></tr>");
}));
sb.append("</table>");
+ } else if (isJson) {
+ try {
+ return ValueUtil.JSON.writeValueAsString(assetStates);
+ } catch (Exception e) {
+ LOG.warning(e.getMessage());
+ }
} else {
sb.append("Asset ID\t\tAsset Name\t\tAttribute\t\tValue");
assetStates.forEach((key, value) -> value.forEach(assetState -> {
@@ -1142,7 +1174,7 @@ public class JsonRulesBuilder extends RulesBuilder {
}
protected static SunTimes.Parameters getSunCalculator(SunPositionTrigger sunPositionTrigger, TimerService timerService) throws IllegalStateException {
- SunPositionTrigger.Position position = sunPositionTrigger.getPosition();
+ SunPositionTrigger.Position position = sunPositionTrigger.getPosition();
GeoJSONPoint location = sunPositionTrigger.getLocation();
if (position == null) {
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
index b6c2d7dc2..c509bbf92 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
@@ -34,6 +34,7 @@ import org.openremote.manager.event.ClientEventService;
import org.openremote.manager.notification.NotificationService;
import org.openremote.manager.rules.facade.*;
import org.openremote.manager.security.ManagerIdentityService;
+import org.openremote.manager.webhook.WebhookService;
import org.openremote.model.PersistenceEvent;
import org.openremote.model.asset.Asset;
import org.openremote.model.query.filter.GeofencePredicate;
@@ -113,6 +114,7 @@ public class RulesEngine<T extends Ruleset> {
final protected Assets assetsFacade;
final protected Users usersFacade;
final protected Notifications notificationFacade;
+ final protected Webhooks webhooksFacade;
final protected PredictedDatapoints predictedFacade;
final protected HistoricDatapoints historicFacade;
final protected AssetLocationPredicateProcessor assetLocationPredicatesConsumer;
@@ -141,6 +143,7 @@ public class RulesEngine<T extends Ruleset> {
AssetStorageService assetStorageService,
AssetProcessingService assetProcessingService,
NotificationService notificationService,
+ WebhookService webhookService,
ClientEventService clientEventService,
AssetDatapointService assetDatapointService,
AssetPredictedDatapointService assetPredictedDatapointService,
@@ -155,6 +158,7 @@ public class RulesEngine<T extends Ruleset> {
this.assetsFacade = assetsFacade;
this.usersFacade = new UsersFacade<>(id, assetStorageService, notificationService, identityService);
this.notificationFacade = new NotificationsFacade<>(id, notificationService);
+ this.webhooksFacade = new WebhooksFacade<>(id, webhookService);
this.historicFacade = new HistoricFacade<>(id, assetDatapointService);
this.predictedFacade = new PredictedFacade<>(id, assetPredictedDatapointService);
this.assetLocationPredicatesConsumer = assetLocationPredicatesConsumer;
@@ -265,7 +269,7 @@ public class RulesEngine<T extends Ruleset> {
removeRuleset(deployment.ruleset);
}
- deployment = new RulesetDeployment(ruleset, timerService, assetStorageService, executorService, assetsFacade, usersFacade, notificationFacade, historicFacade, predictedFacade);
+ deployment = new RulesetDeployment(ruleset, timerService, assetStorageService, executorService, assetsFacade, usersFacade, notificationFacade, webhooksFacade, historicFacade, predictedFacade);
boolean compiled;
if (TextUtil.isNullOrEmpty(ruleset.getRules())) {
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
index a10a9a443..b4ecc6ac6 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
@@ -34,6 +34,7 @@ import org.openremote.manager.datapoint.AssetPredictedDatapointService;
import org.openremote.manager.event.ClientEventService;
import org.openremote.manager.gateway.GatewayService;
import org.openremote.manager.notification.NotificationService;
+import org.openremote.manager.webhook.WebhookService;
import org.openremote.manager.rules.flow.FlowResourceImpl;
import org.openremote.manager.rules.geofence.GeofenceAssetAdapter;
import org.openremote.manager.security.ManagerIdentityService;
@@ -114,6 +115,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
protected ManagerIdentityService identityService;
protected AssetStorageService assetStorageService;
protected NotificationService notificationService;
+ protected WebhookService webhookService;
protected AssetProcessingService assetProcessingService;
protected AssetDatapointService assetDatapointService;
protected AssetPredictedDatapointService assetPredictedDatapointService;
@@ -146,6 +148,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
rulesetStorageService = container.getService(RulesetStorageService.class);
identityService = container.getService(ManagerIdentityService.class);
notificationService = container.getService(NotificationService.class);
+ webhookService = container.getService(WebhookService.class);
assetStorageService = container.getService(AssetStorageService.class);
assetProcessingService = container.getService(AssetProcessingService.class);
assetDatapointService = container.getService(AssetDatapointService.class);
@@ -619,6 +622,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
assetStorageService,
assetProcessingService,
notificationService,
+ webhookService,
clientEventService,
assetDatapointService,
assetPredictedDatapointService,
@@ -659,6 +663,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
assetStorageService,
assetProcessingService,
notificationService,
+ webhookService,
clientEventService,
assetDatapointService,
assetPredictedDatapointService,
@@ -735,6 +740,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
assetStorageService,
assetProcessingService,
notificationService,
+ webhookService,
clientEventService,
assetDatapointService,
assetPredictedDatapointService,
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
index 2eef24478..7e8000da2 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
@@ -128,6 +128,7 @@ public class RulesetDeployment {
final protected Assets assetsFacade;
final protected Users usersFacade;
final protected Notifications notificationsFacade;
+ final protected Webhooks webhooksFacade;
final protected HistoricDatapoints historicDatapointsFacade;
final protected PredictedDatapoints predictedDatapointsFacade;
final protected List<ScheduledFuture<?>> scheduledRuleActions = new ArrayList<>();
@@ -140,7 +141,7 @@ public class RulesetDeployment {
public RulesetDeployment(Ruleset ruleset, TimerService timerService,
AssetStorageService assetStorageService, ScheduledExecutorService executorService,
- Assets assetsFacade, Users usersFacade, Notifications notificationsFacade,
+ Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade,
HistoricDatapoints historicDatapointsFacade, PredictedDatapoints predictedDatapointsFacade) {
this.ruleset = ruleset;
this.timerService = timerService;
@@ -149,6 +150,7 @@ public class RulesetDeployment {
this.assetsFacade = assetsFacade;
this.usersFacade = usersFacade;
this.notificationsFacade = notificationsFacade;
+ this.webhooksFacade = webhooksFacade;
this.historicDatapointsFacade = historicDatapointsFacade;
this.predictedDatapointsFacade = predictedDatapointsFacade;
@@ -267,7 +269,7 @@ public class RulesetDeployment {
protected boolean compileRulesJson(Ruleset ruleset) {
try {
- jsonRulesBuilder = new JsonRulesBuilder(ruleset, timerService, assetStorageService, executorService, assetsFacade, usersFacade, notificationsFacade, historicDatapointsFacade, predictedDatapointsFacade, this::scheduleRuleAction);
+ jsonRulesBuilder = new JsonRulesBuilder(ruleset, timerService, assetStorageService, executorService, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, historicDatapointsFacade, predictedDatapointsFacade, this::scheduleRuleAction);
for (Rule rule : jsonRulesBuilder.build()) {
RulesEngine.LOG.finer("Registering JSON rule: " + rule.getName());
diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/WebhooksFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/WebhooksFacade.java
new file mode 100644
index 000000000..aa2b0e64e
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/facade/WebhooksFacade.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2022, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.rules.facade;
+
+import org.openremote.manager.rules.RulesEngineId;
+import org.openremote.manager.webhook.WebhookService;
+import org.openremote.model.rules.Ruleset;
+import org.openremote.model.rules.Webhooks;
+import org.openremote.model.webhook.Webhook;
+
+import javax.ws.rs.client.WebTarget;
+
+public class WebhooksFacade<T extends Ruleset> extends Webhooks {
+
+ protected final RulesEngineId<T> rulesEngineId;
+ protected final WebhookService webhookService;
+
+ public WebhooksFacade(RulesEngineId<T> rulesEngineId, WebhookService webhookService) {
+ this.rulesEngineId = rulesEngineId;
+ this.webhookService = webhookService;
+ }
+
+ @Override
+ public void send(Webhook webhook, WebTarget target) {
+ webhookService.sendHttpRequest(webhook, target);
+ }
+
+ @Override
+ public WebTarget buildTarget(Webhook webhook) {
+ return webhookService.buildWebTarget(webhook);
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java b/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java
new file mode 100644
index 000000000..eca519fe0
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright 2022, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.webhook;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.jboss.resteasy.client.jaxrs.ResteasyClient;
+import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
+import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
+import org.openremote.container.web.WebClient;
+import org.openremote.container.web.WebTargetBuilder;
+import org.openremote.manager.rules.RulesEngine;
+import org.openremote.model.Container;
+import org.openremote.model.ContainerService;
+import org.openremote.model.http.HTTPMethod;
+import org.openremote.model.webhook.Webhook;
+
+import javax.ws.rs.ProcessingException;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.Response;
+import java.net.URI;
+import java.util.concurrent.TimeUnit;
+import java.util.logging.Logger;
+
+import static org.openremote.container.util.MapAccess.getInteger;
+
+public class WebhookService extends RouteBuilder implements ContainerService {
+
+ private static final Logger LOG = Logger.getLogger(WebhookService.class.getName());
+ protected ResteasyClientBuilder clientBuilder;
+
+ public static final String WEBHOOK_CONNECT_TIMEOUT = "WEBHOOK_CONNECT_TIMEOUT";
+ public static final int WEBHOOK_CONNECT_TIMEOUT_DEFAULT = 2000;
+ public static final String WEBHOOK_REQUEST_TIMEOUT = "WEBHOOK_REQUEST_TIMEOUT";
+ public static final int WEBHOOK_REQUEST_TIMEOUT_DEFAULT = 10000;
+
+ @Override
+ public void init(Container container) throws Exception {
+ this.clientBuilder = new ResteasyClientBuilder()
+ .connectTimeout(
+ getInteger(container.getConfig(), WEBHOOK_CONNECT_TIMEOUT, WEBHOOK_CONNECT_TIMEOUT_DEFAULT),
+ TimeUnit.MILLISECONDS
+ )
+ .readTimeout(
+ getInteger(container.getConfig(), WEBHOOK_REQUEST_TIMEOUT, WEBHOOK_REQUEST_TIMEOUT_DEFAULT),
+ TimeUnit.MILLISECONDS
+ );
+ }
+
+ @Override
+ public int getPriority() {
+ return ContainerService.DEFAULT_PRIORITY;
+ }
+
+ @Override
+ public void configure() throws Exception {
+ // empty
+ }
+
+ @Override
+ public void start(Container container) throws Exception {
+ // empty
+ }
+
+ @Override
+ public void stop(Container container) throws Exception {
+ // empty
+ }
+
+ public void sendHttpRequest(Webhook webhook, WebTarget target) {
+ Response response = null;
+ try {
+ ResteasyWebTarget webTarget = (ResteasyWebTarget) target;
+ response = this.buildRequest(webTarget, webhook.getHttpMethod(), webhook.getPayload());
+ if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
+ RulesEngine.LOG.warning("Webhook request responded with error " + response.getStatus());
+ }
+ } catch (Exception e) {
+ LOG.warning(e.getMessage());
+ } finally {
+ if (response != null) {
+ response.close();
+ }
+ }
+ }
+
+ public WebTarget buildWebTarget(Webhook webhook) {
+ ResteasyClient client = WebClient.registerDefaults(clientBuilder).build();
+ WebTargetBuilder builder = new WebTargetBuilder(client, URI.create(webhook.getUrl()));
+
+ // Authentication
+ if (webhook.getUsernamePassword() != null) {
+ builder.setBasicAuthentication(webhook.getUsernamePassword().getUsername(), webhook.getUsernamePassword().getPassword());
+ } else if (webhook.getOAuthGrant() != null) {
+ builder.setOAuthAuthentication(webhook.getOAuthGrant());
+ }
+ if (webhook.getHeaders() != null && webhook.getHeaders().size() > 0) {
+ builder.setInjectHeaders(webhook.getHeaders());
+ }
+ return builder.build();
+ }
+
+ private Response buildRequest(ResteasyWebTarget target, HTTPMethod method, String payload) throws ProcessingException {
+ Response response = target.request().method(method.name());
+ if (payload != null) {
+ return target.request().method(method.name(), Entity.entity(payload, response.getMediaType()));
+ } else {
+ return response;
+ }
+ }
+}
diff --git a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService
index a6f61da7c..b0093efab 100644
--- a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService
+++ b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService
@@ -16,6 +16,7 @@ org.openremote.manager.agent.AgentService
org.openremote.manager.simulator.SimulatorService
org.openremote.manager.map.MapService
org.openremote.manager.notification.NotificationService
+org.openremote.manager.webhook.WebhookService
org.openremote.manager.apps.ConsoleAppService
org.openremote.manager.web.ManagerWebService
org.openremote.manager.notification.PushNotificationHandler
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.json
index 20ee6b8e4..f22a71f1f 100644
--- a/manager/src/web/shared/locales/en/or.json
+++ b/manager/src/web/shared/locales/en/or.json
@@ -192,6 +192,14 @@
"matchedOfType": "Matched of type {{type}}",
"unmatched": "Unmatched",
"wait": "Wait",
+ "webhook": "Webhook",
+ "webUrl": "Web URL",
+ "header": "Header",
+ "addRequestHeader": "Add Request Header",
+ "requiresAuthorization": "Requires Authorization",
+ "tokenUrl": "Token URL",
+ "method": "Method",
+ "includeBodyInRequest": "Include body in Request",
"linkedUsers": "Linked users",
"setup": "Setup",
"selectFile": "Select file",
@@ -276,6 +284,7 @@
"secured": "Secured",
"clientSecret": "Client secret",
"clientId": "Client ID",
+ "refreshToken": "Refresh Token",
"port": "Port",
"host": "Hostname",
"errorOccurred": "An error has occurred",
diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.json
index fca8d72a9..38290db47 100644
--- a/manager/src/web/shared/locales/nl/or.json
+++ b/manager/src/web/shared/locales/nl/or.json
@@ -192,6 +192,14 @@
"matchedOfType": "Hetzelfde type: {{type}}",
"unmatched": "Niet dezelfde",
"wait": "Wacht",
+ "webhook": "Webhook",
+ "webUrl": "Web URL",
+ "header": "Header",
+ "addRequestHeader": "Voeg Request Header toe",
+ "requiresAuthorization": "Vereist Authorizatie",
+ "tokenUrl": "Token URL",
+ "method": "Methode",
+ "includeBodyInRequest": "Verstuur body met request",
"linkedUsers": "Gekoppelde gebruikers",
"setup": "Instellingen",
"selectFile": "Kies bestand",
@@ -276,6 +284,7 @@
"secured": "Beveiligd",
"clientSecret": "Client wachtwoord",
"clientId": "Client ID",
+ "refreshToken": "Refresh Token",
"port": "Poort",
"host": "Hostname",
"errorOccurred": "Er is een fout opgetreden",
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPMethod.java b/model/src/main/java/org/openremote/model/http/HTTPMethod.java
similarity index 91%
rename from agent/src/main/java/org/openremote/agent/protocol/http/HTTPMethod.java
rename to model/src/main/java/org/openremote/model/http/HTTPMethod.java
index 414d9d6f4..74401c66e 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPMethod.java
+++ b/model/src/main/java/org/openremote/model/http/HTTPMethod.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2020, OpenRemote Inc.
+ * Copyright 2022, OpenRemote Inc.
*
* See the CONTRIBUTORS.txt file in the distribution for a
* full listing of individual contributors.
@@ -17,7 +17,7 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.agent.protocol.http;
+package org.openremote.model.http;
public enum HTTPMethod {
GET,
diff --git a/model/src/main/java/org/openremote/model/rules/Webhooks.java b/model/src/main/java/org/openremote/model/rules/Webhooks.java
new file mode 100644
index 000000000..3fe5d5f59
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/Webhooks.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2022, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.rules;
+
+import org.openremote.model.util.TsIgnore;
+import org.openremote.model.webhook.Webhook;
+
+import javax.ws.rs.client.WebTarget;
+
+@TsIgnore
+public abstract class Webhooks {
+
+ public abstract void send(Webhook webhook, WebTarget target);
+ public abstract WebTarget buildTarget(Webhook webhook);
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleAction.java b/model/src/main/java/org/openremote/model/rules/json/RuleAction.java
index a616d5938..88ca29fa1 100644
--- a/model/src/main/java/org/openremote/model/rules/json/RuleAction.java
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleAction.java
@@ -29,7 +29,8 @@ import java.util.function.Function;
@JsonSubTypes.Type(value = RuleActionWait.class, name = "wait"),
@JsonSubTypes.Type(value = RuleActionWriteAttribute.class, name = "write-attribute"),
@JsonSubTypes.Type(value = RuleActionNotification.class, name = "notification"),
- @JsonSubTypes.Type(value = RuleActionUpdateAttribute.class, name = "update-attribute")
+ @JsonSubTypes.Type(value = RuleActionUpdateAttribute.class, name = "update-attribute"),
+ @JsonSubTypes.Type(value = RuleActionWebhook.class, name = "webhook")
})
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleActionWebhook.java b/model/src/main/java/org/openremote/model/rules/json/RuleActionWebhook.java
new file mode 100644
index 000000000..b2b40b572
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleActionWebhook.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2022, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.rules.json;
+
+import org.openremote.model.webhook.Webhook;
+
+import javax.ws.rs.client.WebTarget;
+
+public class RuleActionWebhook extends RuleAction {
+ public Webhook webhook;
+ public WebTarget target;
+}
diff --git a/model/src/main/java/org/openremote/model/webhook/Webhook.java b/model/src/main/java/org/openremote/model/webhook/Webhook.java
new file mode 100644
index 000000000..5ce2385e8
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/webhook/Webhook.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2022, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.webhook;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import org.openremote.model.auth.OAuthGrant;
+import org.openremote.model.auth.UsernamePassword;
+import org.openremote.model.http.HTTPMethod;
+
+import java.util.List;
+import java.util.Map;
+
+public class Webhook {
+
+ protected String name;
+ protected String url;
+ protected Map<String, List<String>> headers;
+ protected HTTPMethod httpMethod;
+ protected UsernamePassword usernamePassword;
+ protected OAuthGrant oAuthGrant;
+ protected String payload;
+
+ @JsonCreator
+ public Webhook(String name, String url, Map<String, List<String>> headers, HTTPMethod httpMethod, UsernamePassword usernamePassword, OAuthGrant oAuthGrant, String payload) {
+ this.name = name;
+ this.url = url;
+ this.headers = headers;
+ this.httpMethod = httpMethod;
+ this.usernamePassword = usernamePassword;
+ this.oAuthGrant = oAuthGrant;
+ this.payload = payload;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Webhook setName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public Map<String, List<String>> getHeaders() {
+ return headers;
+ }
+
+ public void setHeaders(Map<String, List<String>> headers) {
+ this.headers = headers;
+ }
+
+ public HTTPMethod getHttpMethod() {
+ return httpMethod;
+ }
+
+ public void setHttpMethod(HTTPMethod method) {
+ this.httpMethod = method;
+ }
+
+ public UsernamePassword getUsernamePassword() {
+ return usernamePassword;
+ }
+
+ public void setAuthMethod(UsernamePassword usernamePassword) {
+ this.usernamePassword = usernamePassword;
+ }
+
+ public OAuthGrant getOAuthGrant() {
+ return oAuthGrant;
+ }
+
+ public void setoAuthGrant(OAuthGrant oAuthGrant) {
+ this.oAuthGrant = oAuthGrant;
+ }
+
+ public String getPayload() {
+ return payload;
+ }
+
+ public void setPayload(String payload) {
+ this.payload = payload;
+ }
+}
diff --git a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy
index 8cf6784ac..28175e3b7 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy
@@ -24,7 +24,6 @@ import org.jboss.resteasy.spi.ResteasyUriInfo
import org.jboss.resteasy.util.BasicAuthHelper
import org.openremote.agent.protocol.http.HTTPAgent
import org.openremote.agent.protocol.http.HTTPAgentLink
-import org.openremote.agent.protocol.http.HTTPMethod
import org.openremote.agent.protocol.http.HTTPProtocol
import org.openremote.container.web.OAuthServerResponse
import org.openremote.manager.agent.AgentService
@@ -39,6 +38,7 @@ import org.openremote.model.attribute.MetaItem
import org.openremote.model.auth.OAuthGrant
import org.openremote.model.auth.OAuthPasswordGrant
import org.openremote.model.auth.OAuthRefreshTokenGrant
+import org.openremote.model.http.HTTPMethod
import org.openremote.model.util.ValueUtil
import org.openremote.model.value.RegexValueFilter
import org.openremote.model.value.SubStringValueFilter
diff --git a/ui/app/manager/src/pages/page-rules.ts b/ui/app/manager/src/pages/page-rules.ts
index bb39d96f8..bba7bdd79 100644
--- a/ui/app/manager/src/pages/page-rules.ts
+++ b/ui/app/manager/src/pages/page-rules.ts
@@ -39,6 +39,7 @@ export const PAGE_RULES_CONFIG_DEFAULT: PageRulesConfig = {
actions: {
wait: [],
attribute: [],
+ webhook: [],
email: [NotificationTargetType.USER, NotificationTargetType.CUSTOM],
push: [NotificationTargetType.USER, NotificationTargetType.ASSET],
}
diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.ts
index 96722ecaf..94de9beae 100644
--- a/ui/component/or-rules/src/index.ts
+++ b/ui/component/or-rules/src/index.ts
@@ -52,7 +52,8 @@ export const enum ActionType {
WAIT = "wait",
EMAIL = "email",
PUSH_NOTIFICATION = "push",
- ATTRIBUTE = "attribute"
+ ATTRIBUTE = "attribute",
+ WEBHOOK = "webhook"
}
export enum TimeTriggerType {
TIME_OF_DAY = "TIME_OF_DAY"
diff --git a/ui/component/or-rules/src/json-viewer/forms/or-rule-form-webhook.ts b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-webhook.ts
new file mode 100644
index 000000000..66d2c6477
--- /dev/null
+++ b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-webhook.ts
@@ -0,0 +1,303 @@
+import {
+ HTTPMethod,
+ OAuthGrant,
+ OAuthClientCredentialsGrant,
+ Webhook,
+ OAuthPasswordGrant
+} from "@openremote/model";
+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
+import {i18next} from "@openremote/or-translate";
+import {css, html, LitElement, TemplateResult} from "lit";
+import {customElement, property, state} from "lit/decorators.js";
+import {when} from 'lit/directives/when.js';
+import {OrRulesJsonRuleChangedEvent} from "../or-rule-json-viewer";
+
+
+//language=css
+const styling = css`
+ .divider {
+ border-bottom: 1px solid rgba(0, 0, 0, 12%);
+ }
+`
+
+@customElement("or-rule-form-webhook")
+export class OrRuleFormWebhook extends LitElement {
+
+ @property({type: Object})
+ protected webhook!: Webhook;
+
+ @state()
+ protected loading: boolean = false;
+
+ private httpMethodOptions: HTTPMethod[] = [HTTPMethod.GET, HTTPMethod.POST, HTTPMethod.PUT, HTTPMethod.DELETE];
+ private authMethodOptions: Map<string, string> = new Map<string, string>([
+ ["username_password", (i18next.t('username') + " & " + i18next.t('password'))],
+ ["client_credentials", "oauth Client Credentials Grant"],
+ ["password", "oauth Password Grant"]
+ ]);
+
+ static get styles() {
+ return [styling];
+ }
+
+ /* --------------------------- */
+
+ // Lifecycle methods
+
+ shouldUpdate(changedProperties: Map<string, any>) {
+ if (changedProperties.has('webhook')) {
+ if (this.webhook.headers == undefined) {
+ this.webhook.headers = {};
+ }
+ }
+ return super.shouldUpdate(changedProperties);
+ }
+
+ /* --------------- */
+
+ // Util
+
+ getAuthMethod(webhook: Webhook): string | undefined {
+ if (webhook.oAuthGrant != undefined) {
+ return this.authMethodOptions.get(webhook.oAuthGrant.grant_type);
+ } else {
+ return this.authMethodOptions.get("username_password");
+ }
+ }
+
+ getOAuthGrant(authMethodKey: string): OAuthGrant | undefined {
+ if (authMethodKey == 'client_credentials' || authMethodKey == 'password') {
+ return {grant_type: authMethodKey} as OAuthGrant;
+ } else {
+ return undefined;
+ }
+ }
+
+ reloadHeaders() {
+ this.loading = true;
+ this.updateComplete.then(() => this.loading = false);
+ this.notifyWebhookUpdate(false)
+ }
+
+ notifyWebhookUpdate(requestUpdate: boolean = true) {
+ if (requestUpdate) {
+ this.requestUpdate("webhook");
+ }
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
+ }
+
+ /* ---------------- */
+
+ // Template rendering
+
+ render() {
+ return when(!this.webhook, () => html`
+ ${i18next.t('errorOccurred')}
+ `, () => html`
+ <form style="display: flex; flex-direction: column; min-width: 520px;">
+ <!-- HTTP Method & URL -->
+ <div style="display: flex; flex-direction: row; align-items: center; gap: 5px; margin-bottom: 28px;">
+ <or-mwc-input style="flex: 0;" type="${InputType.SELECT}" .value="${this.webhook.httpMethod}"
+ .options="${this.httpMethodOptions}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ this.webhook.httpMethod = ev.detail.value;
+ this.notifyWebhookUpdate();
+ }}"
+ ></or-mwc-input>
+ <or-mwc-input style="flex: 1;" type="${InputType.URL}" required label="${i18next.t('webUrl')}"
+ .value="${this.webhook.url}" helperPersistent
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {
+ this.webhook.url = e.detail.value;
+ this.notifyWebhookUpdate();
+ }}"></or-mwc-input>
+ </div>
+ <!-- Headers -->
+ <div style="display: flex; flex-direction: column; gap: 5px; margin-bottom: 28px;">
+ <span>Headers</span>
+ ${when(this.loading, () => html`
+ ${this.getHeadersTemplate(this.webhook.headers!, true)}
+ `, () => html`
+ ${this.getHeadersTemplate(this.webhook.headers!, false)}
+ `)}
+ <or-mwc-input type="${InputType.BUTTON}" icon="plus" label="${i18next.t('addRequestHeader')}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ if ((this.webhook.headers ? this.webhook.headers[''] : undefined) != undefined) {
+ this.webhook.headers![''].push('');
+ } else {
+ this.webhook.headers![''] = [''];
+ }
+ this.reloadHeaders();
+ }}"></or-mwc-input>
+ </div>
+ <!-- Authorization -->
+ <div style="display: flex; flex-direction: column; gap: 10px; margin-bottom: ${this.webhook.oAuthGrant || this.webhook.usernamePassword ? '28px' : '0'};">
+ <or-mwc-input type="${InputType.SWITCH}" fullwidth label="${i18next.t('requiresAuthorization')}"
+ .value="${this.webhook.oAuthGrant || this.webhook.usernamePassword}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ this.webhook.usernamePassword = ev.detail.value ? {
+ username: 'admin',
+ password: 'secret'
+ } : undefined;
+ this.notifyWebhookUpdate();
+ }}"></or-mwc-input>
+ ${when(this.webhook.oAuthGrant || this.webhook.usernamePassword, () => {
+ const values: string[] = Array.from(this.authMethodOptions.values());
+ return html`
+ <or-mwc-input type="${InputType.SELECT}" label="${i18next.t('method')}"
+ .value="${this.getAuthMethod(this.webhook)}"
+ .options="${values}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ const entry = [...this.authMethodOptions.entries()].find((entry) => entry[1] == ev.detail.value);
+ this.webhook.oAuthGrant = this.getOAuthGrant(entry![0]);
+ this.notifyWebhookUpdate();
+ }}"></or-mwc-input>
+ ${this.getAuthSettingsTemplate(this.webhook)}
+ `
+ })}
+ </div>
+ <!-- Payload -->
+ <div style="display: flex; flex-direction: column; gap: 5px;">
+ ${when(this.webhook.httpMethod != HTTPMethod.GET && this.webhook.httpMethod != HTTPMethod.DELETE, () => html`
+ <or-mwc-input type="${InputType.SWITCH}" fullwidth label="${i18next.t('includeBodyInRequest')}"
+ .value="${this.webhook.payload != undefined}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ this.webhook.payload = ev.detail.value ? JSON.stringify({
+ rule: "%RULESET_NAME%",
+ assets: "%TRIGGER_ASSETS%"
+ }, null, 4) : undefined;
+ this.notifyWebhookUpdate();
+ }}"
+ ></or-mwc-input>
+ ${when(this.webhook.payload != undefined, () => {
+ return html`
+ <or-mwc-input type="${InputType.TEXTAREA}" .value="${this.webhook.payload}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ this.webhook.payload = ev.detail.value;
+ this.notifyWebhookUpdate();
+ }}"></or-mwc-input>
+ `
+ })}
+ `)}
+ </div>
+ </form>
+ `)
+ }
+
+ getHeadersTemplate(headers: { [p: string]: string[] }, loading: boolean) {
+ return Object.keys(this.webhook.headers!)
+ .sort((a, b) => -(a.localeCompare(b)))
+ .map((key, keyIndex, keys) => {
+ const values: string[] = this.webhook.headers![key];
+ return values.map((value, valueIndex) => html`
+ <div style="display: flex; gap: 5px;">
+ <or-mwc-input type="${InputType.TEXT}" label="${i18next.t('header')}" value="${key}"
+ style="flex: 1;" .disabled="${loading}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ values.length > 0 ? values.splice(valueIndex, 1) : delete this.webhook.headers![key];
+ const newValues = this.webhook.headers![ev.detail.value];
+ if (newValues && newValues.length > 0) {
+ newValues.push(value);
+ } else {
+ this.webhook.headers![ev.detail.value] = [value]
+ }
+ this.reloadHeaders();
+ }}"
+ ></or-mwc-input>
+ <or-mwc-input type="${InputType.TEXT}" label="${i18next.t('value')}" value="${value}"
+ style="flex: 1;" .disabled="${loading}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ this.webhook.headers![key][valueIndex] = ev.detail.value;
+ this.notifyWebhookUpdate();
+ }}"
+ ></or-mwc-input>
+ <or-mwc-input type="${InputType.BUTTON}" icon="delete" .disabled="${loading}"
+ @or-mwc-input-changed="${() => {
+ values.splice(valueIndex, 1);
+ this.reloadHeaders();
+ }}"></or-mwc-input>
+ </div>
+ `)
+ })
+ }
+
+ getAuthSettingsTemplate(webhook: Webhook): TemplateResult | undefined {
+ const authGrant = webhook.oAuthGrant;
+ if (authGrant == undefined) {
+ return html`
+ <div style="display: flex; flex-direction: column; gap: 10px;">
+ <or-mwc-input type="${InputType.TEXT}" label="${i18next.t('username')}"
+ .value="${webhook.usernamePassword?.username}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ if (!this.webhook.usernamePassword) {
+ this.webhook.usernamePassword = {};
+ }
+ this.webhook.usernamePassword.username = ev.detail.value;
+ this.notifyWebhookUpdate();
+ }}"></or-mwc-input>
+ <or-mwc-input type="${InputType.TEXT}" label="${i18next.t('password')}"
+ .value="${this.webhook.usernamePassword?.password}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ if (!this.webhook.usernamePassword) {
+ this.webhook.usernamePassword = {};
+ }
+ this.webhook.usernamePassword.password = ev.detail.value;
+ this.notifyWebhookUpdate();
+ }}"></or-mwc-input>
+ </div>
+ `
+ } else {
+ return html`
+ <div style="display: flex; flex-direction: column; gap: 10px;">
+ <div style="display: flex; flex-direction: row; align-items: center; gap: 5px;">
+ <or-mwc-input style="flex: 1;" type="${InputType.URL}" required
+ label="${i18next.t('tokenUrl')}" .value="${authGrant.tokenEndpointUri}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ authGrant.tokenEndpointUri = ev.detail.value;
+ this.notifyWebhookUpdate();
+ }}"></or-mwc-input>
+ </div>
+ ${when(authGrant.grant_type != undefined, () => {
+ switch (authGrant.grant_type) {
+ case "client_credentials": {
+ const grant = authGrant as OAuthClientCredentialsGrant;
+ return html`
+ <or-mwc-input type="${InputType.TEXT}" label="${i18next.t('clientId')}"
+ .value="${grant.client_id}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ grant.client_id = ev.detail.value;
+ this.notifyWebhookUpdate();
+ }}"></or-mwc-input>
+ <or-mwc-input type="${InputType.PASSWORD}" label="${i18next.t('clientSecret')}"
+ .value="${grant.client_secret}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ grant.client_secret = ev.detail.value;
+ this.notifyWebhookUpdate();
+ }}"></or-mwc-input>
+ `;
+ }
+ case "password": {
+ const grant = authGrant as OAuthPasswordGrant;
+ return html`
+ <or-mwc-input type="${InputType.TEXT}" label="${i18next.t('username')}"
+ .value="${grant.username}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ grant.username = ev.detail.value;
+ this.notifyWebhookUpdate();
+ }}"></or-mwc-input>
+ <or-mwc-input type="${InputType.TEXT}" label="${i18next.t('password')}"
+ .value="${grant.password}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ grant.password = ev.detail.value;
+ this.notifyWebhookUpdate();
+ }}"></or-mwc-input>
+ `
+ }
+ default:
+ return html`${i18next.t('errorOccurred')}`
+ }
+ })}
+ </div>
+ `
+ }
+ }
+}
diff --git a/ui/component/or-rules/src/json-viewer/modals/or-rule-webhook-modal.ts b/ui/component/or-rules/src/json-viewer/modals/or-rule-webhook-modal.ts
new file mode 100644
index 000000000..33c23bd23
--- /dev/null
+++ b/ui/component/or-rules/src/json-viewer/modals/or-rule-webhook-modal.ts
@@ -0,0 +1,77 @@
+import {RuleActionWebhook} from "@openremote/model";
+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
+import {DialogAction, OrMwcDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
+import {i18next} from "@openremote/or-translate";
+import {html, LitElement, PropertyValues} from "lit";
+import {customElement, property} from "lit/decorators.js";
+
+@customElement("or-rule-webhook-modal")
+export class OrRuleWebhookModal extends LitElement {
+
+ @property({type: Object})
+ protected action!: RuleActionWebhook;
+
+ @property({type: String})
+ public title: string = i18next.t('message');
+
+ constructor() {
+ super();
+ }
+
+ /* ----------------------- */
+
+ firstUpdated(changedProperties: PropertyValues) {
+ if (changedProperties.has("action")) {
+ this.renderDialogHTML(this.action);
+ }
+ }
+
+ renderDialogHTML(action: RuleActionWebhook) {
+ const dialog: OrMwcDialog = this.shadowRoot!.getElementById("webhook-modal") as OrMwcDialog;
+ if (!this.shadowRoot) return
+
+ const slot: HTMLSlotElement | null = this.shadowRoot.querySelector('.webhook-form-slot');
+ if (dialog && slot) {
+ let container = document.createElement("div");
+ slot.assignedNodes({flatten: true}).forEach((child) => {
+ if (child instanceof HTMLElement) {
+ container.appendChild(child);
+ }
+ });
+ dialog.content = html`${container}`;
+ dialog.dismissAction = null;
+ this.requestUpdate();
+ }
+ }
+
+ closeForm(event: OrInputChangedEvent) {
+ const dialog: OrMwcDialog = this.shadowRoot!.host as OrMwcDialog;
+ dialog.close();
+ }
+
+ render() {
+ if (!this.action) {
+ return html`${i18next.t('errorOccurred')}`;
+ }
+ const webhookModalActions: DialogAction[] = [
+ {
+ actionName: "", content: html`
+ <or-mwc-input .type="${InputType.BUTTON}" .label="${i18next.t("ok")}"
+ @or-mwc-input-changed="${this.closeForm}"></or-mwc-input>`
+ }
+ ];
+ const webhookModalOpen = () => {
+ const dialog: OrMwcDialog = this.shadowRoot!.getElementById("webhook-modal") as OrMwcDialog;
+ if (dialog) {
+ dialog.open();
+ }
+ };
+ return html`
+ <or-mwc-input type="${InputType.BUTTON}" label="${i18next.t('message')}"
+ @or-mwc-input-changed="${webhookModalOpen}"></or-mwc-input>
+ <or-mwc-dialog id="webhook-modal" heading="${this.title}" .actions="${webhookModalActions}"></or-mwc-dialog>
+ <slot class="webhook-form-slot"></slot>
+ `
+ }
+
+}
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-action-webhook.ts b/ui/component/or-rules/src/json-viewer/or-rule-action-webhook.ts
new file mode 100644
index 000000000..d77fff7dc
--- /dev/null
+++ b/ui/component/or-rules/src/json-viewer/or-rule-action-webhook.ts
@@ -0,0 +1,48 @@
+import { JsonRule, RuleActionWebhook } from "@openremote/model";
+import {css, html, LitElement } from "lit";
+import { customElement, property } from "lit/decorators.js";
+import "./modals/or-rule-webhook-modal";
+import "./forms/or-rule-form-webhook";
+
+// language=CSS
+const style = css`
+ :host {
+ height: 100%;
+ margin: 2px 3px auto 0;
+ }
+
+ :host > * {
+ margin: 0 3px 6px;
+ }
+
+ .min-width {
+ min-width: 200px;
+ }
+`;
+
+@customElement("or-rule-action-webhook")
+export class OrRuleActionWebhook extends LitElement {
+
+ static get styles() {
+ return style;
+ }
+
+ @property({type: Object, attribute: false})
+ public rule!: JsonRule;
+
+ @property({type: Object, attribute: false})
+ public action!: RuleActionWebhook;
+
+
+ /* ---------------------- */
+
+ render() {
+ return html`
+ <div style="display: flex; align-items: center; height: 100%;">
+ <or-rule-webhook-modal .action="${this.action}">
+ <or-rule-form-webhook .webhook="${this.action.webhook}"></or-rule-form-webhook>
+ </or-rule-webhook-modal>
+ </div>
+ `
+ }
+}
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
index 0aac905c0..8a7003cec 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
@@ -325,6 +325,11 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements
case "notification":
// TODO: validate notification rule action
break;
+ case "webhook":
+ if(!action.webhook?.url || !action.webhook.httpMethod) {
+ return false;
+ }
+ break;
case "update-attribute":
if (!action.attributeName) {
return false;
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts
index 8c64b36d3..60edafca3 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts
@@ -5,13 +5,15 @@ import "./or-rule-asset-query";
import {ActionType, getAssetTypeFromQuery, RulesConfig} from "../index";
import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";
import {
+ AssetModelUtil,
AssetTypeInfo,
+ HTTPMethod,
JsonRule,
RuleActionNotification,
RuleActionUnion,
+ RuleActionWebhook,
RuleRecurrence,
- WellknownAssets,
- AssetModelUtil
+ WellknownAssets
} from "@openremote/model";
import i18next from "i18next";
import {InputType} from "@openremote/or-mwc-components/or-mwc-input";
@@ -20,27 +22,30 @@ import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
import {Util} from "@openremote/core";
import "./or-rule-action-attribute";
import "./or-rule-action-notification";
+import "./or-rule-action-webhook";
import {translate} from "@openremote/or-translate";
const NOTIFICATION_COLOR = "4B87EA";
const WAIT_COLOR = "EACC54";
-function getActionTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInfo[]): ListItem[] {
+function getActionTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInfo[]): (ListItem | null)[] {
let addAssetTypes = true;
let addWait = true;
let addNotification = true;
let addPushNotification = true;
+ let addWebhook = true;
if (config && config.controls && config.controls.allowedActionTypes) {
addAssetTypes = config.controls.allowedActionTypes.indexOf(ActionType.ATTRIBUTE) >= 0;
addWait = config.controls.allowedActionTypes.indexOf(ActionType.WAIT) >= 0;
addNotification = config.controls.allowedActionTypes.indexOf(ActionType.EMAIL) >= 0;
addPushNotification = config.controls.allowedActionTypes.indexOf(ActionType.PUSH_NOTIFICATION) >= 0;
+ addWebhook = config.controls.allowedActionTypes.indexOf(ActionType.WEBHOOK) >= 0;
}
- const menu: ListItem[] = [];
+ const menu: (ListItem | null)[] = [];
if (addAssetTypes && assetInfos) {
menu.push(...assetInfos.filter((assetInfo) => assetInfo.assetDescriptor!.descriptorType !== "agent").map((assetTypeInfo) => {
@@ -58,6 +63,9 @@ function getActionTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInfo[]):
}));
}
+ menu.sort(Util.sortByString((listItem) => listItem?.value!));
+ menu.push(null); // divider
+
if (addNotification) {
menu.push({
text: i18next.t("email"),
@@ -85,7 +93,14 @@ function getActionTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInfo[]):
} as ListItem);
}
- menu.sort(Util.sortByString((listItem) => listItem.value!));
+ if (addWebhook) {
+ menu.push({
+ text: i18next.t("webhook"),
+ icon: "webhook",
+ value: ActionType.WEBHOOK,
+ styleMap: {"--or-icon-fill": "#" + NOTIFICATION_COLOR}
+ })
+ }
return menu;
}
@@ -282,6 +297,10 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
buttonIcon = "timer";
buttonColor = WAIT_COLOR;
break;
+ case ActionType.WEBHOOK:
+ buttonIcon = "webhook";
+ buttonColor = NOTIFICATION_COLOR;
+ break;
case "notification":
action = action as RuleActionNotification
if (type === "push") {
@@ -330,6 +349,9 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
case ActionType.EMAIL:
template = html`<or-rule-action-notification id="email-notification" .rule="${this.rule}" .action="${action}" .actionType="${ActionType.EMAIL}" .config="${this.config}" .assetInfos="${this.assetInfos}" .readonly="${this.readonly}"></or-rule-action-notification>`;
break;
+ case ActionType.WEBHOOK:
+ template = html`<or-rule-action-webhook .rule="${this.rule}" .action="${action}" .actionType="${ActionType.WEBHOOK}"></or-rule-action-webhook>`;
+ break;
default:
template = html`<or-rule-action-attribute .action="${action}" .targetTypeMap="${this.targetTypeMap}" .config="${this.config}" .assetInfos="${this.assetInfos}" .readonly="${this.readonly}"></or-rule-action-attribute>`;
break;
@@ -377,6 +399,9 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
switch (action.action) {
case "wait":
break;
+ case "webhook":
+ return action.action;
+ break;
case "notification":
const type = action.notification && action.notification.message && action.notification.message.type ? action.notification.message.type : action.action;
return type;
@@ -428,6 +453,8 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
case "wait":
action.millis = undefined;
break;
+ case "webhook":
+ break;
case "write-attribute":
action.value = undefined;
action.attributeName = undefined;
@@ -446,6 +473,16 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
if (value === ActionType.WAIT) {
action.action = "wait";
+ } else if (value == ActionType.WEBHOOK) {
+ action = action as RuleActionWebhook;
+ action.action = "webhook";
+ action.webhook = {
+ httpMethod: HTTPMethod.POST,
+ payload: JSON.stringify({
+ rule: "%RULESET_NAME%",
+ assets: "%TRIGGER_ASSETS%"
+ }, null, 4)
+ };
} else if (value === ActionType.EMAIL) {
action = action as RuleActionNotification;
action.action = "notification";