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.cms.scripts;
017
018import java.util.Map;
019
020import org.apache.avalon.framework.service.ServiceException;
021import org.apache.avalon.framework.service.ServiceManager;
022import org.quartz.SchedulerException;
023
024import org.ametys.core.ui.Callable;
025import org.ametys.core.ui.StaticClientSideElement;
026import org.ametys.plugins.core.schedule.Scheduler;
027import org.ametys.runtime.authentication.AccessDeniedException;
028
029/**
030 * Client side element for the script tool
031 */
032public class ScriptToolClientSideElement extends StaticClientSideElement
033{
034    /** The Ametys scheduler */
035    protected Scheduler _scheduler;
036    
037    @Override
038    public void service(ServiceManager smanager) throws ServiceException
039    {
040        super.service(smanager);
041        _scheduler = (Scheduler) smanager.lookup(Scheduler.ROLE);
042    }
043    
044    /**
045     * Adds a new task.
046     * @param label The label
047     * @param description The description
048     * @param fireProcess the fire process
049     * @param cron The cron expression
050     * @param schedulableId The id of the schedulable model
051     * @param params The values of the parameters
052     * @return A result map
053     * @throws SchedulerException if an error occured
054     */
055    @Callable(rights = Callable.CHECKED_BY_IMPLEMENTATION)
056    public Map<String, Object> add(String label, String description, String fireProcess, String cron, String schedulableId, Map<String, Object> params) throws SchedulerException
057    {
058        // Hardcode the same right has ScriptHandler.executeScript
059        Map<String, String> executeRights = Map.of("CORE_Rights_ExecuteScript", "/${WorkspaceName}");
060        if (hasRight(executeRights) && schedulableId.equals("org.ametys.core.schedule.Script"))
061        {
062            return _scheduler.add(label, description, fireProcess, cron, schedulableId, params);
063        }
064        throw new AccessDeniedException(_currentUserProvider.getUser() + "' tried to execute schedulable '" + schedulableId + "' without any of the following rights: " + executeRights);
065    }
066
067}