diff options
Diffstat (limited to 'src/main/java/org/traccar/notification')
5 files changed, 115 insertions, 215 deletions
diff --git a/src/main/java/org/traccar/notification/EventForwarder.java b/src/main/java/org/traccar/notification/EventForwarder.java deleted file mode 100644 index c908fedbd..000000000 --- a/src/main/java/org/traccar/notification/EventForwarder.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2016 - 2020 Anton Tananaev (anton@traccar.org) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.traccar.notification; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.traccar.Context; -import org.traccar.config.Keys; -import org.traccar.model.Device; -import org.traccar.model.Event; -import org.traccar.model.Geofence; -import org.traccar.model.Maintenance; -import org.traccar.model.Position; - -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.InvocationCallback; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -public class EventForwarder { - - private static final Logger LOGGER = LoggerFactory.getLogger(EventForwarder.class); - - private final String url; - private final String header; - - public EventForwarder() { - url = Context.getConfig().getString(Keys.EVENT_FORWARD_URL); - header = Context.getConfig().getString(Keys.EVENT_FORWARD_HEADERS); - } - - private static final String KEY_POSITION = "position"; - private static final String KEY_EVENT = "event"; - private static final String KEY_GEOFENCE = "geofence"; - private static final String KEY_DEVICE = "device"; - private static final String KEY_MAINTENANCE = "maintenance"; - private static final String KEY_USERS = "users"; - - public final void forwardEvent(Event event, Position position, Set<Long> users) { - - Invocation.Builder requestBuilder = Context.getClient().target(url).request(); - - if (header != null && !header.isEmpty()) { - for (String line: header.split("\\r?\\n")) { - String[] values = line.split(":", 2); - requestBuilder.header(values[0].trim(), values[1].trim()); - } - } - - LOGGER.debug("Event forwarding initiated"); - requestBuilder.async().post( - Entity.json(preparePayload(event, position, users)), new InvocationCallback<Object>() { - @Override - public void completed(Object o) { - LOGGER.debug("Event forwarding succeeded"); - } - - @Override - public void failed(Throwable throwable) { - LOGGER.warn("Event forwarding failed", throwable); - } - }); - } - - protected Map<String, Object> preparePayload(Event event, Position position, Set<Long> users) { - Map<String, Object> data = new HashMap<>(); - data.put(KEY_EVENT, event); - if (position != null) { - data.put(KEY_POSITION, position); - } - Device device = Context.getIdentityManager().getById(event.getDeviceId()); - if (device != null) { - data.put(KEY_DEVICE, device); - } - if (event.getGeofenceId() != 0) { - Geofence geofence = Context.getGeofenceManager().getById(event.getGeofenceId()); - if (geofence != null) { - data.put(KEY_GEOFENCE, geofence); - } - } - if (event.getMaintenanceId() != 0) { - Maintenance maintenance = Context.getMaintenancesManager().getById(event.getMaintenanceId()); - if (maintenance != null) { - data.put(KEY_MAINTENANCE, maintenance); - } - } - data.put(KEY_USERS, Context.getUsersManager().getItems(users)); - return data; - } - -} diff --git a/src/main/java/org/traccar/notification/NotificationFormatter.java b/src/main/java/org/traccar/notification/NotificationFormatter.java index 9a6723a71..9ee3b97b6 100644 --- a/src/main/java/org/traccar/notification/NotificationFormatter.java +++ b/src/main/java/org/traccar/notification/NotificationFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 - 2021 Anton Tananaev (anton@traccar.org) + * Copyright 2016 - 2022 Anton Tananaev (anton@traccar.org) * Copyright 2017 - 2018 Andrey Kunitsyn (andrey@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,50 +17,59 @@ package org.traccar.notification; import org.apache.velocity.VelocityContext; -import org.traccar.Context; +import org.traccar.helper.model.UserUtil; import org.traccar.model.Device; import org.traccar.model.Event; +import org.traccar.model.Geofence; +import org.traccar.model.Maintenance; import org.traccar.model.Position; +import org.traccar.model.Server; import org.traccar.model.User; -import org.traccar.reports.ReportUtils; +import org.traccar.session.cache.CacheManager; -public final class NotificationFormatter { +import javax.inject.Inject; +import javax.inject.Singleton; - private NotificationFormatter() { +@Singleton +public class NotificationFormatter { + + private final CacheManager cacheManager; + private final TextTemplateFormatter textTemplateFormatter; + + @Inject + public NotificationFormatter( + CacheManager cacheManager, TextTemplateFormatter textTemplateFormatter) { + this.cacheManager = cacheManager; + this.textTemplateFormatter = textTemplateFormatter; } - public static VelocityContext prepareContext(long userId, Event event, Position position) { + public NotificationMessage formatMessage(User user, Event event, Position position, String templatePath) { - User user = Context.getPermissionsManager().getUser(userId); - Device device = Context.getIdentityManager().getById(event.getDeviceId()); + Server server = cacheManager.getServer(); + Device device = cacheManager.getObject(Device.class, event.getDeviceId()); - VelocityContext velocityContext = TextTemplateFormatter.prepareContext(user); + VelocityContext velocityContext = textTemplateFormatter.prepareContext(server, user); velocityContext.put("device", device); velocityContext.put("event", event); if (position != null) { velocityContext.put("position", position); - velocityContext.put("speedUnit", ReportUtils.getSpeedUnit(userId)); - velocityContext.put("distanceUnit", ReportUtils.getDistanceUnit(userId)); - velocityContext.put("volumeUnit", ReportUtils.getVolumeUnit(userId)); + velocityContext.put("speedUnit", UserUtil.getSpeedUnit(server, user)); + velocityContext.put("distanceUnit", UserUtil.getDistanceUnit(server, user)); + velocityContext.put("volumeUnit", UserUtil.getVolumeUnit(server, user)); } if (event.getGeofenceId() != 0) { - velocityContext.put("geofence", Context.getGeofenceManager().getById(event.getGeofenceId())); + velocityContext.put("geofence", cacheManager.getObject(Geofence.class, event.getGeofenceId())); } if (event.getMaintenanceId() != 0) { - velocityContext.put("maintenance", Context.getMaintenancesManager().getById(event.getMaintenanceId())); + velocityContext.put("maintenance", cacheManager.getObject(Maintenance.class, event.getMaintenanceId())); } String driverUniqueId = event.getString(Position.KEY_DRIVER_UNIQUE_ID); if (driverUniqueId != null) { - velocityContext.put("driver", Context.getDriversManager().getDriverByUniqueId(driverUniqueId)); + velocityContext.put("driver", cacheManager.findDriverByUniqueId(device.getId(), driverUniqueId)); } - return velocityContext; - } - - public static NotificationMessage formatMessage(long userId, Event event, Position position, String templatePath) { - VelocityContext velocityContext = prepareContext(userId, event, position); - return TextTemplateFormatter.formatMessage(velocityContext, event.getType(), templatePath); + return textTemplateFormatter.formatMessage(velocityContext, event.getType(), templatePath); } } diff --git a/src/main/java/org/traccar/notification/NotificatorManager.java b/src/main/java/org/traccar/notification/NotificatorManager.java index dfd8cd3d6..1d9f4f423 100644 --- a/src/main/java/org/traccar/notification/NotificatorManager.java +++ b/src/main/java/org/traccar/notification/NotificatorManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 - 2020 Anton Tananaev (anton@traccar.org) + * Copyright 2018 - 2022 Anton Tananaev (anton@traccar.org) * Copyright 2018 Andrey Kunitsyn (andrey@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,87 +16,71 @@ */ package org.traccar.notification; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - +import com.google.inject.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.traccar.Context; +import org.traccar.config.Config; +import org.traccar.config.Keys; import org.traccar.model.Typed; +import org.traccar.notificators.Notificator; import org.traccar.notificators.NotificatorFirebase; import org.traccar.notificators.NotificatorMail; import org.traccar.notificators.NotificatorNull; -import org.traccar.notificators.Notificator; +import org.traccar.notificators.NotificatorPushover; import org.traccar.notificators.NotificatorSms; +import org.traccar.notificators.NotificatorTelegram; import org.traccar.notificators.NotificatorTraccar; import org.traccar.notificators.NotificatorWeb; -import org.traccar.notificators.NotificatorTelegram; -import org.traccar.notificators.NotificatorPushover; -public final class NotificatorManager { +import javax.inject.Inject; +import javax.inject.Singleton; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +@Singleton +public class NotificatorManager { private static final Logger LOGGER = LoggerFactory.getLogger(NotificatorManager.class); - private static final Notificator NULL_NOTIFICATOR = new NotificatorNull(); + private static final Map<String, Class<? extends Notificator>> NOTIFICATORS_ALL = Map.of( + "web", NotificatorWeb.class, + "mail", NotificatorMail.class, + "sms", NotificatorSms.class, + "firebase", NotificatorFirebase.class, + "traccar", NotificatorTraccar.class, + "telegram", NotificatorTelegram.class, + "pushover", NotificatorPushover.class); - private final Map<String, Notificator> notificators = new HashMap<>(); + private final Injector injector; - public NotificatorManager() { - final String[] types = Context.getConfig().getString("notificator.types", "").split(","); - for (String type : types) { - String defaultNotificator = ""; - switch (type) { - case "web": - defaultNotificator = NotificatorWeb.class.getCanonicalName(); - break; - case "mail": - defaultNotificator = NotificatorMail.class.getCanonicalName(); - break; - case "sms": - defaultNotificator = NotificatorSms.class.getCanonicalName(); - break; - case "firebase": - defaultNotificator = NotificatorFirebase.class.getCanonicalName(); - break; - case "traccar": - defaultNotificator = NotificatorTraccar.class.getCanonicalName(); - break; - case "telegram": - defaultNotificator = NotificatorTelegram.class.getCanonicalName(); - break; - case "pushover": - defaultNotificator = NotificatorPushover.class.getCanonicalName(); - break; - default: - break; - } - final String className = Context.getConfig() - .getString("notificator." + type + ".class", defaultNotificator); - try { - notificators.put(type, (Notificator) Class.forName(className).newInstance()); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { - LOGGER.warn("Unable to load notificator class for " + type + " " + className + " " + e.getMessage()); - } + private final Set<String> types = new HashSet<>(); + + @Inject + public NotificatorManager(Injector injector, Config config) { + this.injector = injector; + String types = config.getString(Keys.NOTIFICATOR_TYPES); + if (types != null) { + this.types.addAll(Arrays.asList(types.split(","))); } } public Notificator getNotificator(String type) { - final Notificator notificator = notificators.get(type); - if (notificator == null) { - LOGGER.warn("No notificator configured for type : " + type); - return NULL_NOTIFICATOR; + var clazz = NOTIFICATORS_ALL.get(type); + if (clazz != null) { + var notificator = injector.getInstance(clazz); + if (notificator != null) { + return notificator; + } } - return notificator; + LOGGER.warn("Failed to get notificator {}", type); + return new NotificatorNull(); } public Set<Typed> getAllNotificatorTypes() { - Set<Typed> result = new HashSet<>(); - for (String notificator : notificators.keySet()) { - result.add(new Typed(notificator)); - } - return result; + return types.stream().map(Typed::new).collect(Collectors.toUnmodifiableSet()); } } diff --git a/src/main/java/org/traccar/notification/PropertiesProvider.java b/src/main/java/org/traccar/notification/PropertiesProvider.java index f0078feef..91887b5d4 100644 --- a/src/main/java/org/traccar/notification/PropertiesProvider.java +++ b/src/main/java/org/traccar/notification/PropertiesProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 Anton Tananaev (anton@traccar.org) + * Copyright 2016 - 2022 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package org.traccar.notification; import org.traccar.config.Config; +import org.traccar.config.ConfigKey; import org.traccar.model.ExtendedModel; public class PropertiesProvider { @@ -32,36 +33,29 @@ public class PropertiesProvider { this.extendedModel = extendedModel; } - public String getString(String key) { + public String getString(ConfigKey<String> key) { if (config != null) { return config.getString(key); } else { - return extendedModel.getString(key); + String result = extendedModel.getString(key.getKey()); + return result != null ? result : key.getDefaultValue(); } } - public String getString(String key, String defaultValue) { - String value = getString(key); - if (value == null) { - value = defaultValue; - } - return value; - } - - public int getInteger(String key, int defaultValue) { + public int getInteger(ConfigKey<Integer> key) { if (config != null) { - return config.getInteger(key, defaultValue); + return config.getInteger(key); } else { - Object result = extendedModel.getAttributes().get(key); + Object result = extendedModel.getAttributes().get(key.getKey()); if (result != null) { return result instanceof String ? Integer.parseInt((String) result) : (Integer) result; } else { - return defaultValue; + return key.getDefaultValue(); } } } - public Boolean getBoolean(String key) { + public Boolean getBoolean(ConfigKey<Boolean> key) { if (config != null) { if (config.hasKey(key)) { return config.getBoolean(key); @@ -69,7 +63,7 @@ public class PropertiesProvider { return null; } } else { - Object result = extendedModel.getAttributes().get(key); + Object result = extendedModel.getAttributes().get(key.getKey()); if (result != null) { return result instanceof String ? Boolean.valueOf((String) result) : (Boolean) result; } else { diff --git a/src/main/java/org/traccar/notification/TextTemplateFormatter.java b/src/main/java/org/traccar/notification/TextTemplateFormatter.java index b7058c824..444f4a7c2 100644 --- a/src/main/java/org/traccar/notification/TextTemplateFormatter.java +++ b/src/main/java/org/traccar/notification/TextTemplateFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright 2021 Anton Tananaev (anton@traccar.org) + * Copyright 2021 - 2022 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,37 +17,56 @@ package org.traccar.notification; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.tools.generic.DateTool; import org.apache.velocity.tools.generic.NumberTool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.traccar.Context; +import org.traccar.api.signature.TokenManager; +import org.traccar.helper.model.UserUtil; +import org.traccar.model.Server; import org.traccar.model.User; -import org.traccar.reports.ReportUtils; +import org.traccar.storage.StorageException; +import javax.inject.Inject; +import javax.inject.Singleton; +import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; +import java.security.GeneralSecurityException; import java.util.Locale; -public final class TextTemplateFormatter { +@Singleton +public class TextTemplateFormatter { private static final Logger LOGGER = LoggerFactory.getLogger(TextTemplateFormatter.class); - private TextTemplateFormatter() { + private final VelocityEngine velocityEngine; + private final TokenManager tokenManager; + + @Inject + public TextTemplateFormatter(VelocityEngine velocityEngine, TokenManager tokenManager) { + this.velocityEngine = velocityEngine; + this.tokenManager = tokenManager; } - public static VelocityContext prepareContext(User user) { + public VelocityContext prepareContext(Server server, User user) { VelocityContext velocityContext = new VelocityContext(); if (user != null) { velocityContext.put("user", user); - velocityContext.put("timezone", ReportUtils.getTimezone(user.getId())); + velocityContext.put("timezone", UserUtil.getTimezone(server, user)); + try { + velocityContext.put("token", tokenManager.generateToken(user.getId())); + } catch (IOException | GeneralSecurityException | StorageException e) { + LOGGER.warn("Token generation failed", e); + } } - velocityContext.put("webUrl", Context.getVelocityEngine().getProperty("web.url")); + velocityContext.put("webUrl", velocityEngine.getProperty("web.url")); velocityContext.put("dateTool", new DateTool()); velocityContext.put("numberTool", new NumberTool()); velocityContext.put("locale", Locale.getDefault()); @@ -55,23 +74,23 @@ public final class TextTemplateFormatter { return velocityContext; } - public static Template getTemplate(String name, String path) { + public Template getTemplate(String name, String path) { String templateFilePath; Template template; try { templateFilePath = Paths.get(path, name + ".vm").toString(); - template = Context.getVelocityEngine().getTemplate(templateFilePath, StandardCharsets.UTF_8.name()); + template = velocityEngine.getTemplate(templateFilePath, StandardCharsets.UTF_8.name()); } catch (ResourceNotFoundException error) { LOGGER.warn("Notification template error", error); templateFilePath = Paths.get(path, "unknown.vm").toString(); - template = Context.getVelocityEngine().getTemplate(templateFilePath, StandardCharsets.UTF_8.name()); + template = velocityEngine.getTemplate(templateFilePath, StandardCharsets.UTF_8.name()); } return template; } - public static NotificationMessage formatMessage(VelocityContext velocityContext, String name, String templatePath) { + public NotificationMessage formatMessage(VelocityContext velocityContext, String name, String templatePath) { StringWriter writer = new StringWriter(); getTemplate(name, templatePath).merge(velocityContext, writer); return new NotificationMessage((String) velocityContext.get("subject"), writer.toString()); |