gcube-cms-suite/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/ManageDoActionNotification....

243 lines
9.7 KiB
Java

package org.gcube.application.cms.notifications.manage;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.gcube.application.cms.implementations.utils.UserUtils;
import org.gcube.application.cms.notifications.NotificationGenericConstants;
import org.gcube.application.cms.notifications.config.NotificationFor;
import org.gcube.application.cms.notifications.config.NotificationWhen;
import org.gcube.application.cms.notifications.config.SubscribeNotificationEvent;
import org.gcube.application.cms.notifications.gis.GisClient;
import org.gcube.application.cms.notifications.social.SocialClients;
import org.gcube.application.cms.notifications.substitutor.NMessagesPlaceholdersSubstitutorUtil;
import org.gcube.application.cms.notifications.substitutor.SubstitutorMessagesMap;
import org.gcube.application.cms.plugins.events.ItemObserved;
import org.gcube.application.geoportal.common.model.document.Project;
import org.gcube.application.geoportal.common.model.document.accounting.User;
import org.gcube.application.geoportal.common.model.document.lifecycle.LifecycleInformation;
import org.gcube.common.authorization.utils.manager.SecretManager;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.portlets.user.uriresolvermanager.resolvers.query.GeoportalResolverQueryStringBuilder.RESOLVE_AS;
import org.gcube.social_networking.socialnetworking.model.beans.catalogue.CatalogueEventType;
import lombok.extern.slf4j.Slf4j;
/**
* The Class ManageDoActionNotification.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 1, 2024
*/
@Slf4j
public class ManageDoActionNotification {
private List<SubscribeNotificationEvent> listSubscribedNotification;
private ItemObserved<Project> itemObserved;
private NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersS;
/**
* Instantiates a new manage do action notification.
*
* @param itemObserved the item observed
* @param nMPlaceholdersSUtil the n M placeholders S util
* @param filterList the filter list
*/
public ManageDoActionNotification(ItemObserved<Project> itemObserved,
NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersSUtil, List<SubscribeNotificationEvent> filterList) {
this.listSubscribedNotification = filterList;
this.nMPlaceholdersS = nMPlaceholdersSUtil;
this.itemObserved = itemObserved;
// Creating the map for replacing the placeholder with their values
SubstitutorMessagesMap placeholderMapValues = new SubstitutorMessagesMap();
String gisLink = GisClient.gisLink(RESOLVE_AS.PRIVATE, itemObserved.getUCD_Id(), itemObserved.getProjectId(),
itemObserved.getContext().getId(), true);
placeholderMapValues.putGisLink(gisLink);
placeholderMapValues.putProjectId(itemObserved.getProjectId());
LinkedHashMap<String, Object> docAsMap = itemObserved.getDocumentEntries(1);
String projectName = docAsMap.size() > 0 ? docAsMap.values().stream().findFirst().get() + ""
: itemObserved.getProjectId();
placeholderMapValues.putProjectName(projectName);
placeholderMapValues.putUser(itemObserved.getUserCaller().getUsername());
nMPlaceholdersS.setPlaceholderMapValues(placeholderMapValues);
}
/**
* Manage.
*/
public void manage() {
log.debug("manage called...");
if (listSubscribedNotification == null || listSubscribedNotification.isEmpty())
return;
for (SubscribeNotificationEvent subscribeNotificationEvent : listSubscribedNotification) {
List<NotificationFor> listNotificationFor = subscribeNotificationEvent.getNotificationFor();
// Reading 'phase' property from itemObserved
LifecycleInformation lInfo = itemObserved.getProject().getLifecycleInformation();
String itemPhase = lInfo.getPhase();
String lastInvokedStep = lInfo.getLastInvokedStep();
log.debug("ItemObserved phase is: {}, lastInvokedStep is: {}", itemPhase, lastInvokedStep);
final SecretManager cm = SecretManagerProvider.instance.get();
for (final NotificationFor notificationFor : listNotificationFor) {
// Filtering notifications on 'phase' and 'lastInvokedStep' according to item
// itemObserved 'phase'
List<NotificationWhen> notificationsCompliantToPhase = matchNotificationsAccordingItemStatus(
notificationFor, itemPhase, lastInvokedStep);
// log.debug("Filtered notifications on phase {} and lastInvokedStep {} are: {}", itemPhase, lastInvokedStep,
// notificationsCompliantToPhase);
if (notificationsCompliantToPhase != null && notificationsCompliantToPhase.size() > 0) {
// GET LIST USER COMPLIANT TO ROLES
List<User> notifyUsers = getListUserCompliantToRoles(notificationFor, itemObserved);
final SocialClients socialClients = new SocialClients();
if (notifyUsers.size() > 0) {
log.info("Users compliant to role are: {}", notifyUsers.size());
if (log.isDebugEnabled()) {
notifyUsers.stream().forEach(u -> log.debug("user: " + u));
}
for (final User user : notifyUsers) {
try {
NotifyUser mnu = new NotifyUser(socialClients, notificationsCompliantToPhase,
nMPlaceholdersS, user);
mnu.send();
} catch (Exception e) {
log.error("Error occurred when send notify: ", e);
}
}
/*
* for (final User user : notifyUsers) { Thread notificationT = new Thread() {
* public void run() { SecretManagerProvider.instance.set(cm); NotifyUser mnu =
* new NotifyUser(socialClients, notificationsCompliantToPhase, nMPlaceholdersS,
* user); try { mnu.send(); } catch (Exception e) {
* log.error("Error occurred when send notify: ", e); } };
*
* };
*
* notificationT.start(); }
*/
}
}
}
}
}
public static List<NotificationWhen> matchNotificationsAccordingItemStatus(NotificationFor notificationFor,
String itemPhase, String lastInvokedStep) {
log.info("Filtering notifications according to phase: {}, lastInvokedStep: {}", itemPhase, lastInvokedStep);
List<NotificationWhen> filteredList = new ArrayList<NotificationWhen>();
int i = 0;
for (NotificationWhen notificationWhen : notificationFor.getWhen()) {
log.info(++i + ") notificationWhen target phases: {} and last_invoked_step: {}",
notificationWhen.getTarget_phase(), notificationWhen.getLast_invoked_step());
if (notificationWhen.getTarget_phase().contains(itemPhase)) {
if (notificationWhen.getLast_invoked_step() == null) {
// no filtering on lastInvokedStep
filteredList.add(notificationWhen);
} else if (notificationWhen.getLast_invoked_step().compareToIgnoreCase(lastInvokedStep) == 0) {
// matching the lastInvokedStep
filteredList.add(notificationWhen);
}
}
}
log.info("returning filtered list with {} object {}", filteredList.size(),
NotificationWhen.class.getSimpleName());
return filteredList;
}
public static CatalogueEventType toCatalogueEventType(String itemPhase, String lastInvokedStep) {
return null;
}
/**
* Gets the list user compliant to roles.
*
* @param notificationFor the notification for
* @param itemObserved the item observed
* @return the list user compliant to roles
*/
// GET LIST USER COMPLIANT TO ROLES
public List<User> getListUserCompliantToRoles(NotificationFor notificationFor, ItemObserved<Project> itemObserved) {
log.debug("getListUserCompliantToRoles called for scope: {}", UserUtils.getCurrent().getContext());
List<String> notifyUserWithRoles = notificationFor.getRoles();
List<User> notifyUsers = new ArrayList<User>();
String anyRole = NotificationGenericConstants.CUSTOM_USER_ROLES.Any.name();
SocialClients socialClients = new SocialClients();
if (notifyUserWithRoles.contains(anyRole)) {
try {
// String token = AccessTokenProvider.instance.set(s);
List<String> listUsername = socialClients.getUsernamesByScope();
notifyUsers.addAll(
listUsername.stream().map(username -> new User(username, null)).collect(Collectors.toList()));
} catch (Exception e) {
log.error("Error on reading users from scope {}: ", UserUtils.getCurrent().getContext(), e);
}
log.info("returning {} users for role {}", notifyUsers.size(), anyRole);
return notifyUsers;
}
// We need to create the list of users that must be notified
for (String role : notifyUserWithRoles) {
// Reading the list of users in the VRE with specific role
// Creator of the item
String itemCreatorRole = NotificationGenericConstants.CUSTOM_USER_ROLES.Item_Creator.name();
if (role.compareTo(itemCreatorRole) == 0) {
try {
String creatorUsername = itemObserved.getProject().getInfo().getCreationInfo().getUser()
.getUsername();
notifyUsers.add(
new User(creatorUsername, Stream.of(role).collect(Collectors.toCollection(HashSet::new))));
log.info("added {} user for role {}", notifyUsers.size(), role);
} catch (Exception e) {
log.error("Error on reading user {} from scope {}: ", itemCreatorRole,
UserUtils.getCurrent().getContext(), e);
}
} else {
try {
List<String> listUsernameForRole = socialClients.getUsernamesByRole(role);
notifyUsers.addAll(listUsernameForRole.stream()
.map(username -> new User(username,
Stream.of(role).collect(Collectors.toCollection(HashSet::new))))
.collect(Collectors.toList()));
log.info("added {} users for role {}", notifyUsers.size(), role);
} catch (Exception e) {
log.error("Error on reading users from scope {}: ", UserUtils.getCurrent().getContext(), e);
}
}
}
// return the list of users that must be notified;
log.info("returing {} users to be notified: ", notifyUsers.size());
return notifyUsers;
}
}