001/*
002 * (C) Copyright 2013-2016 Nuxeo SA (http://nuxeo.com/) and others.
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 * Contributors:
017 *   Nuxeo - initial API and implementation
018 */
019package org.nuxeo.ecm.platform.mail.adapter;
020
021import java.util.regex.Matcher;
022import java.util.regex.Pattern;
023
024import org.nuxeo.ecm.core.api.Blob;
025import org.nuxeo.ecm.core.api.Blobs;
026import org.nuxeo.ecm.core.api.DocumentModel;
027import org.nuxeo.ecm.core.api.blobholder.DocumentBlobHolder;
028import org.nuxeo.ecm.platform.mail.utils.MailCoreConstants;
029
030/**
031 * BlobHolder for MailMessage documents. The blob returned is a StringBlob with the mail body message as content.
032 *
033 * @author ldoguin
034 * @since 5.7.3
035 */
036public class MailMessageBlobHolder extends DocumentBlobHolder {
037
038    protected Pattern isHtmlPattern = Pattern.compile("(.*)<(html|head|body)>(.*)",
039            Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
040
041    private final String filename;
042
043    public MailMessageBlobHolder(DocumentModel doc, String xPath, String filename) {
044        super(doc, xPath);
045        this.filename = filename;
046    }
047
048    @Override
049    public Blob getBlob() {
050        String htmlTextProperty = (String) doc.getPropertyValue(xPath);
051        Blob blob;
052        if (htmlTextProperty != null && filename != null && htmlTextProperty.length() != 0) {
053            blob = Blobs.createBlob(htmlTextProperty);
054            Matcher m = isHtmlPattern.matcher(htmlTextProperty);
055            if (m.matches()) {
056                blob.setMimeType("text/html");
057            } // else default is text/plain
058        } else {
059            String txt = (String) doc.getPropertyValue(MailCoreConstants.TEXT_PROPERTY_NAME);
060            if (txt == null) {
061                txt = "";
062            }
063            blob = Blobs.createBlob(txt);
064        }
065        blob.setFilename(filename);
066        // set dummy digest to avoid comparison error
067        blob.setDigest("notInBinaryStore");
068        return blob;
069    }
070}