Subversion Repositories linshare

[/] [branches/] [0.7/] [linshare/] [src/] [main/] [java/] [org/] [linagora/] [linShare/] [view/] [tapestry/] [components/] [ConfirmSharePopup.java] - Blame information for rev 167

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 1 sbahloul
/*
2
 *    This file is part of Linshare.
3
 *
4
 *   Linshare is free software: you can redistribute it and/or modify
5
 *   it under the terms of the GNU Affero General Public License as
6
 *   published by the Free Software Foundation, either version 3 of
7
 *   the License, or (at your option) any later version.
8
 *
9
 *   Linshare is distributed in the hope that it will be useful,
10
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 *   GNU Affero General Public License for more details.
13
 *
14
 *   You should have received a copy of the GNU Affero General Public
15
 *   License along with Foobar.  If not, see
16
 *                                    <http://www.gnu.org/licenses/>.
17
 *
18
 *   (c) 2008 Groupe Linagora - http://linagora.org
19
 *
20
*/
21
package org.linagora.linShare.view.tapestry.components;
22
 
23
import java.io.IOException;
24 25 sduprey
import java.text.DateFormat;
25 1 sbahloul
import java.util.ArrayList;
26 25 sduprey
import java.util.Calendar;
27
import java.util.Date;
28 1 sbahloul
import java.util.HashSet;
29
import java.util.List;
30
import java.util.Set;
31
import java.util.StringTokenizer;
32
import java.util.regex.Pattern;
33
 
34
import org.apache.tapestry5.Asset;
35
import org.apache.tapestry5.BindingConstants;
36
import org.apache.tapestry5.Block;
37 45 sduprey
import org.apache.tapestry5.ComponentResources;
38 43 sduprey
import org.apache.tapestry5.RenderSupport;
39
import org.apache.tapestry5.annotations.AfterRender;
40 1 sbahloul
import org.apache.tapestry5.annotations.ApplicationState;
41
import org.apache.tapestry5.annotations.Component;
42 43 sduprey
import org.apache.tapestry5.annotations.Environmental;
43
import org.apache.tapestry5.annotations.IncludeJavaScriptLibrary;
44 1 sbahloul
import org.apache.tapestry5.annotations.InjectComponent;
45
import org.apache.tapestry5.annotations.Parameter;
46
import org.apache.tapestry5.annotations.Path;
47
import org.apache.tapestry5.annotations.Persist;
48
import org.apache.tapestry5.annotations.Property;
49
import org.apache.tapestry5.annotations.SetupRender;
50
import org.apache.tapestry5.corelib.components.Form;
51
import org.apache.tapestry5.ioc.Messages;
52
import org.apache.tapestry5.ioc.annotations.Inject;
53 25 sduprey
import org.apache.tapestry5.services.PersistentLocale;
54 1 sbahloul
import org.linagora.linShare.core.Facade.RecipientFavouriteFacade;
55 25 sduprey
import org.linagora.linShare.core.Facade.ShareExpiryDateFacade;
56 1 sbahloul
import org.linagora.linShare.core.Facade.ShareFacade;
57
import org.linagora.linShare.core.Facade.UserFacade;
58
import org.linagora.linShare.core.domain.objects.SuccessesAndFailsItems;
59
import org.linagora.linShare.core.domain.vo.DocumentVo;
60
import org.linagora.linShare.core.domain.vo.ShareDocumentVo;
61
import org.linagora.linShare.core.domain.vo.UserVo;
62
import org.linagora.linShare.core.exception.BusinessException;
63
import org.linagora.linShare.core.exception.TechnicalErrorCode;
64
import org.linagora.linShare.core.exception.TechnicalException;
65 25 sduprey
import org.linagora.linShare.core.utils.FileUtils;
66 1 sbahloul
import org.linagora.linShare.view.tapestry.beans.ShareSessionObjects;
67
import org.linagora.linShare.view.tapestry.services.Templating;
68
import org.linagora.linShare.view.tapestry.services.impl.PropertiesSymbolProvider;
69
import org.slf4j.Logger;
70
import org.slf4j.LoggerFactory;
71
 
