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