Search in sources :

Example 1 with ConsoleAsset

use of org.openremote.model.asset.impl.ConsoleAsset in project openremote by openremote.

the class ConsoleResourceImpl method register.

@Override
public ConsoleRegistration register(RequestParams requestParams, ConsoleRegistration consoleRegistration) {
    if (getRequestTenant() == null) {
        throw new BadRequestException("Invalid realm");
    }
    ConsoleAsset consoleAsset = null;
    // If console registration has an id and asset exists then ensure asset type is console
    if (!TextUtil.isNullOrEmpty(consoleRegistration.getId())) {
        Asset<?> existingAsset = assetStorageService.find(consoleRegistration.getId(), true);
        if (existingAsset != null && !(existingAsset instanceof ConsoleAsset)) {
            throw new BadRequestException("Console registration ID is not for a Console asset: " + consoleRegistration.getId());
        }
        consoleAsset = (ConsoleAsset) existingAsset;
    }
    if (consoleAsset == null) {
        consoleAsset = initConsoleAsset(consoleRegistration, true, true);
        consoleAsset.setRealm(getRequestRealm());
        consoleAsset.setParentId(getConsoleParentAssetId(getRequestRealm()));
        consoleAsset.setId(consoleRegistration.getId());
    }
    consoleAsset.setConsoleName(consoleRegistration.getName()).setConsoleVersion(consoleRegistration.getVersion()).setConsoleProviders(new ConsoleProviders(consoleRegistration.getProviders())).setConsolePlatform(consoleRegistration.getPlatform());
    consoleAsset = assetStorageService.merge(consoleAsset);
    consoleRegistration.setId(consoleAsset.getId());
    // If authenticated link the console to this user
    if (isAuthenticated()) {
        assetStorageService.storeUserAssetLinks(Collections.singletonList(new UserAssetLink(getAuthenticatedRealm(), getUserId(), consoleAsset.getId())));
    }
    return consoleRegistration;
}
Also used : ConsoleAsset(org.openremote.model.asset.impl.ConsoleAsset) ConsoleProviders(org.openremote.model.console.ConsoleProviders) BadRequestException(javax.ws.rs.BadRequestException) UserAssetLink(org.openremote.model.asset.UserAssetLink)

Example 2 with ConsoleAsset

use of org.openremote.model.asset.impl.ConsoleAsset in project openremote by openremote.

the class PushNotificationHandler method getTargets.

