diff --git a/checkstyle.xml b/checkstyle.xml index 14cfd1d130a..9d0314b06ed 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -98,7 +98,6 @@ - diff --git a/debug.xml b/debug.xml index bf8f8e2b5b9..039f5a7a90e 100644 --- a/debug.xml +++ b/debug.xml @@ -52,6 +52,21 @@ true + + + @@ -280,6 +295,27 @@ DELETE FROM device_geofence WHERE deviceId = :deviceId AND geofenceId = :geofenceId; + + SELECT * FROM notifications; + + + + INSERT INTO notifications (userId, type, attributes) + VALUES (:userId, :type, :attributes); + + + + UPDATE notifications SET + userId = :userId, + type = :type, + attributes = :attributes + WHERE id = :id; + + + + DELETE FROM notifications WHERE id = :id; + + 5001 diff --git a/pom.xml b/pom.xml index eb1ac20de7f..0df84a4aa67 100644 --- a/pom.xml +++ b/pom.xml @@ -112,6 +112,12 @@ liquibase-core 3.4.2 + + javax.mail + mail + 1.4.7 + + diff --git a/schema/changelog-3.6.xml b/schema/changelog-3.6.xml index 13d4cae6030..a17b68e476b 100644 --- a/schema/changelog-3.6.xml +++ b/schema/changelog-3.6.xml @@ -90,5 +90,28 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/setup/unix/traccar.xml b/setup/unix/traccar.xml index b7537643449..890229d0082 100644 --- a/setup/unix/traccar.xml +++ b/setup/unix/traccar.xml @@ -28,6 +28,20 @@ true + + org.h2.Driver @@ -252,6 +266,27 @@ DELETE FROM device_geofence WHERE deviceId = :deviceId AND geofenceId = :geofenceId; + + SELECT * FROM notifications; + + + + INSERT INTO notifications (userId, type, attributes) + VALUES (:userId, :type, :attributes); + + + + UPDATE notifications SET + userId = :userId, + type = :type, + attributes = :attributes + WHERE id = :id; + + + + DELETE FROM notifications WHERE id = :id; + + 5001 diff --git a/setup/windows/traccar.xml b/setup/windows/traccar.xml index 995b52c0d1a..0f50dc0b295 100644 --- a/setup/windows/traccar.xml +++ b/setup/windows/traccar.xml @@ -28,6 +28,20 @@ true + + org.h2.Driver @@ -252,6 +266,27 @@ DELETE FROM device_geofence WHERE deviceId = :deviceId AND geofenceId = :geofenceId; + + SELECT * FROM notifications; + + + + INSERT INTO notifications (userId, type, attributes) + VALUES (:userId, :type, :attributes); + + + + UPDATE notifications SET + userId = :userId, + type = :type, + attributes = :attributes + WHERE id = :id; + + + + DELETE FROM notifications WHERE id = :id; + + 5001 diff --git a/src/org/traccar/api/resource/DevicePermissionResource.java b/src/org/traccar/api/resource/DevicePermissionResource.java index 2ef436f11e3..7de05007494 100644 --- a/src/org/traccar/api/resource/DevicePermissionResource.java +++ b/src/org/traccar/api/resource/DevicePermissionResource.java @@ -38,7 +38,9 @@ public Response add(DevicePermission entity) throws SQLException { Context.getPermissionsManager().checkAdmin(getUserId()); Context.getDataManager().linkDevice(entity.getUserId(), entity.getDeviceId()); Context.getPermissionsManager().refresh(); - Context.getGeofenceManager().refresh(); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } return Response.ok(entity).build(); } @@ -47,7 +49,9 @@ public Response remove(DevicePermission entity) throws SQLException { Context.getPermissionsManager().checkAdmin(getUserId()); Context.getDataManager().unlinkDevice(entity.getUserId(), entity.getDeviceId()); Context.getPermissionsManager().refresh(); - Context.getGeofenceManager().refresh(); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index d6032bb1e6e..d6c53dc04d8 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -60,7 +60,9 @@ public Response add(Device entity) throws SQLException { Context.getDataManager().addDevice(entity); Context.getDataManager().linkDevice(getUserId(), entity.getId()); Context.getPermissionsManager().refresh(); - Context.getGeofenceManager().refresh(); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } return Response.ok(entity).build(); } @@ -70,6 +72,9 @@ public Response update(@PathParam("id") long id, Device entity) throws SQLExcept Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), id); Context.getDataManager().updateDevice(entity); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } return Response.ok(entity).build(); } @@ -80,7 +85,9 @@ public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkDevice(getUserId(), id); Context.getDataManager().removeDevice(id); Context.getPermissionsManager().refresh(); - Context.getGeofenceManager().refresh(); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/GroupPermissionResource.java b/src/org/traccar/api/resource/GroupPermissionResource.java index 564a379d24c..1fbf37a2b25 100644 --- a/src/org/traccar/api/resource/GroupPermissionResource.java +++ b/src/org/traccar/api/resource/GroupPermissionResource.java @@ -38,7 +38,9 @@ public Response add(GroupPermission entity) throws SQLException { Context.getPermissionsManager().checkAdmin(getUserId()); Context.getDataManager().linkGroup(entity.getUserId(), entity.getGroupId()); Context.getPermissionsManager().refresh(); - Context.getGeofenceManager().refresh(); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } return Response.ok(entity).build(); } @@ -47,7 +49,9 @@ public Response remove(GroupPermission entity) throws SQLException { Context.getPermissionsManager().checkAdmin(getUserId()); Context.getDataManager().unlinkGroup(entity.getUserId(), entity.getGroupId()); Context.getPermissionsManager().refresh(); - Context.getGeofenceManager().refresh(); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/GroupResource.java b/src/org/traccar/api/resource/GroupResource.java index dda9ab03bde..957f39ebeed 100644 --- a/src/org/traccar/api/resource/GroupResource.java +++ b/src/org/traccar/api/resource/GroupResource.java @@ -59,7 +59,9 @@ public Response add(Group entity) throws SQLException { Context.getDataManager().addGroup(entity); Context.getDataManager().linkGroup(getUserId(), entity.getId()); Context.getPermissionsManager().refresh(); - Context.getGeofenceManager().refresh(); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } return Response.ok(entity).build(); } @@ -69,6 +71,9 @@ public Response update(@PathParam("id") long id, Group entity) throws SQLExcepti Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkGroup(getUserId(), id); Context.getDataManager().updateGroup(entity); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } return Response.ok(entity).build(); } @@ -79,7 +84,9 @@ public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkGroup(getUserId(), id); Context.getDataManager().removeGroup(id); Context.getPermissionsManager().refresh(); - Context.getGeofenceManager().refresh(); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/NotificationResource.java b/src/org/traccar/api/resource/NotificationResource.java new file mode 100644 index 00000000000..236e352e1e6 --- /dev/null +++ b/src/org/traccar/api/resource/NotificationResource.java @@ -0,0 +1,44 @@ +package org.traccar.api.resource; + +import java.sql.SQLException; +import java.util.Collection; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.traccar.Context; +import org.traccar.api.BaseResource; +import org.traccar.model.Notification; + +@Path("users/notifications") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class NotificationResource extends BaseResource { + + @GET + public Collection get(@QueryParam("all") boolean all, + @QueryParam("userId") long userId) throws SQLException { + if (all) { + return Context.getNotificationManager().getAllNotifications(); + } + if (userId == 0) { + userId = getUserId(); + } + Context.getPermissionsManager().checkUser(getUserId(), userId); + return Context.getNotificationManager().getUserNotifications(userId); + } + + @POST + public Response update(Notification entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); + Context.getNotificationManager().updateNotification(entity); + return Response.ok(entity).build(); + } +} diff --git a/src/org/traccar/api/resource/UserResource.java b/src/org/traccar/api/resource/UserResource.java index 7cc4ed09abc..cfe338b567c 100644 --- a/src/org/traccar/api/resource/UserResource.java +++ b/src/org/traccar/api/resource/UserResource.java @@ -52,7 +52,12 @@ public Response add(User entity) throws SQLException { } Context.getDataManager().addUser(entity); Context.getPermissionsManager().refresh(); - Context.getGeofenceManager().refresh(); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } + if (Context.getNotificationManager() != null) { + Context.getNotificationManager().refresh(); + } return Response.ok(entity).build(); } @@ -66,7 +71,12 @@ public Response update(@PathParam("id") long id, User entity) throws SQLExceptio } Context.getDataManager().updateUser(entity); Context.getPermissionsManager().refresh(); - Context.getGeofenceManager().refresh(); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } + if (Context.getNotificationManager() != null) { + Context.getNotificationManager().refresh(); + } return Response.ok(entity).build(); } @@ -76,7 +86,12 @@ public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkUser(getUserId(), id); Context.getDataManager().removeUser(id); Context.getPermissionsManager().refresh(); - Context.getGeofenceManager().refresh(); + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refresh(); + } + if (Context.getNotificationManager() != null) { + Context.getNotificationManager().refresh(); + } return Response.noContent().build(); } diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java index 860bf1b8439..0317030230e 100644 --- a/src/org/traccar/database/DataManager.java +++ b/src/org/traccar/database/DataManager.java @@ -52,6 +52,7 @@ import org.traccar.model.Group; import org.traccar.model.GroupGeofence; import org.traccar.model.GroupPermission; +import org.traccar.model.Notification; import org.traccar.model.Position; import org.traccar.model.Server; import org.traccar.model.User; @@ -644,4 +645,27 @@ public void unlinkDeviceGeofence(long deviceId, long geofenceId) throws SQLExcep .setLong("geofenceId", geofenceId) .executeUpdate(); } + + public Collection getNotifications() throws SQLException { + return QueryBuilder.create(dataSource, getQuery("database.selectNotifications")) + .executeQuery(Notification.class); + } + + public void addNotification(Notification notification) throws SQLException { + notification.setId(QueryBuilder.create(dataSource, getQuery("database.insertNotification"), true) + .setObject(notification) + .executeUpdate()); + } + + public void updateNotification(Notification notification) throws SQLException { + QueryBuilder.create(dataSource, getQuery("database.updateNotification")) + .setObject(notification) + .executeUpdate(); + } + + public void removeNotification(Notification notification) throws SQLException { + QueryBuilder.create(dataSource, getQuery("database.deleteNotification")) + .setLong("id", notification.getId()) + .executeUpdate(); + } } diff --git a/src/org/traccar/database/NotificationManager.java b/src/org/traccar/database/NotificationManager.java index ab6b2230a26..ae91d81cca2 100644 --- a/src/org/traccar/database/NotificationManager.java +++ b/src/org/traccar/database/NotificationManager.java @@ -15,21 +15,35 @@ */ package org.traccar.database; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; import java.sql.SQLException; import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; import java.util.Set; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; import org.traccar.Context; import org.traccar.helper.Log; import org.traccar.model.Event; +import org.traccar.model.Notification; import org.traccar.model.Position; +import org.traccar.notification.NotificationMail; public class NotificationManager { private final DataManager dataManager; + private final Map> userNotifications = new HashMap<>(); + + private final ReadWriteLock notificationsLock = new ReentrantReadWriteLock(); + public NotificationManager(DataManager dataManager) { this.dataManager = dataManager; + refresh(); } public void updateEvent(Event event, Position position) { @@ -43,7 +57,15 @@ public void updateEvent(Event event, Position position) { for (Long userId : users) { if (event.getGeofenceId() == 0 || Context.getGeofenceManager() != null && Context.getGeofenceManager().checkGeofence(userId, event.getGeofenceId())) { - Context.getConnectionManager().updateEvent(userId, event, position); + Notification notification = getUserNotificationByType(userId, event.getType()); + if (notification != null) { + if (notification.getAttributes().containsKey("web")) { + Context.getConnectionManager().updateEvent(userId, event, position); + } + if (notification.getAttributes().containsKey("mail")) { + NotificationMail.sendMailAsync(userId, event, position); + } + } } } } @@ -54,4 +76,119 @@ public void updateEvents(Collection events, Position position) { updateEvent(event, position); } } + + private Set getUserNotificationsUnsafe(long userId) { + if (!userNotifications.containsKey(userId)) { + userNotifications.put(userId, new HashSet()); + } + return userNotifications.get(userId); + } + + public Set getUserNotifications(long userId) { + notificationsLock.readLock().lock(); + try { + return getUserNotificationsUnsafe(userId); + } finally { + notificationsLock.readLock().unlock(); + } + } + + public final void refresh() { + if (dataManager != null) { + try { + notificationsLock.writeLock().lock(); + try { + userNotifications.clear(); + for (Notification notification : dataManager.getNotifications()) { + getUserNotificationsUnsafe(notification.getUserId()).add(notification); + } + } finally { + notificationsLock.writeLock().unlock(); + } + } catch (SQLException error) { + Log.warning(error); + } + } + } + + public Notification getUserNotificationByType(long userId, String type) { + notificationsLock.readLock().lock(); + try { + for (Notification notification : getUserNotificationsUnsafe(userId)) { + if (notification.getType().equals(type)) { + return notification; + } + } + } finally { + notificationsLock.readLock().unlock(); + } + return null; + } + + public void updateNotification(Notification notification) { + Notification cachedNotification = getUserNotificationByType(notification.getUserId(), notification.getType()); + if (cachedNotification != null) { + if (!cachedNotification.getAttributes().equals(notification.getAttributes())) { + if (notification.getAttributes().isEmpty()) { + try { + dataManager.removeNotification(cachedNotification); + } catch (SQLException error) { + Log.warning(error); + } + notificationsLock.writeLock().lock(); + try { + getUserNotificationsUnsafe(notification.getUserId()).remove(cachedNotification); + } finally { + notificationsLock.writeLock().unlock(); + } + } else { + notificationsLock.writeLock().lock(); + try { + cachedNotification.setAttributes(notification.getAttributes()); + } finally { + notificationsLock.writeLock().unlock(); + } + try { + dataManager.updateNotification(cachedNotification); + } catch (SQLException error) { + Log.warning(error); + } + } + } else { + notification.setId(cachedNotification.getId()); + } + } else if (!notification.getAttributes().isEmpty()) { + try { + dataManager.addNotification(notification); + } catch (SQLException error) { + Log.warning(error); + } + notificationsLock.writeLock().lock(); + try { + getUserNotificationsUnsafe(notification.getUserId()).add(notification); + } finally { + notificationsLock.writeLock().unlock(); + } + } + } + + public Set getAllNotifications() { + + Set notifications = new HashSet<>(); + long id = 0; + Field[] fields = Event.class.getDeclaredFields(); + for (Field field : fields) { + if (Modifier.isStatic(field.getModifiers()) && field.getName().startsWith("TYPE_")) { + try { + Notification notification = new Notification(); + notification.setType(field.get(null).toString()); + notification.setId(id++); + notifications.add(notification); + } catch (IllegalArgumentException | IllegalAccessException error) { + Log.warning(error); + } + } + } + return notifications; + } } diff --git a/src/org/traccar/model/Notification.java b/src/org/traccar/model/Notification.java new file mode 100644 index 00000000000..0664d6a00d0 --- /dev/null +++ b/src/org/traccar/model/Notification.java @@ -0,0 +1,40 @@ +/* + * Copyright 2016 Anton Tananaev (anton.tananaev@gmail.com) + * + * 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.model; + +public class Notification extends Extensible { + + private long userId; + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + private String type; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/src/org/traccar/model/User.java b/src/org/traccar/model/User.java index 287de121c1c..aa73cfcff6d 100644 --- a/src/org/traccar/model/User.java +++ b/src/org/traccar/model/User.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 - 2015 Anton Tananaev (anton.tananaev@gmail.com) + * Copyright 2013 - 2016 Anton Tananaev (anton.tananaev@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,17 +18,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import org.traccar.helper.Hashing; -public class User { - - private long id; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } +public class User extends Extensible { private String name; diff --git a/src/org/traccar/notification/NotificationFormatter.java b/src/org/traccar/notification/NotificationFormatter.java new file mode 100644 index 00000000000..edfa70f4d4e --- /dev/null +++ b/src/org/traccar/notification/NotificationFormatter.java @@ -0,0 +1,164 @@ +/* + * Copyright 2016 Anton Tananaev (anton.tananaev@gmail.com) + * + * 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 java.util.Formatter; +import java.util.Locale; + +import org.traccar.Context; +import org.traccar.model.Device; +import org.traccar.model.Event; +import org.traccar.model.Position; + +public final class NotificationFormatter { + + private NotificationFormatter() { + } + + public static final String TITLE_TEMPLATE_TYPE_COMMAND_RESULT = "%1$s: command result received"; + public static final String MESSAGE_TEMPLATE_TYPE_COMMAND_RESULT = "Device: %1$s%n" + + "Result: %3$s%n" + + "Time: %2$tc%n"; + + public static final String TITLE_TEMPLATE_TYPE_DEVICE_ONLINE = "%1$s: online"; + public static final String MESSAGE_TEMPLATE_TYPE_DEVICE_ONLINE = "Device: %1$s%n" + + "Online%n" + + "Time: %2$tc%n"; + public static final String TITLE_TEMPLATE_TYPE_DEVICE_OFFLINE = "%1$s: offline"; + public static final String MESSAGE_TEMPLATE_TYPE_DEVICE_OFFLINE = "Device: %1$s%n" + + "Offline%n" + + "Time: %2$tc%n"; + + public static final String TITLE_TEMPLATE_TYPE_DEVICE_MOVING = "%1$s: moving"; + public static final String MESSAGE_TEMPLATE_TYPE_DEVICE_MOVING = "Device: %1$s%n" + + "Moving%n" + + "Point: http://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" + + "Time: %2$tc%n"; + public static final String TITLE_TEMPLATE_TYPE_DEVICE_STOPPED = "%1$s: stopped"; + public static final String MESSAGE_TEMPLATE_TYPE_DEVICE_STOPPED = "Device: %1$s%n" + + "Stopped%n" + + "Point: http://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" + + "Time: %2$tc%n"; + + public static final String TITLE_TEMPLATE_TYPE_DEVICE_OVERSPEED = "%1$s: exeeds the speed"; + public static final String MESSAGE_TEMPLATE_TYPE_DEVICE_OVERSPEED = "Device: %1$s%n" + + "Exeeds the speed: %5$f%n" + + "Point: http://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" + + "Time: %2$tc%n"; + + public static final String TITLE_TEMPLATE_TYPE_GEOFENCE_ENTER = "%1$s: has entered geofence"; + public static final String MESSAGE_TEMPLATE_TYPE_GEOFENCE_ENTER = "Device: %1$s%n" + + "Has entered geofence: %5$s%n" + + "Point: http://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" + + "Time: %2$tc%n"; + public static final String TITLE_TEMPLATE_TYPE_GEOFENCE_EXIT = "%1$s: has exited geofence"; + public static final String MESSAGE_TEMPLATE_TYPE_GEOFENCE_EXIT = "Device: %1$s%n" + + "Has exited geofence: %5$s%n" + + "Point: http://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" + + "Time: %2$tc%n"; + + public static String formatTitle(long userId, Event event, Position position) { + Device device = Context.getIdentityManager().getDeviceById(event.getDeviceId()); + StringBuilder stringBuilder = new StringBuilder(); + Formatter formatter = new Formatter(stringBuilder, Locale.getDefault()); + + switch (event.getType()) { + case Event.TYPE_COMMAND_RESULT : formatter.format(TITLE_TEMPLATE_TYPE_COMMAND_RESULT, device.getName()); + break; + case Event.TYPE_DEVICE_ONLINE : formatter.format(TITLE_TEMPLATE_TYPE_DEVICE_ONLINE, device.getName()); + break; + case Event.TYPE_DEVICE_OFFLINE : formatter.format(TITLE_TEMPLATE_TYPE_DEVICE_OFFLINE, device.getName()); + break; + case Event.TYPE_DEVICE_MOVING : formatter.format(TITLE_TEMPLATE_TYPE_DEVICE_MOVING, device.getName()); + break; + case Event.TYPE_DEVICE_STOPPED : formatter.format(TITLE_TEMPLATE_TYPE_DEVICE_STOPPED, device.getName()); + break; + case Event.TYPE_DEVICE_OVERSPEED: formatter.format(TITLE_TEMPLATE_TYPE_DEVICE_OVERSPEED, device.getName()); + break; + case Event.TYPE_GEOFENCE_ENTER : formatter.format(TITLE_TEMPLATE_TYPE_GEOFENCE_ENTER, device.getName()); + break; + case Event.TYPE_GEOFENCE_EXIT : formatter.format(TITLE_TEMPLATE_TYPE_GEOFENCE_EXIT, device.getName()); + break; + default : formatter.format("Unknown type"); + break; + } + String result = formatter.toString(); + formatter.close(); + return result; + } + + public static String formatMessage(long userId, Event event, Position position) { + Device device = Context.getIdentityManager().getDeviceById(event.getDeviceId()); + StringBuilder stringBuilder = new StringBuilder(); + Formatter formatter = new Formatter(stringBuilder, Locale.getDefault()); + + switch (event.getType()) { + case Event.TYPE_COMMAND_RESULT : formatter.format(MESSAGE_TEMPLATE_TYPE_COMMAND_RESULT, + device.getName(), + event.getServerTime(), + position.getAttributes().get("result")); + break; + case Event.TYPE_DEVICE_ONLINE : formatter.format(MESSAGE_TEMPLATE_TYPE_DEVICE_ONLINE, + device.getName(), + event.getServerTime()); + break; + case Event.TYPE_DEVICE_OFFLINE : formatter.format(MESSAGE_TEMPLATE_TYPE_DEVICE_OFFLINE, + device.getName(), + event.getServerTime()); + break; + case Event.TYPE_DEVICE_MOVING : formatter.format(MESSAGE_TEMPLATE_TYPE_DEVICE_MOVING, + device.getName(), + position.getFixTime(), + position.getLatitude(), + position.getLongitude()); + break; + case Event.TYPE_DEVICE_STOPPED : formatter.format(MESSAGE_TEMPLATE_TYPE_DEVICE_STOPPED, + device.getName(), + position.getFixTime(), + position.getLatitude(), + position.getLongitude()); + break; + case Event.TYPE_DEVICE_OVERSPEED: formatter.format(MESSAGE_TEMPLATE_TYPE_DEVICE_OVERSPEED, + device.getName(), + position.getFixTime(), + position.getLatitude(), + position.getLongitude(), + position.getSpeed()); + break; + case Event.TYPE_GEOFENCE_ENTER : formatter.format(MESSAGE_TEMPLATE_TYPE_GEOFENCE_ENTER, + device.getName(), + position.getFixTime(), + position.getLatitude(), + position.getLongitude(), + (Context.getGeofenceManager() != null) + ? Context.getGeofenceManager().getGeofence(event.getGeofenceId()).getName() : ""); + break; + case Event.TYPE_GEOFENCE_EXIT : formatter.format(MESSAGE_TEMPLATE_TYPE_GEOFENCE_EXIT, + device.getName(), + position.getFixTime(), + position.getLatitude(), + position.getLongitude(), + (Context.getGeofenceManager() != null) + ? Context.getGeofenceManager().getGeofence(event.getGeofenceId()).getName() : ""); + break; + default : formatter.format("Unknown type"); + break; + } + String result = formatter.toString(); + formatter.close(); + return result; + } +} diff --git a/src/org/traccar/notification/NotificationMail.java b/src/org/traccar/notification/NotificationMail.java new file mode 100644 index 00000000000..7189b531bb9 --- /dev/null +++ b/src/org/traccar/notification/NotificationMail.java @@ -0,0 +1,133 @@ +/* + * Copyright 2016 Anton Tananaev (anton.tananaev@gmail.com) + * + * 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 java.sql.SQLException; +import java.util.Properties; + +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +import org.traccar.Config; +import org.traccar.Context; +import org.traccar.database.DataManager; +import org.traccar.helper.Log; +import org.traccar.model.Event; +import org.traccar.model.Position; +import org.traccar.model.User; + +public final class NotificationMail { + + private NotificationMail() { + } + + public static void sendMailSync(long userId, Event event, Position position) { + Config config = Context.getConfig(); + DataManager dataManager = Context.getDataManager(); + + Properties mailServerProperties; + Session mailSession; + MimeMessage mailMessage; + + String from = null; + String username = null; + String password = null; + + try { + User user = dataManager.getUser(userId); + + mailServerProperties = new Properties(); + String host = config.getString("mail.smtp.host", null); + if (host != null) { + mailServerProperties.put("mail.smtp.host", host); + mailServerProperties.put("mail.smtp.port", config.getString("mail.smtp.port", "25")); + + if (config.getBoolean("mail.smtp.starttls.enable")) { + mailServerProperties.put("mail.smtp.starttls.enable", + config.getBoolean("mail.smtp.starttls.enable")); + } else if (config.getBoolean("mail.smtp.ssl.enable")) { + mailServerProperties.put("mail.smtp.socketFactory.port", + mailServerProperties.getProperty("mail.smtp.port")); + mailServerProperties.put("mail.smtp.socketFactory.class", + "javax.net.ssl.SSLSocketFactory"); + } + + mailServerProperties.put("mail.smtp.auth", config.getBoolean("mail.smtp.auth")); + username = config.getString("mail.smtp.username", null); + password = config.getString("mail.smtp.password", null); + from = config.getString("mail.smtp.from", null); + } else if (user.getAttributes().containsKey("mail.smtp.host")) { + mailServerProperties.put("mail.smtp.host", user.getAttributes().get("mail.smtp.host")); + String port = (String) user.getAttributes().get("mail.smtp.port"); + mailServerProperties.put("mail.smtp.port", (port != null) ? port : "25"); + if (user.getAttributes().containsKey("mail.smtp.starttls.enable")) { + boolean tls = Boolean.parseBoolean((String) user.getAttributes().get("mail.smtp.starttls.enable")); + mailServerProperties.put("mail.smtp.starttls.enable", tls); + } else if (user.getAttributes().containsKey("mail.smtp.ssl.enable")) { + boolean ssl = Boolean.parseBoolean((String) user.getAttributes().get("mail.smtp.ssl.enable")); + if (ssl) { + mailServerProperties.put("mail.smtp.socketFactory.port", + mailServerProperties.getProperty("mail.smtp.port")); + mailServerProperties.put("mail.smtp.socketFactory.class", + "javax.net.ssl.SSLSocketFactory"); + } + } + boolean auth = Boolean.parseBoolean((String) user.getAttributes().get("mail.smtp.auth")); + mailServerProperties.put("mail.smtp.auth", auth); + + username = (String) user.getAttributes().get("mail.smtp.username"); + password = (String) user.getAttributes().get("mail.smtp.password"); + from = (String) user.getAttributes().get("mail.smtp.from"); + } else { + return; + } + + mailSession = Session.getDefaultInstance(mailServerProperties, null); + + mailMessage = new MimeMessage(mailSession); + + if (from != null) { + mailMessage.setFrom(new InternetAddress(from)); + } + mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress( + Context.getDataManager().getUser(userId).getEmail())); + mailMessage.setSubject(NotificationFormatter.formatTitle(userId, event, position)); + mailMessage.setText(NotificationFormatter.formatMessage(userId, event, position)); + + Transport transport = mailSession.getTransport("smtp"); + transport.connect(mailServerProperties.getProperty("mail.smtp.host"), username, password); + transport.sendMessage(mailMessage, mailMessage.getAllRecipients()); + transport.close(); + + } catch (MessagingException | SQLException error) { + Log.warning(error); + } + } + + public static void sendMailAsync(final long userId, final Event event, final Position position) { + Runnable runnableSend = new Runnable() { + public void run() { + sendMailSync(userId, event, position); + } + }; + + new Thread(runnableSend).start(); + } +} diff --git a/src/org/traccar/web/WebServer.java b/src/org/traccar/web/WebServer.java index c06ee5d35d7..5527e80f3c1 100644 --- a/src/org/traccar/web/WebServer.java +++ b/src/org/traccar/web/WebServer.java @@ -41,6 +41,7 @@ import org.traccar.api.resource.DevicePermissionResource; import org.traccar.api.resource.UserResource; import org.traccar.api.resource.GroupResource; +import org.traccar.api.resource.NotificationResource; import org.traccar.api.resource.DeviceResource; import org.traccar.api.resource.PositionResource; import org.traccar.api.resource.CommandTypeResource; @@ -155,7 +156,8 @@ private void initApi() { GroupPermissionResource.class, DevicePermissionResource.class, UserResource.class, GroupResource.class, DeviceResource.class, PositionResource.class, CommandTypeResource.class, EventResource.class, GeofenceResource.class, - DeviceGeofenceResource.class, GeofencePermissionResource.class, GroupGeofenceResource.class); + DeviceGeofenceResource.class, GeofencePermissionResource.class, GroupGeofenceResource.class, + NotificationResource.class); servletHandler.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*"); handlers.addHandler(servletHandler); diff --git a/web/app/Application.js b/web/app/Application.js index dbbc7a5944e..5911579b8ef 100644 --- a/web/app/Application.js +++ b/web/app/Application.js @@ -32,7 +32,8 @@ Ext.define('Traccar.Application', { 'Attribute', 'Command', 'Event', - 'Geofence' + 'Geofence', + 'Notification' ], stores: [ @@ -52,7 +53,9 @@ Ext.define('Traccar.Application', { 'Languages', 'Events', 'Geofences', - 'AllGeofences' + 'AllGeofences', + 'Notifications', + 'AllNotifications' ], controllers: [ diff --git a/web/app/controller/Root.js b/web/app/controller/Root.js index da3e3a2a9ca..ba23b90bf8b 100644 --- a/web/app/controller/Root.js +++ b/web/app/controller/Root.js @@ -144,7 +144,7 @@ Ext.define('Traccar.controller.Root', { break; } } - text = Strings.eventCommandResult + text; + text = Strings.eventCommandResult + ": " + text; } else { typeKey = 'event' + array[i].type.charAt(0).toUpperCase() + array[i].type.slice(1); text = Strings[typeKey]; diff --git a/web/app/model/Notification.js b/web/app/model/Notification.js new file mode 100644 index 00000000000..9b4d61eb4d6 --- /dev/null +++ b/web/app/model/Notification.js @@ -0,0 +1,33 @@ +/* + * Copyright 2016 Anton Tananaev (anton.tananaev@gmail.com) + * + * 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. + */ + +Ext.define('Traccar.model.Notification', { + extend: 'Ext.data.Model', + identifier: 'negative', + + fields: [{ + name: 'id', + type: 'int' + }, { + name: 'type', + type: 'string' + }, { + name: 'userId', + type: 'int' + }, { + name: 'attributes' + }] +}); diff --git a/web/app/model/User.js b/web/app/model/User.js index 35b849187bd..352acc651be 100644 --- a/web/app/model/User.js +++ b/web/app/model/User.js @@ -54,6 +54,8 @@ Ext.define('Traccar.model.User', { }, { name: 'twelveHourFormat', type: 'boolean' + }, { + name: 'attributes' }], proxy: { diff --git a/web/app/store/AllNotifications.js b/web/app/store/AllNotifications.js new file mode 100644 index 00000000000..fed02b2602d --- /dev/null +++ b/web/app/store/AllNotifications.js @@ -0,0 +1,30 @@ +/* + * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) + * + * 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. + */ + +Ext.define('Traccar.store.AllNotifications', { + extend: 'Ext.data.Store', + model: 'Traccar.model.Notification', + + proxy: { + type: 'rest', + url: '/api/users/notifications', + extraParams: { + all: true + } + }, + sortOnLoad: true, + sorters: { property: 'type', direction : 'ASC' } +}); diff --git a/web/app/store/Notifications.js b/web/app/store/Notifications.js new file mode 100644 index 00000000000..5dc8cb614f9 --- /dev/null +++ b/web/app/store/Notifications.js @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) + * + * 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. + */ + +Ext.define('Traccar.store.Notifications', { + extend: 'Ext.data.Store', + model: 'Traccar.model.Notification', + + proxy: { + type: 'rest', + url: '/api/users/notifications' + } +}); diff --git a/web/app/view/Notifications.js b/web/app/view/Notifications.js new file mode 100644 index 00000000000..8efebd038ed --- /dev/null +++ b/web/app/view/Notifications.js @@ -0,0 +1,58 @@ +/* + * Copyright 2016 Anton Tananaev (anton.tananaev@gmail.com) + * + * 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. + */ + +Ext.define('Traccar.view.Notifications', { + extend: 'Ext.grid.Panel', + xtype: 'notificationsView', + + requires: [ + 'Traccar.view.NotificationsController' + ], + + controller: 'notificationsController', + store: 'AllNotifications', + + selModel: { + selType: 'cellmodel', + }, + + columns: [{ + text: Strings.notificationType, + dataIndex: 'type', + flex: 1, + renderer: function (value) { + var typeKey = 'event' + value.charAt(0).toUpperCase() + value.slice(1); + return Strings[typeKey]; + } + }, { + text: Strings.notificationWeb, + dataIndex: 'web', + xtype: 'checkcolumn', + flex: 1, + listeners: { + checkChange: 'onCheckChange' + } + }, { + text: Strings.notificationMail, + dataIndex: 'mail', + xtype: 'checkcolumn', + flex: 1, + listeners: { + checkChange: 'onCheckChange' + } + }], + +}); diff --git a/web/app/view/NotificationsController.js b/web/app/view/NotificationsController.js new file mode 100644 index 00000000000..7a609ef199e --- /dev/null +++ b/web/app/view/NotificationsController.js @@ -0,0 +1,83 @@ +/* + * Copyright 2016 Anton Tananaev (anton.tananaev@gmail.com) + * + * 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. + */ + +Ext.define('Traccar.view.NotificationsController', { + extend: 'Ext.app.ViewController', + alias: 'controller.notificationsController', + + init: function () { + this.userId = this.getView().user.getData().id; + this.getView().getStore().load({ + scope: this, + callback: function (records, operation, success) { + var notificationsStore = Ext.create('Traccar.store.Notifications'); + notificationsStore.load({ + params: { + userId: this.userId + }, + scope: this, + callback: function (records, operation, success) { + var i, index, attributes, storeRecord; + if (success) { + for (i = 0; i < records.length; i++) { + index = this.getView().getStore().find('type', records[i].getData().type); + attributes = records[i].getData().attributes; + storeRecord = this.getView().getStore().getAt(index); + if (typeof attributes.web != 'undefined') { + storeRecord.set('web', attributes.web); + } + if (typeof attributes.mail != 'undefined') { + storeRecord.set('mail', attributes.mail); + } + + storeRecord.commit(); + } + } + } + }); + } + }); + }, + + onCheckChange: function (column, rowIndex, checked, eOpts) { + var record = this.getView().getStore().getAt(rowIndex); + var web, mail; + var data = { + userId: this.userId, + type: record.getData().type, + attributes: {} + }; + web = record.getData().web; + if (typeof web != 'undefined' && web) { + data.attributes.web = "true"; + } + mail = record.getData().mail; + if (typeof mail != 'undefined' && mail) { + data.attributes.mail = "true"; + } + Ext.Ajax.request({ + scope: this, + url: '/api/users/notifications', + jsonData: data, + callback: function (options, success, response) { + if (!success) { + Traccar.app.showError(response); + } + } + }); + + } +}); diff --git a/web/app/view/SettingsMenu.js b/web/app/view/SettingsMenu.js index 704884928b6..70041bd63e4 100644 --- a/web/app/view/SettingsMenu.js +++ b/web/app/view/SettingsMenu.js @@ -47,6 +47,9 @@ Ext.define('Traccar.view.SettingsMenu', { hidden: true, handler: 'onUsersClick', reference: 'settingsUsersButton' + }, { + text: Strings.sharedNotifications, + handler: 'onNotificationsClick', }, { text: Strings.loginLogout, handler: 'onLogoutClick' diff --git a/web/app/view/SettingsMenuController.js b/web/app/view/SettingsMenuController.js index 48ae60aa5e9..45b159ccb7e 100644 --- a/web/app/view/SettingsMenuController.js +++ b/web/app/view/SettingsMenuController.js @@ -25,6 +25,7 @@ Ext.define('Traccar.view.SettingsMenuController', { 'Traccar.view.Users', 'Traccar.view.Groups', 'Traccar.view.Geofences', + 'Traccar.view.Notifications', 'Traccar.view.BaseWindow' ], @@ -77,6 +78,18 @@ Ext.define('Traccar.view.SettingsMenuController', { }).show(); }, + onNotificationsClick: function () { + var user = Traccar.app.getUser(); + Ext.create('Traccar.view.BaseWindow', { + title: Strings.sharedNotifications, + modal: false, + items: { + xtype: 'notificationsView', + user: user + } + }).show(); + }, + onLogoutClick: function () { Ext.create('Traccar.view.LoginController').logout(); } diff --git a/web/app/view/Users.js b/web/app/view/Users.js index b6301b38b48..4abfff1efc5 100644 --- a/web/app/view/Users.js +++ b/web/app/view/Users.js @@ -45,6 +45,11 @@ Ext.define('Traccar.view.Users', { disabled: true, handler: 'onGeofencesClick', reference: 'userGeofencesButton' + }, { + text: Strings.sharedNotifications, + disabled: true, + handler: 'onNotificationsClick', + reference: 'userNotificationsButton' }] }, diff --git a/web/app/view/UsersController.js b/web/app/view/UsersController.js index acba66b4dfa..e745ee04cf0 100644 --- a/web/app/view/UsersController.js +++ b/web/app/view/UsersController.js @@ -23,6 +23,7 @@ Ext.define('Traccar.view.UsersController', { 'Traccar.view.UserDevices', 'Traccar.view.UserGroups', 'Traccar.view.UserGeofences', + 'Traccar.view.Notifications', 'Traccar.view.BaseWindow' ], @@ -114,6 +115,18 @@ Ext.define('Traccar.view.UsersController', { }).show(); }, + onNotificationsClick: function () { + var user = this.getView().getSelectionModel().getSelection()[0]; + Ext.create('Traccar.view.BaseWindow', { + title: Strings.sharedNotifications, + modal: false, + items: { + xtype: 'notificationsView', + user: user + } + }).show(); + }, + onSelectionChange: function (selected) { var disabled = selected.length > 0; this.lookupReference('toolbarEditButton').setDisabled(disabled); @@ -121,5 +134,6 @@ Ext.define('Traccar.view.UsersController', { this.lookupReference('userDevicesButton').setDisabled(disabled); this.lookupReference('userGroupsButton').setDisabled(disabled); this.lookupReference('userGeofencesButton').setDisabled(disabled); + this.lookupReference('userNotificationsButton').setDisabled(disabled); } }); diff --git a/web/l10n/en.json b/web/l10n/en.json index 8ac09caf261..351ad462d48 100644 --- a/web/l10n/en.json +++ b/web/l10n/en.json @@ -19,6 +19,7 @@ "sharedSearch": "Search", "sharedGeofence": "Geofence", "sharedGeofences": "Geofences", + "sharedNotifications": "Notifications", "errorTitle": "Error", "errorUnknown": "Unknown error", "errorConnection": "Connection error", @@ -106,7 +107,10 @@ "eventDeviceMoving": "Device is moving", "eventDeviceStopped": "Device is stopped", "eventDeviceOverspeed": "Device exceeds the speed", - "eventCommandResult": "Command result: ", + "eventCommandResult": "Command result", "eventGeofenceEnter": "Device has entered geofence", - "eventGeofenceExit": "Device has exited geofence" + "eventGeofenceExit": "Device has exited geofence", + "notificationType": "Type of Notification", + "notificationWeb": "Send via Web", + "notificationMail": "Send via Mail" } \ No newline at end of file