View Javadoc

1   /**
2    * This file Copyright (c) 2013 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.mail.app.verify;
35  
36  import info.magnolia.context.MgnlContext;
37  import info.magnolia.dam.api.Asset;
38  import info.magnolia.dam.api.AssetProviderRegistry;
39  import info.magnolia.dam.api.ItemKey;
40  import info.magnolia.i18nsystem.SimpleTranslator;
41  import info.magnolia.jcr.util.PropertyUtil;
42  import info.magnolia.jcr.util.SessionUtil;
43  import info.magnolia.module.mail.MailModule;
44  import info.magnolia.module.mail.MailTemplate;
45  import info.magnolia.module.mail.app.MailSubAppDecriptor;
46  import info.magnolia.module.mail.templates.MailAttachment;
47  import info.magnolia.module.mail.templates.MgnlEmail;
48  import info.magnolia.module.mail.util.MailUtil;
49  import info.magnolia.objectfactory.ComponentProvider;
50  import info.magnolia.repository.RepositoryConstants;
51  import info.magnolia.ui.api.app.SubAppContext;
52  import info.magnolia.ui.api.context.UiContext;
53  import info.magnolia.ui.dialog.formdialog.FormBuilder;
54  import info.magnolia.ui.form.definition.FormDefinition;
55  import info.magnolia.ui.vaadin.form.FormViewReduced;
56  import info.magnolia.ui.vaadin.overlay.MessageStyleTypeEnum;
57  
58  import java.io.File;
59  import java.util.HashMap;
60  import java.util.Iterator;
61  import java.util.List;
62  import java.util.Map;
63  
64  import javax.jcr.Node;
65  import javax.mail.Message.RecipientType;
66  import javax.mail.internet.InternetAddress;
67  
68  import org.apache.commons.io.IOUtils;
69  import org.apache.commons.lang.StringUtils;
70  import org.slf4j.Logger;
71  import org.slf4j.LoggerFactory;
72  
73  import com.google.inject.Inject;
74  import com.mycila.inject.internal.guava.io.Files;
75  import com.vaadin.data.util.PropertysetItem;
76  
77  /**
78   * Presenter for the mail verify subapp.
79   */
80  public class MailVerifyPresenter implements MailVerifyView.Listener {
81  
82      private MailVerifyView view;
83      private ComponentProvider componentProvider;
84      private MailModule mailModule;
85      private SubAppContext subAppContext;
86      private UiContext context;
87      private SimpleTranslator translator;
88      private FormBuilder builder;
89      protected Map<String, PropertysetItem> items = new HashMap<String, PropertysetItem>();
90  
91      private static final String PATH_SEPARATOR = "/";
92      private static final String SIMPLE_RENDERER = "simple";
93  
94      private static final String SIMPLE_MAIL_FORM_DEFINITION = "simple";
95      private static final String TEMPLATE_MAIL_FORM_DEFINITION = "template";
96      private static final String SIMPLE_CONFIGURATION_NODE_PATH = "/modules/mail/config/simpleConfiguration";
97  
98      private static final String PROPERTY_CONTENT_TYPE = "contentType";
99      private static final String PROPERTY_ATTACHMENT = "attachment";
100     private static final String PROPERTY_EMAIL = "email";
101     private static final String PROPERTY_TEMPLATE = "template";
102     private static final String PROPERTY_DATA = "data";
103 
104     private static final String BUTTON_SIMPLE_MAIL_SUCCESS = "mail.app.verify.button.simple.success";
105     private static final String BUTTON_SIMPLE_MAIL_ERROR = "mail.app.verify.button.simple.error";
106     private static final String BUTTON_TEMPLATE_MAIL_SUCCESS = "mail.app.verify.button.template.success";
107     private static final String BUTTON_TEMPLATE_MAIL_ERROR = "mail.app.verify.button.template.error";
108 
109     private static final Logger log = LoggerFactory.getLogger(MailVerifyPresenter.class);
110     private final AssetProviderRegistry assetRegistry;
111 
112     @Inject
113     public MailVerifyPresenter(MailVerifyView view, FormBuilder builder, ComponentProvider componentProvider, MailModule mailModule, SubAppContext subAppContext, UiContext context, SimpleTranslator translator, AssetProviderRegistry assetRegistry) {
114         this.view = view;
115         this.builder = builder;
116         this.componentProvider = componentProvider;
117         this.mailModule = mailModule;
118         this.subAppContext = subAppContext;
119         this.context = context;
120         this.translator = translator;
121         this.assetRegistry = assetRegistry;
122     }
123 
124     public MailVerifyView start() {
125         FormDefinition formDefinition = ((MailSubAppDecriptor) subAppContext.getSubAppDescriptor()).getFormDefinitions().get(SIMPLE_MAIL_FORM_DEFINITION);
126         FormViewReduced formView = componentProvider.getComponent(FormViewReduced.class);
127         PropertysetItem item = new PropertysetItem();
128         items.put(SIMPLE_MAIL_FORM_DEFINITION, item);
129         builder.buildReducedForm(formDefinition, formView, item, null);
130         view.addFormViewReduced(SIMPLE_MAIL_FORM_DEFINITION, formView);
131 
132         formDefinition = ((MailSubAppDecriptor) subAppContext.getSubAppDescriptor()).getFormDefinitions().get(TEMPLATE_MAIL_FORM_DEFINITION);
133         formView = componentProvider.getComponent(FormViewReduced.class);
134         item = new PropertysetItem();
135         items.put(TEMPLATE_MAIL_FORM_DEFINITION, item);
136         builder.buildReducedForm(formDefinition, formView, item, null);
137         view.addFormViewReduced(TEMPLATE_MAIL_FORM_DEFINITION, formView);
138 
139         view.setListner(this);
140         view.build();
141         return view;
142     }
143 
144     private Node getMailConfigurationNode() {
145         return SessionUtil.getNode(RepositoryConstants.CONFIG, SIMPLE_CONFIGURATION_NODE_PATH);
146     }
147 
148     @Override
149     public void sendSimpleMail() {
150         File tmp = null; // temporary file used for attachment
151         try {
152             Node mailNode = getMailConfigurationNode();
153             Map<String, Object> params = new HashMap<String, Object>();
154 
155             String userEmailAddress = PropertyUtil.getString(SessionUtil.getNodeByIdentifier(RepositoryConstants.USERS, MgnlContext.getUser().getIdentifier()), PROPERTY_EMAIL);
156             if (StringUtils.isBlank(userEmailAddress)) {
157                 context.openNotification(MessageStyleTypeEnum.ERROR, true, translator.translate("mail.app.verify.button.simple.error.no.email", MgnlContext.getUser().getName()));
158                 return;
159             }
160             String contentType = (String) items.get(SIMPLE_MAIL_FORM_DEFINITION).getItemProperty(PROPERTY_CONTENT_TYPE).getValue();
161             String itemKeyAsString = (String) items.get(SIMPLE_MAIL_FORM_DEFINITION).getItemProperty(PROPERTY_ATTACHMENT).getValue(); // asset id to attachment
162 
163             // set mail parameters
164             params.put(MailTemplate.MAIL_TO, userEmailAddress);
165             params.put(MailTemplate.MAIL_FROM, PropertyUtil.getString(mailNode, MailTemplate.MAIL_FROM));
166             params.put(MailTemplate.MAIL_SUBJECT, PropertyUtil.getString(mailNode, MailTemplate.MAIL_SUBJECT));
167             params.put(MailTemplate.MAIL_BODY, PropertyUtil.getString(mailNode, MailTemplate.MAIL_BODY));
168 
169             // create attachment list
170             List<MailAttachment> attachments = MailUtil.createAttachmentList();
171 
172             // get asset and create temporary file to be send as attachment
173             if (StringUtils.isNotEmpty(itemKeyAsString) && ItemKey.isValid(itemKeyAsString)) {
174                 ItemKey itemKey = ItemKey.from(itemKeyAsString);
175                 Asset asset = assetRegistry.getProviderFor(itemKey).getAsset(itemKey);
176                 if (asset != null) {
177                     tmp = new File(asset.getFileName());
178                     Files.write(IOUtils.toByteArray(asset.getContentStream()), tmp);
179                     MailAttachment a = new MailAttachment(tmp, asset.getFileName(), asset.getDescription(), MailAttachment.DISPOSITION_ATTACHMENT);
180                     attachments.add(a);
181                 }
182             }
183 
184             MgnlEmail email = mailModule.getFactory().getEmailFromType(params, SIMPLE_RENDERER, contentType, attachments);
185             mailModule.getHandler().prepareAndSendMail(email);
186             context.openNotification(MessageStyleTypeEnum.INFO, true, translator.translate(BUTTON_SIMPLE_MAIL_SUCCESS, userEmailAddress));
187         } catch (Exception e) {
188             log.error("Unable to send email.", e);
189             context.openNotification(MessageStyleTypeEnum.ERROR, true, translator.translate(BUTTON_SIMPLE_MAIL_ERROR, e.getMessage()));
190         } finally {
191             if (tmp != null) {
192                 tmp.delete();
193             }
194         }
195     }
196 
197     @Override
198     public void sendTemplateMail() {
199         try {
200             String templateName = StringUtils.substringAfterLast((String) items.get(TEMPLATE_MAIL_FORM_DEFINITION).getItemProperty(PROPERTY_TEMPLATE).getValue(), PATH_SEPARATOR);
201             String paramStr = (String) items.get(TEMPLATE_MAIL_FORM_DEFINITION).getItemProperty(PROPERTY_DATA).getValue();
202 
203             Iterator<MailTemplate> iter = mailModule.getTemplatesConfiguration().iterator();
204             MailTemplate template = null;
205             while (iter.hasNext()) {
206                 template = iter.next();
207                 if (!template.getName().equals(templateName)) {
208                     template = null;
209                 } else {
210                     break;
211                 }
212             }
213             if (template != null) {
214                 Map<String, Object> params = new HashMap<String, Object>();
215 
216                 String userEmailAddress = PropertyUtil.getString(SessionUtil.getNodeByIdentifier(RepositoryConstants.USERS, MgnlContext.getUser().getIdentifier()), PROPERTY_EMAIL);
217                 if (StringUtils.isBlank(userEmailAddress)) {
218                     context.openNotification(MessageStyleTypeEnum.ERROR, true, translator.translate("mail.app.verify.button.simple.error.no.email", MgnlContext.getUser().getName()));
219                     return;
220                 }
221                 params.put(MailTemplate.MAIL_TO, userEmailAddress);
222 
223                 if (StringUtils.isNotEmpty(paramStr)) {
224                     params = template.getParameters();
225                     String[] parameters = StringUtils.split(paramStr, "\n");
226                     for (String parameter : parameters) {
227                         String[] value = StringUtils.split(parameter, "=");
228                         if (value.length == 2) {
229                             params.put(value[0], value[1]);
230                         } else {
231                             log.warn("Template mail parameter {} has no value specified.", value[0]);
232                             params.put(value[0], "");
233                         }
234                     }
235                 }
236 
237                 MgnlEmail email = mailModule.getFactory().getEmailFromTemplate(template.getName(), template.getAttachments(), params);
238                 email.addRecipient(RecipientType.TO, new InternetAddress(userEmailAddress));
239                 email.setBodyFromResourceFile();
240                 mailModule.getHandler().sendMail(email);
241                 context.openNotification(MessageStyleTypeEnum.INFO, true, translator.translate(BUTTON_TEMPLATE_MAIL_SUCCESS, template.getName(), userEmailAddress));
242             }
243         } catch (Exception e) {
244             log.error("Unable to send email.", e);
245             context.openNotification(MessageStyleTypeEnum.ERROR, true, translator.translate(BUTTON_TEMPLATE_MAIL_ERROR, e.getMessage()));
246         }
247     }
248 
249 }