72 43 sduprey
@IncludeJavaScriptLibrary("SizeOfPopup.js")
73 1 sbahloul
public class ConfirmSharePopup{
74
        private static final Logger logger = LoggerFactory.getLogger(ConfirmSharePopup.class);
75
 
76
        @ApplicationState
77
        private UserVo userVo;
78
 
79
        @ApplicationState
80
        private ShareSessionObjects shareSessionObjects;
81
 
82
 
83
        @SuppressWarnings("unused")
84
        @Parameter(required=true,defaultPrefix=BindingConstants.PROP)
85
        @Property
86
        private List<UserVo> usersVo;
87
 
88
        @SuppressWarnings("unused")
89
        @Parameter(required=true,defaultPrefix=BindingConstants.PROP)
90
        @Property
91
        private List<DocumentVo> documentsVo;
92
 
93
        @SuppressWarnings("unused")
94
        @Component(parameters = {"style=bluelighting", "show=false","width=650", "height=550"})
95
        private WindowWithEffects confirmWindow;
96
 
97
        @SuppressWarnings("unused")
98
        @Parameter(required=true,defaultPrefix=BindingConstants.LITERAL)
99
        @Property
100
        private String messageLabel;
101
 
102
        @SuppressWarnings("unused")
103
        @Parameter(required=true,defaultPrefix=BindingConstants.LITERAL)
104
        private String eventName;
105
 
106
 
107
        @Inject
108
        private Messages messages;
109
 
110
        @Inject
111
        private Templating templating;
112
 
113
        @Property
114
        private String textAreaValue;
115
 
116 147 sduprey
        @Property
117
        private String textAreaSubjectValue;
118 1 sbahloul
 
119 147 sduprey
 
120 1 sbahloul
        @Persist("flash")
121
        @Property
122
        private String recipientsSearch;
123
 
124
        @Persist("flash")
125
        @Property
126
        private boolean secureSharing;
127
 
128
 
129
        @Persist("flash")
130
        private List<String> recipientsEmail;
131
 
132
 
133
    // The block that contains the action to be thrown on success 
134
        @Inject
135
        private Block onSuccess;
136
 
137
    // The block that contains the action to be thrown on failure
138
        @Inject
139
        private Block onFailure;
140
 
141
    @InjectComponent
142
    private Form confirmshare;
143
 
144 25 sduprey
        @InjectComponent
145
        private DatePicker datePicker;
146
 
147
        @Property
148
        @Persist
149
        private Date minDatePicker;
150
        @Property
151
        @Persist
152
        private Date maxDatePicker;
153
        @Property
154
        private Date defaultDatePicker;
155 1 sbahloul
 
156 25 sduprey
        @Property
157
        private String tooltipValue;
158
        @Property
159
        private String tooltipTitle;
160
 
161
 
162 1 sbahloul
        /* ***********************************************************
163
         *                      Injected services
164
         ************************************************************ */
165
        @Inject
166
        @Path("context:templates/shared-message.html")
167
        private Asset sharedTemplate;
168
 
169
        @Inject
170
        @Path("context:templates/shared-message.txt")
171
        private Asset sharedTemplateTxt;
172
 
173
        @Inject
174
        @Path("context:templates/shared-message-withpassword.html")
175
        private Asset passwordSharedTemplate;
176
 
177
        @Inject
178
        @Path("context:templates/shared-message-withpassword.txt")
179
        private Asset passwordSharedTemplateTxt;
180
 
181
        @Inject
182
        private ShareFacade shareFacade;
183
 
184
        @Inject
185
        private UserFacade userFacade;
186
 
187
        @Inject
188 25 sduprey
        private PersistentLocale persistentLocale;
189
 
190
        @Inject
191
        private ShareExpiryDateFacade shareExpiryDateFacade;
192
 
193
        @Inject
194 1 sbahloul
        private RecipientFavouriteFacade recipientFavouriteFacade;
195
 
196
        @Inject
197
        private PropertiesSymbolProvider propertiesSymbolProvider;
198 43 sduprey
 
199
    @Environmental
200
    private RenderSupport renderSupport;
201 1 sbahloul
 
202 45 sduprey
        @Inject
203
        private ComponentResources componentResources;
204
 
205 1 sbahloul
        /* ***********************************************************
206
         *                   Event handlers&processing
207
         ************************************************************ */
208
 
209
 
210
        /**
211
         * Initialization of the form.
212
         */
213
        @SetupRender
214
        public void init() {
215
 
216
                //init emails list for selected users
217
                if(usersVo!=null && usersVo.size()>0){
218
                        String emails="";
219
                        for (UserVo recipient : usersVo) {
220
                                emails = emails + formatLabel(recipient)+',';
221
                        }
222
                        recipientsSearch = emails.substring(0,emails.length()-1); //delete last comma.
223
                }
224 25 sduprey
 
225
                computePickerDates();
226
                buildTooltipValue();
227 1 sbahloul
        }
228 43 sduprey
 
229
        @AfterRender
230
    public void afterRender() {
231
        //resize the share popup
232
        renderSupport.addScript(String.format("confirmWindow.setSize(650, getHeightForPopup())"));
233
    }
234 1 sbahloul
 
235 25 sduprey
        /**
236
         * Compute the minDate, maxDate and defaultDate the user can select in
237
         * the datePicker for the expiration date of the share
238
         */
239
        private void computePickerDates() {
240
                Calendar today = Calendar.getInstance();
241
                today.add(Calendar.DAY_OF_MONTH, 1);
242
                minDatePicker = today.getTime();
243
                Calendar expiryDateMin = shareExpiryDateFacade.computeMinShareExpiryDateOfList(documentsVo);
244
                defaultDatePicker = expiryDateMin.getTime();
245
                maxDatePicker = expiryDateMin.getTime();
246
        }
247
 
248
        /**
249
         * Build the content (title and message) of the tooltip which explain
250
         * how the expiration date of files is computed
251
         */
252
        private void buildTooltipValue() {
253
                DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, persistentLocale.get());
254
                tooltipTitle = messages.get("components.confirmSharePopup.tooltip.title");
255
 
256
                StringBuffer value = new StringBuffer();
257
                value.append("<p class='tooltipTableDescription'>");
258
                value.append(messages.get("components.confirmSharePopup.tooltip.description"));
259
                value.append("</p>");
260
                value.append("<table class='tooltipTable'><tr><th>");
261
                value.append(messages.get("components.confirmSharePopup.tooltip.table.file"));
262
                value.append("</th><th>");
263
                value.append(messages.get("components.confirmSharePopup.tooltip.table.size"));
264
                value.append("</th><th>");
265
                value.append(messages.get("components.confirmSharePopup.tooltip.table.date"));
266
                value.append("</th></tr>");
267
                for (DocumentVo docVo : documentsVo) {
268
                        value.append("<tr><td>");
269 32 sduprey
                        String docName = docVo.getFileName();
270
                        if (docName.length() > 28) {
271
                                docName = docName.substring(0, 28).concat("...");
272
                        }
273
                        value.append(docName);
274
                        value.append("</td><td class='nowrap'>");
275 25 sduprey
                        value.append(FileUtils.getFriendlySize(docVo.getSize(), messages));
276
                        value.append("</td><td>");
277
                        value.append(dateFormat.format(shareExpiryDateFacade.computeShareExpiryDate(docVo).getTime()));
278
                        value.append("</td></tr>");
279
                }
280
                value.append("</table>");
281
 
282
                tooltipValue = value.toString();
283
        }
