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