001/*
002 *  Copyright 2025 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.userdirectory.observation;
017
018import java.util.List;
019import java.util.Map;
020
021import org.apache.avalon.framework.service.ServiceException;
022import org.apache.avalon.framework.service.ServiceManager;
023import org.apache.avalon.framework.service.Serviceable;
024
025import org.ametys.cms.repository.Content;
026import org.ametys.core.ObservationConstants;
027import org.ametys.core.observation.AsyncObserver;
028import org.ametys.core.observation.Event;
029import org.ametys.core.user.UserIdentity;
030import org.ametys.plugins.userdirectory.DeleteUserComponent;
031import org.ametys.plugins.userdirectory.UserDirectoryHelper;
032import org.ametys.runtime.plugin.component.AbstractLogEnabled;
033
034/**
035 * Delete user contents of deleted user
036 */
037public class UserDeletedObserver extends AbstractLogEnabled implements AsyncObserver, Serviceable
038{
039    /** The user directory helper */
040    protected UserDirectoryHelper _userDirectoryHelper;
041    /** The delete user component */
042    protected DeleteUserComponent _deleteUserComponent;
043
044    public void service(ServiceManager manager) throws ServiceException
045    {
046        _deleteUserComponent = (DeleteUserComponent) manager.lookup(DeleteUserComponent.ROLE);
047        _userDirectoryHelper = (UserDirectoryHelper) manager.lookup(UserDirectoryHelper.ROLE);
048    }
049    
050    public int getPriority()
051    {
052        return Integer.MAX_VALUE;
053    }
054
055    public boolean supports(Event event)
056    {
057        return ObservationConstants.EVENT_USER_DELETED.equals(event.getId());
058    }
059    
060    public void observe(Event event, Map<String, Object> transientVars) throws Exception
061    {
062        UserIdentity identity = (UserIdentity) event.getArguments().get(ObservationConstants.ARGS_USER);
063        List<Content> userContents = _userDirectoryHelper.getUserContents(identity);
064        
065        int deletedContents = _deleteUserComponent.deleteContentsWithLog(userContents, Map.of(), Map.of(), getLogger());
066        if (userContents.size() != deletedContents)
067        {
068            getLogger().error("Something prevented the user content of a deleted user to be deleted");
069        }
070    }
071}