284
 
285 1 sbahloul
        public List<String> onProvideCompletionsFromRecipientsPatternSharePopup(String input) {
286
                List<UserVo> searchResults = performSearch(input);
287
 
288
                List<String> elements = new ArrayList<String>();
289
                for (UserVo user : searchResults) {
290
                         String completeName = formatLabel(user);
291
            if (!elements.contains(completeName)) {
292
                elements.add(completeName);
293
            }
294
                }
295
 
296
                return elements;
297
        }
298
 
299
        private String formatLabel(UserVo user){
300
                StringBuffer buf = new StringBuffer();
301
 
302
                if(user.getLastName()!=null&&user.getFirstName()!=null){
303
                        //uservo from USER table or ldap
304
                        buf.append("\"").append(user.getLastName().trim()).append(" ").append(user.getFirstName().trim()).append("\"");
305
                        buf.append(" <").append(user.getMail()).append(">,");
306
                } else {
307
                        //uservo from favorite table
308
                        buf.append(user.getMail()).append(",");
309
                }
310
                return buf.toString();
311
        }
312
 
313
        // "Michael georges" <michael@linagora.com>,"Laporte Robert" <robert@robert.com>,bruce.willis@orange.fr,...
314
        private static List<String> parseEmails(String recipientsList){
315
 
316
                String[] recipients = recipientsList.split(",");
317
                ArrayList<String> emails = new ArrayList<String> ();
318
 
319
                for (String oneUser : recipients) {
320
 
321
                        String email = contentInsideToken(oneUser, "<",">");
322
                        if(email==null) email = oneUser.trim();
323
 
324
                        if(!email.equals("")) //ignore empty string
325
                        emails.add(email); // add good and bad email
326
                }
327
 
328
                return emails;
329
        }
