001/*
002 *  Copyright 2021 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 */
016
017package org.ametys.cms.data;
018
019import java.util.Optional;
020
021import org.apache.cocoon.xml.AttributesImpl;
022import org.apache.excalibur.xml.sax.ContentHandlerProxy;
023import org.xml.sax.Attributes;
024import org.xml.sax.ContentHandler;
025import org.xml.sax.SAXException;
026
027import org.ametys.plugins.repository.data.ametysobject.DataAwareAmetysObject;
028import org.ametys.plugins.repository.model.RepositoryDataContext;
029import org.ametys.plugins.repository.version.VersionAwareAmetysObject;
030import org.ametys.runtime.model.type.DataContext;
031
032/**
033 * Proxy handler to enhance the rich text attachments.
034 * Add the content id and the data path to the local attachment's fileref attribute 
035 */
036public class LocalMediaObjectHandler extends ContentHandlerProxy
037{
038    private static final String __ATTACHMENT_IMAGE_TAG_NAME = "imagedata";
039    private static final String __ATTACHMENT_VIDEO_TAG_NAME = "videodata";
040    private static final String __ATTACHMENT_AUDIO_TAG_NAME = "audiodata";
041    private static final String __ATTACHMENT_TYPE_ATTRIBUTE_NAME = "type";
042    private static final String __ATTACHMENT_TYPE_ATTRIBUTE_LOCAL_VALUE = "local";
043
044    private DataContext _context;
045    
046    /**
047     * Constructor
048     * @param contentHandler the contentHandler to pass SAX events to
049     * @param context the context of the rich text to SAX
050     */
051    public LocalMediaObjectHandler(ContentHandler contentHandler, DataContext context)
052    {
053        super(contentHandler);
054        _context = context;
055    }
056
057    @Override
058    public void startElement(String uri, String loc, String raw, Attributes attrs) throws SAXException
059    {
060        // A new attachment starts being saxed
061        boolean isAttachment = _isAttachment(loc);
062        String type = attrs.getValue(__ATTACHMENT_TYPE_ATTRIBUTE_NAME);
063        if (isAttachment && __ATTACHMENT_TYPE_ATTRIBUTE_LOCAL_VALUE.equals(type))
064        {
065            Attributes newAttrs = _processAttachment(attrs);
066            super.startElement(uri, loc, raw, newAttrs);
067        }
068        else
069        {
070            super.startElement(uri, loc, raw, attrs);
071        }
072    }
073
074    private boolean _isAttachment(String loc)
075    {
076        return __ATTACHMENT_IMAGE_TAG_NAME.equals(loc) || __ATTACHMENT_VIDEO_TAG_NAME.equals(loc) || __ATTACHMENT_AUDIO_TAG_NAME.equals(loc);
077    }
078
079    private Attributes _processAttachment(Attributes attrs) throws SAXException
080    {
081        RepositoryDataContext repoContext = _context instanceof RepositoryDataContext rc ? rc : RepositoryDataContext.newInstance(_context);
082        
083        DataAwareAmetysObject content = repoContext.getObject()
084                                                   .orElseThrow(() -> new SAXException("The object is required in the data context in order to set the fileref"));
085
086        String contentId = content.getId();
087        
088        Optional<String> contentVersion = Optional.of(content)
089                                                  .filter(VersionAwareAmetysObject.class::isInstance)
090                                                  .map(VersionAwareAmetysObject.class::cast)
091                                                  .map(VersionAwareAmetysObject::getRevision);
092        
093        String dataPath = _context.getDataPath();
094        String fileName = attrs.getValue("fileref");
095
096        AttributesImpl newAttrs = new AttributesImpl();
097        _copyAttributes(attrs, newAttrs);
098
099        StringBuilder newFilerefAttribute = new StringBuilder();
100        newFilerefAttribute.append(contentId);
101        contentVersion.ifPresent(v -> newFilerefAttribute.append("|").append(v));
102        newFilerefAttribute.append("@").append(dataPath)
103                           .append(";").append(fileName);
104        
105        newAttrs.addCDATAAttribute("fileref", newFilerefAttribute.toString());
106
107        return newAttrs;
108    }
109
110    /**
111     * Copy the attributes except the fileref attribute
112     * @param attrs the attributes to copy.
113     * @param newAttrs the attributes to copy to.
114     */
115    private void _copyAttributes(Attributes attrs, AttributesImpl newAttrs)
116    {
117        for (int i = 0; i < attrs.getLength(); i++)
118        {
119            String name = attrs.getQName(i);
120
121            if (!"fileref".equals(name))
122            {
123                newAttrs.addAttribute(attrs.getURI(i), attrs.getLocalName(i), name, attrs.getType(i), attrs.getValue(i));
124            }
125        }
126    }
127}