PageRenderTime 32ms CodeModel.GetById 18ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/hudson/plugins/emailext/EmailRecipientUtils.java

https://gitlab.com/github-cloud-corp/email-ext-plugin
Java | 189 lines | 166 code | 21 blank | 2 comment | 52 complexity | 3afa834b19784d34bef130e421704cbc MD5 | raw file
  1package hudson.plugins.emailext;
  2
  3import java.io.UnsupportedEncodingException;
  4import java.util.LinkedHashSet;
  5import java.util.Set;
  6import java.util.logging.Logger;
  7
  8import javax.mail.internet.AddressException;
  9import javax.mail.internet.InternetAddress;
 10
 11import hudson.EnvVars;
 12import hudson.model.TaskListener;
 13import hudson.model.User;
 14import hudson.plugins.emailext.plugins.ContentBuilder;
 15import hudson.tasks.Mailer;
 16import hudson.util.FormValidation;
 17import java.util.StringTokenizer;
 18import java.util.logging.Level;
 19import javax.mail.MessagingException;
 20import jenkins.model.Jenkins;
 21import org.apache.commons.lang.StringUtils;
 22
 23public class EmailRecipientUtils {
 24
 25    private static final Logger LOGGER = Logger.getLogger(EmailRecipientUtils.class.getName());
 26
 27    public static final int TO = 0;
 28    public static final int CC = 1;
 29    public static final int BCC = 2;
 30    
 31    public static Set<InternetAddress> convertRecipientString(String recipientList, EnvVars envVars)
 32            throws AddressException, UnsupportedEncodingException {
 33        return convertRecipientString(recipientList, envVars, TO);
 34    }
 35    
 36    public static Set<InternetAddress> convertRecipientString(String recipientList, EnvVars envVars, int type)
 37        throws AddressException, UnsupportedEncodingException {
 38        final Set<InternetAddress> internetAddresses = new LinkedHashSet<>();
 39        if (!StringUtils.isBlank(recipientList)) {
 40            final String expandedRecipientList = fixupDelimiters(envVars.expand(recipientList));
 41            InternetAddress[] all = InternetAddress.parse(expandedRecipientList.replace("bcc:", "").replace("cc:", ""));
 42            final Set<InternetAddress> to = new LinkedHashSet<>();
 43            final Set<InternetAddress> cc = new LinkedHashSet<>();
 44            final Set<InternetAddress> bcc = new LinkedHashSet<>();
 45            final String defaultSuffix = ExtendedEmailPublisher.descriptor().getDefaultSuffix();
 46
 47            for(InternetAddress address : all) {
 48                if(address.getPersonal() != null) {
 49                    if(expandedRecipientList.contains("bcc:" + address.getPersonal()) || expandedRecipientList.contains("bcc:\"" + address.toString() + "\"")) {
 50                        bcc.add(address);
 51                    } else if(expandedRecipientList.contains("cc:" + address.getPersonal()) || expandedRecipientList.contains("cc:\"" + address.toString() + "\"")) {
 52                        cc.add(address);
 53                    } else {
 54                        to.add(address);
 55                    }
 56                } else {
 57                    if(expandedRecipientList.contains("bcc:" + address.toString())) {
 58                        bcc.add(address);
 59                    } else if(expandedRecipientList.contains("cc:" + address.toString())) {
 60                        cc.add(address);
 61                    } else {
 62                        to.add(address);
 63                    }
 64                }
 65            }
 66
 67            if(type == BCC) {
 68                internetAddresses.addAll(bcc);
 69            } else if(type == CC) {
 70                internetAddresses.addAll(cc);
 71            } else {
 72                internetAddresses.addAll(to);
 73            }
 74
 75            for(InternetAddress address : internetAddresses) {
 76                if(!address.getAddress().contains("@")) {
 77                    User u = User.get(address.getAddress(), false, null);
 78                    String userEmail;
 79                    if(u != null) {
 80                        userEmail = getUserConfiguredEmail(u);
 81                        if(userEmail != null){
 82                            //if configured user email does not have @domain prefix, then default prefix will be added on next step
 83                            address.setAddress(userEmail);
 84                        }
 85                    }
 86                }
 87
 88                if(!address.getAddress().contains("@") && defaultSuffix != null && defaultSuffix.contains("@")) {
 89                    address.setAddress(address.getAddress() + defaultSuffix);
 90                }
 91
 92                if(address.getPersonal() != null) {
 93                    address.setPersonal(address.getPersonal(), ExtendedEmailPublisher.descriptor().getCharset());
 94                }
 95            }
 96        }
 97        return internetAddresses;
 98    }
 99
100    public static String getUserConfiguredEmail(User user) {
101        String addr = null;
102        if(user != null) {
103            Mailer.UserProperty mailProperty = user.getProperty(Mailer.UserProperty.class);
104            if (mailProperty != null) {
105                addr = mailProperty.getAddress();
106                String message = String.format("Resolved %s to %s", user.getId(), addr);
107                LOGGER.fine(message);
108            }
109        }
110        return addr;
111    }
112
113    public FormValidation validateFormRecipientList(String recipientList) {
114        // Try and convert the recipient string to a list of InternetAddress. If this fails then the validation fails.
115        try {
116            convertRecipientString(recipientList, new EnvVars(), TO);
117            convertRecipientString(recipientList, new EnvVars(), BCC);
118            convertRecipientString(recipientList, new EnvVars(), CC);
119            return FormValidation.ok();
120        } catch (AddressException e) {
121            return FormValidation.error(e.getMessage() + ": \"" + e.getRef() + "\"");
122        } catch(UnsupportedEncodingException e) {
123            return FormValidation.error(e.getMessage());
124        }
125    }
126
127    private static String fixupDelimiters(String input) {
128        input = input.replaceAll("\\s+", " ");
129        if(input.contains(" ") && !input.contains(",")) {
130            input = input.replace(" ", ",");
131        }
132
133        input = input.replace(';', ',');
134        return input;
135    }
136    
137    public static boolean isExcludedRecipient(String userName, TaskListener listener) {
138        ExtendedEmailPublisherDescriptor descriptor = Jenkins.getActiveInstance().getDescriptorByType(ExtendedEmailPublisherDescriptor.class);
139        if(descriptor.getExcludedCommitters() != null) {
140            StringTokenizer tokens = new StringTokenizer(descriptor.getExcludedCommitters(), ", ");
141            while (tokens.hasMoreTokens()) {
142                String check = tokens.nextToken().trim();
143                descriptor.debug(listener.getLogger(), "Checking '%s' against '%s' to see if they are excluded", userName, check);
144                if (check.equalsIgnoreCase(userName)) {
145                    return true;
146                }
147            }
148        }
149        return false;
150    }
151    
152    public static boolean isExcludedRecipient(User user, TaskListener listener) {
153        Mailer.UserProperty prop = user.getProperty(Mailer.UserProperty.class);
154        String[] testValues = new String[] { user.getFullName(), user.getId(), user.getDisplayName(), prop != null ? prop.getAddress() : null };
155        for(String testValue : testValues) {
156            if(testValue != null && isExcludedRecipient(testValue, listener)) {
157                return true;
158            }
159        }
160        return false;
161    }
162    
163    public static void addAddressesFromRecipientList(Set<InternetAddress> to, Set<InternetAddress> cc, Set<InternetAddress> bcc, String recipientList,
164            EnvVars envVars, TaskListener listener) {
165        try {
166            Set<InternetAddress> internetAddresses = convertRecipientString(recipientList, envVars, EmailRecipientUtils.TO);
167            to.addAll(internetAddresses);
168            if(bcc != null) {
169                Set<InternetAddress> bccInternetAddresses = convertRecipientString(recipientList, envVars, EmailRecipientUtils.BCC);
170                bcc.addAll(bccInternetAddresses);
171            }
172            if(cc != null) {
173                Set<InternetAddress> ccInternetAddresses = convertRecipientString(recipientList, envVars, EmailRecipientUtils.CC);
174                cc.addAll(ccInternetAddresses);
175            }
176        } catch (AddressException ae) {
177            LOGGER.log(Level.WARNING, "Could not create email address.", ae);
178            listener.getLogger().println("Failed to create e-mail address for " + ae.getRef());
179        } catch(UnsupportedEncodingException e) {
180            LOGGER.log(Level.WARNING, "Could not create email address.", e);
181            listener.getLogger().println("Failed to create e-mail address because of invalid encoding");
182        }
183    }
184    
185    public static String getRecipientList(ExtendedEmailPublisherContext context, String recipients)
186        throws MessagingException {
187        return StringUtils.isBlank(recipients) ? "" : ContentBuilder.transformText(recipients, context, context.getPublisher().getRuntimeMacros(context));
188    }
189}