330
 
331
 
332
        public static String contentInsideToken(String str,String tokenright,String tokenleft) {
333
                int deb = str.indexOf(tokenright,0);
334
                int end = str.indexOf(tokenleft,1);
335
                if(deb==-1||end==-1) return null;
336
                else return str.substring(deb+1, end).trim();
337
        }
338
 
339
        private static final Pattern MAILREGEXP = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$");
340
 
341
 
342
 
343
        /** Perform a user search using the user search pattern.
344
         * @param input user search pattern.
345
         * @return list of users.
346
         */
347
        private List<UserVo> performSearch(String input) {
348
 
349
 
350
                Set<UserVo> userSet = new HashSet<UserVo>();
351
 
352
                String firstName_ = null;
353
                String lastName_ = null;
354
 
355
                if (input != null && input.length() > 0) {
356
                        StringTokenizer stringTokenizer = new StringTokenizer(input, " ");
357
                        if (stringTokenizer.hasMoreTokens()) {
358
                                firstName_ = stringTokenizer.nextToken();
359
                                if (stringTokenizer.hasMoreTokens()) {
360
                                        lastName_ = stringTokenizer.nextToken();
361
                                }
362
                        }
363
                }
364
 
365
        if (input != null) {
366
            userSet.addAll(userFacade.searchUser(input.trim(), null, null,userVo));
367
        }
368
                userSet.addAll(userFacade.searchUser(null, firstName_, lastName_, userVo));
369
                userSet.addAll(userFacade.searchUser(null, lastName_, firstName_,  userVo));
370
                userSet.addAll(recipientFavouriteFacade.findRecipientFavorite(input.trim(), userVo));
371
 
372
                return recipientFavouriteFacade.recipientsOrderedByWeightDesc(new ArrayList<UserVo>(userSet), userVo);
373
        }
374
 
375
 
376
 
377
        public void onValidateFormFromConfirmshare() throws BusinessException {
378
 
379
        if (confirmshare.getHasErrors()) {
380
                return ;
381
        }
382
 
383
        boolean sendErrors = false;
384
 
385
                List<String> recipients = parseEmails(recipientsSearch);
386
                String badFormatEmail =  "";
387
 
388
                for (String recipient : recipients) {
389
                        if (!MAILREGEXP.matcher(recipient.toUpperCase()).matches()){
390
                                badFormatEmail = badFormatEmail + recipient + " ";
391
                                sendErrors = true;
392
                        }
393
                }
394
 
395
                if(sendErrors) {
396
                        confirmshare.recordError(String.format(messages.get("components.confirmSharePopup.validate.email"), badFormatEmail));
397
                }
398
                else {
399
                        this.recipientsEmail = recipients;
400
                }
401
        }
402
 
403
    public Block onFailure() {
404
        return onFailure;
405
    }
406
 
407
 