@Override
public List<Notification.Target> getTargets(Notification.Source source, String sourceId, List<Notification.Target> targets, AbstractNotificationMessage message) {
    // Check if message is going to a topic if so then filter consoles subscribed to that topic
    PushNotificationMessage pushMessage = (PushNotificationMessage) message;
    List<Notification.Target> mappedTargets = new ArrayList<>();
    if (pushMessage.getTargetType() == TOPIC || pushMessage.getTargetType() == CONDITION) {
        mappedTargets.add(new Notification.Target(Notification.TargetType.CUSTOM, pushMessage.getTargetType() + ": " + pushMessage.getTarget()));
        return mappedTargets;
    }
    if (targets != null) {
        targets.forEach(target -> {
            Notification.TargetType targetType = target.getType();
            String targetId = target.getId();
            switch(targetType) {
                case TENANT:
                    // Get all console assets with a push provider defined within the specified tenant
                    List<Asset<?>> consoleAssets = assetStorageService.findAll(new AssetQuery().select(new AssetQuery.Select().excludeAttributes()).tenant(new TenantPredicate(targetId)).types(ConsoleAsset.class).attributes(new AttributePredicate(ConsoleAsset.CONSOLE_PROVIDERS, null, false, new NameValuePredicate.Path(PushNotificationMessage.TYPE))));
                    // Get all user ids which have pushNotificationsDisabled set to false
                    String[] userIds = Arrays.stream(managerIdentityService.getIdentityProvider().queryUsers(new UserQuery().tenant(new TenantPredicate((targetId))))).filter(user -> Boolean.parseBoolean(user.getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0))).map(User::getId).toArray(String[]::new);
                    String[] assetIds = assetStorageService.findUserAssetLinks(targetId, null, null).stream().filter(userAssetLink -> Arrays.stream(userIds).anyMatch(userId -> userId.equals(userAssetLink.getId().getUserId()))).map(userAssetLink -> userAssetLink.getId().getAssetId()).toArray(String[]::new);
                    // Remove consoleAssets which are linked to an User which has pushNotificationsDisabled set to false
                    consoleAssets = consoleAssets.stream().filter(consoleAsset -> Arrays.stream(assetIds).noneMatch(assetId -> assetId.equals(consoleAsset.getId()))).collect(Collectors.toList());
                    mappedTargets.addAll(consoleAssets.stream().map(asset -> new Notification.Target(Notification.TargetType.ASSET, asset.getId())).collect(Collectors.toList()));
                    break;
                case USER:
                    Optional<User> user = Arrays.stream(managerIdentityService.getIdentityProvider().queryUsers(new UserQuery().ids(targetId))).findFirst();
                    if (user.isPresent() && !Boolean.parseBoolean(user.get().getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0))) {
                        // Get all console assets linked to the specified user
                        String[] ids = assetStorageService.findUserAssetLinks(null, targetId, null).stream().map(userAssetLink -> userAssetLink.getId().getAssetId()).toArray(String[]::new);
                        if (ids.length > 0) {
                            mappedTargets.addAll(assetStorageService.findAll(new AssetQuery().select(new AssetQuery.Select().excludeAttributes()).ids(ids).types(ConsoleAsset.class).attributes(new AttributePredicate(ConsoleAsset.CONSOLE_PROVIDERS, null, false, new NameValuePredicate.Path(PushNotificationMessage.TYPE)))).stream().map(asset -> new Notification.Target(Notification.TargetType.ASSET, asset.getId())).collect(Collectors.toList()));
                        }
                    } else {
                        LOG.fine("No console assets linked to target user");
                        return;
                    }
                    break;
                case ASSET:
                    // Find all console descendants of the specified asset
                    consoleAssets = assetStorageService.findAll(new AssetQuery().select(new AssetQuery.Select().excludeAttributes()).paths(new PathPredicate(targetId)).types(ConsoleAsset.class).attributes(new AttributePredicate(ConsoleAsset.CONSOLE_PROVIDERS, null, false, new NameValuePredicate.Path(PushNotificationMessage.TYPE))));
                    UserAssetLink[] userAssetLinks = consoleAssets.stream().map(consoleAsset -> assetStorageService.findUserAssetLinks(null, null, consoleAsset.getId())).flatMap(Collection::stream).toArray(UserAssetLink[]::new);
                    // Get all user ids which have pushNotificationsDisabled set to false
                    assetIds = Arrays.stream(userAssetLinks).filter(userAssetLink -> Arrays.stream(managerIdentityService.getIdentityProvider().queryUsers(new UserQuery().asset(new UserAssetPredicate(userAssetLink.getId().getAssetId())))).filter(user1 -> Boolean.parseBoolean(user1.getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0))).map(User::getId).anyMatch(userId -> userId.equals(userAssetLink.getId().getUserId()))).map(userAssetLink -> userAssetLink.getId().getAssetId()).toArray(String[]::new);
                    // Remove consoleAssets which are linked to an User which has pushNotificationsDisabled set to false
                    consoleAssets = consoleAssets.stream().filter(consoleAsset -> Arrays.stream(assetIds).noneMatch(assetId -> assetId.equals(consoleAsset.getId()))).collect(Collectors.toList());
                    mappedTargets.addAll(consoleAssets.stream().map(asset -> new Notification.Target(Notification.TargetType.ASSET, asset.getId())).collect(Collectors.toList()));
                    break;
            }
        });
    }
    return mappedTargets;
}
Also used : AssetStorageService(org.openremote.manager.asset.AssetStorageService) GatewayService.isNotForGateway(org.openremote.manager.gateway.GatewayService.isNotForGateway) UserAssetLink(org.openremote.model.asset.UserAssetLink) java.util(java.util) com.google.firebase.messaging(com.google.firebase.messaging) AbstractNotificationMessage(org.openremote.model.notification.AbstractNotificationMessage) FirebaseOptions(com.google.firebase.FirebaseOptions) ValueUtil(org.openremote.model.util.ValueUtil) Level(java.util.logging.Level) Notification(org.openremote.model.notification.Notification) UserQuery(org.openremote.model.query.UserQuery) PersistenceService(org.openremote.container.persistence.PersistenceService) ConsoleProvider(org.openremote.model.console.ConsoleProvider) org.openremote.model.query.filter(org.openremote.model.query.filter) StreamSupport(java.util.stream.StreamSupport) TextUtil(org.openremote.model.util.TextUtil) TypeReference(com.fasterxml.jackson.core.type.TypeReference) NotificationSendResult(org.openremote.model.notification.NotificationSendResult) PersistenceEvent(org.openremote.model.PersistenceEvent) MessageBrokerService(org.openremote.container.message.MessageBrokerService) User(org.openremote.model.security.User) TargetType(org.openremote.model.notification.PushNotificationMessage.TargetType) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) Asset(org.openremote.model.asset.Asset) Files(java.nio.file.Files) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED(org.openremote.manager.security.ManagerKeycloakIdentityProvider.KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED) AssetQuery(org.openremote.model.query.AssetQuery) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ContainerService(org.openremote.model.ContainerService) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Container(org.openremote.model.Container) PushNotificationMessage(org.openremote.model.notification.PushNotificationMessage) RouteBuilder(org.apache.camel.builder.RouteBuilder) ConsoleAsset(org.openremote.model.asset.impl.ConsoleAsset) Paths(java.nio.file.Paths) GatewayService(org.openremote.manager.gateway.GatewayService) FirebaseApp(com.google.firebase.FirebaseApp) InputStream(java.io.InputStream) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) User(org.openremote.model.security.User) Notification(org.openremote.model.notification.Notification) UserAssetLink(org.openremote.model.asset.UserAssetLink) Asset(org.openremote.model.asset.Asset) ConsoleAsset(org.openremote.model.asset.impl.ConsoleAsset) ConsoleAsset(org.openremote.model.asset.impl.ConsoleAsset) AssetQuery(org.openremote.model.query.AssetQuery) UserQuery(org.openremote.model.query.UserQuery) PushNotificationMessage(org.openremote.model.notification.PushNotificationMessage)

