001/*
002 *  Copyright 2020 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.odf.schedulable;
017
018import java.io.File;
019import java.io.FileInputStream;
020import java.io.IOException;
021import java.io.InputStream;
022import java.time.ZonedDateTime;
023import java.time.format.DateTimeFormatter;
024import java.util.ArrayList;
025import java.util.HashMap;
026import java.util.List;
027import java.util.Map;
028
029import org.quartz.JobDataMap;
030import org.quartz.JobExecutionContext;
031
032import org.ametys.cms.data.Binary;
033import org.ametys.cms.repository.Content;
034import org.ametys.cms.repository.ModifiableContent;
035import org.ametys.cms.repository.WorkflowAwareContent;
036import org.ametys.core.schedule.Schedulable;
037import org.ametys.core.util.DateUtils;
038import org.ametys.odf.ProgramItem;
039import org.ametys.plugins.core.schedule.Scheduler;
040import org.ametys.plugins.repository.data.holder.group.ModifiableModelAwareRepeater;
041import org.ametys.plugins.repository.data.holder.group.ModifiableModelAwareRepeaterEntry;
042import org.ametys.plugins.workflow.AbstractWorkflowComponent;
043import org.ametys.plugins.workflow.component.CheckRightsCondition;
044import org.ametys.runtime.i18n.I18nizableText;
045
046/**
047 * {@link Schedulable} for archive educational booklet.
048 */
049public class ArchiveEducationalBookletSchedulable extends EducationalBookletSchedulable
050{
051    /** Scheduler parameter name of archive date */
052    public static final String PARAM_ARCHIVE_DATE = "archiveDate";
053    /** Scheduler parameter name of edit workflow action id */
054    public static final String PARAM_WORKFLOW_ACTION_ID = "workflowActionId";
055    
056    @Override
057    protected void _generateProgramItemsEducationalBooklet(JobExecutionContext context, File bookletDirectory, Map<String, Object> pdfParameters)
058    {
059        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
060        
061        ZonedDateTime archiveDate = (ZonedDateTime) jobDataMap.get(Scheduler.PARAM_VALUES_PREFIX + PARAM_ARCHIVE_DATE);
062        long workflowActionId = (long) jobDataMap.get(Scheduler.PARAM_VALUES_PREFIX + PARAM_WORKFLOW_ACTION_ID);
063        
064        pdfParameters.put(PARAM_ARCHIVE_DATE, DateUtils.zonedDateTimeToString(archiveDate));
065        pdfParameters.put(PARAM_INCLUDE_SUBPROGRAMS, jobDataMap.get(Scheduler.PARAM_VALUES_PREFIX + PARAM_INCLUDE_SUBPROGRAMS));
066        
067        super._generateProgramItemsEducationalBooklet(context, bookletDirectory, pdfParameters);
068        
069        EducationalBookletReport report = (EducationalBookletReport) context.get(_EDUCATIONAL_BOOKLET_REPORT);
070        
071        List<Content> exportedProgramItems = new ArrayList<>();
072        List<Content> programItemsInError = report.getProgramItemsInError();
073        for (Content content : report.getExportedProgramItems())
074        {
075            ModifiableModelAwareRepeater repeater = ((ModifiableContent) content).getRepeater(ProgramItem.EDUCATIONAL_BOOKLETS, true);
076            ModifiableModelAwareRepeaterEntry entry = repeater.addEntry();
077            
078            entry.setValue("date", archiveDate);
079
080            File educationalBookletPDF = new File(report.getBookletDirectory(), content.getName() + "/" + content.getLanguage() + "/educational-booklet.pdf");
081            
082            try
083            {
084                Binary binary = _getEducationalBookletAsBinary(educationalBookletPDF, content, archiveDate);
085                entry.setValue("pdf", binary);
086                
087                Map<String, Object> paramsEdit = new HashMap<>();
088                paramsEdit.put(CheckRightsCondition.FORCE, true); // Ignore the right condition
089                paramsEdit.put(AbstractWorkflowComponent.CONTEXT_PARAMETERS_KEY, new HashMap<>());
090                
091                _contentWorkflowHelper.doAction((WorkflowAwareContent) content, (int) workflowActionId, paramsEdit);
092                
093                exportedProgramItems.add(content);
094            }
095            catch (Exception e)
096            {
097                programItemsInError.add(content);
098                getLogger().error("An error occurred during saving the educational booklet into content '{} ({})'", content.getTitle(), content.getId(), e);
099            }
100            
101        }
102        
103        report.setExportedProgramItems(exportedProgramItems);
104        
105        context.put(_EDUCATIONAL_BOOKLET_REPORT, report);
106    }
107    
108    /**
109     * Build a binary object from the educational booklet file
110     * @param educationalBookletPDF the educational booklet file
111     * @param content the content
112     * @param votedDate the voted date for the educational booklet 
113     * @return the binary
114     * @throws IOException if an error occurred
115     */
116    protected Binary _getEducationalBookletAsBinary(File educationalBookletPDF, Content content, ZonedDateTime votedDate) throws IOException
117    {
118        Binary binary = new Binary();
119        try (InputStream is = new FileInputStream(educationalBookletPDF))
120        {
121            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
122            String dateAsString = votedDate.format(formatter);
123            
124            String prefix = _i18nUtils.translate(new I18nizableText("plugin.odf", "PLUGINS_ODF_EDUCATIONAL_BOOKLET_PROGRAMITEM_PDF_NAME_PREFIX"), content.getLanguage());
125            String fileName = prefix + " " + content.getTitle() + " - " + dateAsString + ".pdf";
126
127            binary.setEncoding("UTF-8");
128            binary.setMimeType("application/pdf");
129            binary.setLastModificationDate(ZonedDateTime.now());
130            binary.setFilename(fileName);
131            binary.setInputStream(is);
132        }
133        return binary;
134    }
135    
136    @Override
137    protected String _getMailSubjectBaseKey()
138    {
139        return "PLUGINS_ODF_EDUCATIONAL_BOOKLET_PROGRAMITEM_MAIL_SUBJECT_ARCHIVE_";
140    }
141
142    @Override
143    protected String _getMailBodyBaseKey()
144    {
145        return "PLUGINS_ODF_EDUCATIONAL_BOOKLET_PROGRAMITEM_MAIL_BODY_ARCHIVE_";
146    }
147}