408
    public Block onSuccess() throws BusinessException {
409 25 sduprey
        /**
410
                 * verify the value of the expiration date selected
411
                 *
412
                 */
413
                Calendar dateExpiry = Calendar.getInstance();
414
                Date dateSelected = datePicker.getDatePicked();
415
                if (dateSelected == null || dateSelected.after(maxDatePicker) || dateSelected.before(Calendar.getInstance().getTime())) {
416
                        dateExpiry = null;
417
                }
418
                else dateExpiry.setTime(dateSelected);
419 1 sbahloul
 
420
                /**
421
                 * retrieve the url from propertie file
422
                 *
423
                 */
424 167 sduprey
                String linShareUrlInternal=propertiesSymbolProvider.valueForSymbol("linshare.info.url.internal");
425
                String linShareUrlBase=propertiesSymbolProvider.valueForSymbol("linshare.info.url.base");
426 1 sbahloul
 
427
                /**
428
                 * retrieve the subject of the mail.
429
                 */
430 147 sduprey
                String subject = "";
431
                if (textAreaSubjectValue==null || textAreaSubjectValue.trim().length()==0) {
432
                        subject=messages.get("mail.user.all.share.subject");
433
                }
434
                else {
435
                        subject = textAreaSubjectValue;
436
                }
437 1 sbahloul
 
438
                // prevent NPE
439
                if (textAreaValue==null)
440
                        textAreaValue = "";
441
 
442
                //html template
443
                String sharedTemplateContent = null;
444
                String passwordSharedTemplateContent = null;
445
                //TXT template
446
                String sharedTemplateContentTxt = null;
447
                String passwordSharedTemplateContentTxt = null;
448
 
449
                try {
450
                        sharedTemplateContent = templating.readFullyTemplateContent(sharedTemplate.getResource().openStream());
451
                        passwordSharedTemplateContent = templating.readFullyTemplateContent(passwordSharedTemplate.getResource().openStream());
452
 
453
                        sharedTemplateContentTxt = templating.readFullyTemplateContent(sharedTemplateTxt.getResource().openStream());
454
                        passwordSharedTemplateContentTxt = templating.readFullyTemplateContent(passwordSharedTemplateTxt.getResource().openStream());
455
 
456
                } catch (IOException e) {
457
                        logger.error("Bad mail template", e);
458
                        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION,"Bad template",e);
459
                }
460
                SuccessesAndFailsItems<ShareDocumentVo> sharing = new SuccessesAndFailsItems<ShareDocumentVo>();
461
                try {
462
 
463
                        //OLD CALL with userVo !
464
                        //sharing = shareFacade.createSharingWithMail(userVo, documentsVo, usersVo,textAreaValue, message,subject);
465
 
466
                        //CALL new share function with all adress mails !
467 167 sduprey
                        sharing = shareFacade.createSharingWithMailUsingRecipientsEmailAndExpiryDate(userVo, documentsVo,recipientsEmail,textAreaValue,subject,linShareUrlInternal, linShareUrlBase,secureSharing,sharedTemplateContent,sharedTemplateContentTxt,passwordSharedTemplateContent,passwordSharedTemplateContentTxt, dateExpiry);
468 1 sbahloul
 
469
 
470
 
471
                } catch (BusinessException e1) {
472
                        logger.error("Could not create sharing", e1);
473
                        throw e1;
474
                }
475
 
476
 
477
                shareSessionObjects=new ShareSessionObjects();
478
                if (sharing.getFailsItem().size()>0) {
479 146 sduprey
                        shareSessionObjects.addError(messages.get("components.confirmSharePopup.fail"));
480 1 sbahloul
                } else {
481
                        recipientFavouriteFacade.increment(userVo, recipientsEmail);
482
                        shareSessionObjects.addMessage(messages.get("components.confirmSharePopup.success"));
483 45 sduprey
                        componentResources.triggerEvent("resetListFiles", null, null);
484 1 sbahloul
                }
485
 
486
                return onSuccess;
487
 
488
        }
489
 
490
 
491
        public String getJSONId() {
492
                return confirmWindow.getJSONId();
493
        }
494
 
495
 
496
}