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.core.schedule.Schedulable;
034import org.ametys.core.util.DateUtils;
035import org.ametys.odf.program.SubProgram;
036import org.ametys.plugins.core.schedule.Scheduler;
037import org.ametys.plugins.repository.data.holder.group.impl.ModifiableModelAwareRepeater;
038import org.ametys.plugins.repository.data.holder.group.impl.ModifiableModelAwareRepeaterEntry;
039import org.ametys.plugins.workflow.AbstractWorkflowComponent;
040import org.ametys.plugins.workflow.component.CheckRightsCondition;
041import org.ametys.runtime.i18n.I18nizableText;
042
043/**
044 * {@link Schedulable} for archive educational booklet.
045 */
046public class ArchiveEducationalBookletSchedulable extends EducationalBookletSchedulable
047{
048    @Override
049    protected void _generateSubProgramsEducationalBooklet(JobExecutionContext context, File bookletDirectory, Map<String, String> pdfParameters)
050    {
051        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
052        ZonedDateTime archiveDate = (ZonedDateTime) jobDataMap.get(Scheduler.PARAM_VALUES_PREFIX + "archiveDate");
053        pdfParameters.put("archiveDate", DateUtils.zonedDateTimeToString(archiveDate));
054        
055        super._generateSubProgramsEducationalBooklet(context, bookletDirectory, pdfParameters);
056        
057        EducationalBookletReport report = (EducationalBookletReport) context.get(_EDUCATIONAL_BOOKLET_REPORT);
058        
059        List<SubProgram> exportSubPrograms = new ArrayList<>();
060        List<SubProgram> subProgramsInError = report.getSubProgramsWithError();
061        for (SubProgram subProgram : report.getExportSubPrograms())
062        {
063            ModifiableModelAwareRepeater repeater = subProgram.getRepeater("educational-booklets", true);
064            ModifiableModelAwareRepeaterEntry entry = repeater.addEntry();
065            
066            entry.setValue("date", archiveDate);
067
068            File educationalBookletPDF = new File(report.getBookletDirectory(), subProgram.getName() + "/" + subProgram.getLanguage() + "/educational-booklet.pdf");
069            
070            try
071            {
072                Binary binary = _getEducationalBookletAsBinary(educationalBookletPDF, subProgram, archiveDate);
073                entry.setValue("pdf", binary);
074                
075                Map<String, Object> paramsEdit = new HashMap<>();
076                paramsEdit.put(CheckRightsCondition.FORCE, true); // Ignore the right condition
077                paramsEdit.put(AbstractWorkflowComponent.CONTEXT_PARAMETERS_KEY, new HashMap<>());
078                
079                _contentWorkflowHelper.doAction(subProgram, 222, paramsEdit);
080                
081                exportSubPrograms.add(subProgram);
082            }
083            catch (Exception e)
084            {
085                subProgramsInError.add(subProgram);
086                getLogger().error("An error occurred during saving the educational booklet in the subprogram '{} ({})'", subProgram.getTitle(), subProgram.getId(), e);
087            }
088            
089        }
090        
091        report.setExportSubProgram(exportSubPrograms);
092        
093        context.put(_EDUCATIONAL_BOOKLET_REPORT, report);
094    }
095    
096    /**
097     * Build a binary object from the educational booklet file
098     * @param educationalBookletPDF the educational booklet file
099     * @param subProgram the subProgram
100     * @param votedDate the voted date for the educational booklet 
101     * @return the binary
102     * @throws IOException if an error occurred
103     */
104    protected Binary _getEducationalBookletAsBinary(File educationalBookletPDF, SubProgram subProgram, ZonedDateTime votedDate) throws IOException
105    {
106        Binary binary = new Binary();
107        try (InputStream is = new FileInputStream(educationalBookletPDF))
108        {
109            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
110            String dateAsString = votedDate.format(formatter);
111            
112            String prefix = _i18nUtils.translate(new I18nizableText("plugin.odf", "PLUGINS_ODF_EDUCATIONAL_BOOKLET_SUBPROGRAM_PDF_NAME_PREFIX"), subProgram.getLanguage());
113            String fileName = prefix + " " + subProgram.getTitle() + " - " + dateAsString + ".pdf";
114
115            binary.setEncoding("UTF-8");
116            binary.setMimeType("application/pdf");
117            binary.setLastModificationDate(ZonedDateTime.now());
118            binary.setFilename(fileName);
119            binary.setInputStream(is);
120        }
121        return binary;
122    }
123    
124    @Override
125    protected String _getMailSubjectBaseKey()
126    {
127        return "PLUGINS_ODF_EDUCATIONAL_BOOKLET_SUBPROGRAM_MAIL_SUBJECT_ARCHIVE_";
128    }
129
130    @Override
131    protected String _getMailBodyBaseKey()
132    {
133        return "PLUGINS_ODF_EDUCATIONAL_BOOKLET_SUBPROGRAM_MAIL_BODY_ARCHIVE_";
134    }
135}