Example 3 with ConsoleAsset

use of org.openremote.model.asset.impl.ConsoleAsset in project openremote by openremote.

the class PushNotificationHandler method configure.

@Override
public void configure() throws Exception {
    // If any console asset was modified in the database, detect push provider changes
    from(PersistenceService.PERSISTENCE_TOPIC).routeId("PushNotificationAssetChanges").filter(PersistenceService.isPersistenceEventForEntityType(ConsoleAsset.class)).filter(isNotForGateway(gatewayService)).process(exchange -> {
        @SuppressWarnings("unchecked") PersistenceEvent<ConsoleAsset> persistenceEvent = (PersistenceEvent<ConsoleAsset>) exchange.getIn().getBody(PersistenceEvent.class);
        final ConsoleAsset asset = persistenceEvent.getEntity();
        processConsoleAssetChange(asset, persistenceEvent);
    });
}
Also used : ConsoleAsset(org.openremote.model.asset.impl.ConsoleAsset) PersistenceEvent(org.openremote.model.PersistenceEvent)

Example 4 with ConsoleAsset

use of org.openremote.model.asset.impl.ConsoleAsset in project openremote by openremote.

the class ORConsoleGeofenceAssetAdapter method processConsoleAssetChange.

protected void processConsoleAssetChange(PersistenceEvent<ConsoleAsset> persistenceEvent) {
    ConsoleAsset asset = persistenceEvent.getEntity();
    withLock(getClass().getSimpleName() + "::processAssetChange", () -> {
        switch(persistenceEvent.getCause()) {
            case CREATE:
            case UPDATE:
                if (isLinkedToORConsoleGeofenceAdapter(asset)) {
                    consoleIdRealmMap.put(asset.getId(), asset.getRealm());
                } else {
                    consoleIdRealmMap.remove(asset.getId());
                }
                break;
            case DELETE:
                consoleIdRealmMap.remove(asset.getId());
                break;
        }
    });
}
Also used : ConsoleAsset(org.openremote.model.asset.impl.ConsoleAsset)

Example 5 with ConsoleAsset

use of org.openremote.model.asset.impl.ConsoleAsset in project openremote by openremote.

the class ConsoleResourceImpl method initConsoleAsset.

public static ConsoleAsset initConsoleAsset(ConsoleRegistration consoleRegistration, boolean allowPublicLocationWrite, boolean allowRestrictedLocationWrite) {
    ConsoleAsset consoleAsset = new ConsoleAsset(consoleRegistration.getName());
    consoleAsset.getAttributes().getOrCreate(Asset.LOCATION).addOrReplaceMeta(new MetaItem<>(RULE_STATE));
    if (allowPublicLocationWrite) {
        consoleAsset.getAttributes().getOrCreate(Asset.LOCATION).addOrReplaceMeta(new MetaItem<>(ACCESS_PUBLIC_WRITE, true));
    }
    if (allowRestrictedLocationWrite) {
        consoleAsset.getAttributes().getOrCreate(Asset.LOCATION).addOrReplaceMeta(new MetaItem<>(ACCESS_RESTRICTED_WRITE, true));
    }
    consoleAsset.setAccessPublicRead(true);
    return consoleAsset;
}
Also used : ConsoleAsset(org.openremote.model.asset.impl.ConsoleAsset)

Aggregations

ConsoleAsset (org.openremote.model.asset.impl.ConsoleAsset)5 PersistenceEvent (org.openremote.model.PersistenceEvent)2 UserAssetLink (org.openremote.model.asset.UserAssetLink)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)1 FirebaseApp (com.google.firebase.FirebaseApp)1 FirebaseOptions (com.google.firebase.FirebaseOptions)1 com.google.firebase.messaging (com.google.firebase.messaging)1 InputStream (java.io.InputStream)1 Files (java.nio.file.Files)1 Paths (java.nio.file.Paths)1 java.util (java.util)1 Level (java.util.logging.Level)1 Logger (java.util.logging.Logger)1 Collectors (java.util.stream.Collectors)1 StreamSupport (java.util.stream.StreamSupport)1 BadRequestException (javax.ws.rs.BadRequestException)1 RouteBuilder (org.apache.camel.builder.RouteBuilder)1 GlobalLock.withLock (org.openremote.container.concurrent.GlobalLock.withLock)1