minafaw3

configureInlineImagesForInternal

May 13th, 2020
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. private String configureInlineImagesForInternal(String body) {
  2. if(body.equals("")) {
  3. return "<p></p>";
  4. }
  5. JerryParser jerry = Jerry.jerry();
  6.  
  7. //Jerry uses Lagarto behind the scenes, so we get the LagartoDOMBuilder to configure it
  8. LagartoDOMBuilder domBuilder = (LagartoDOMBuilder) jerry.getDOMBuilder();
  9. //We want to parse HTML, not XML, et al.
  10. domBuilder.enableHtmlMode();
  11. //By default, Lagarto pretends to handle IE conditional comments, but we want it to ignore
  12. //them and treat them as normal comments so the HTML roundtrips the parse
  13. domBuilder.setConditionalCommentExpression(null);
  14. domBuilder.setIgnoreComments(false);
  15.  
  16. //With Lagarto configured, resume the regularly scheduled Jerry Springer show
  17. Jerry htmlBody = jerry.parse(body);
  18. Jerry imgs = htmlBody.find("img");
  19. imgs.forEach(img -> {
  20. String source = img.attr("src");
  21. if(source.startsWith("data") && source.contains("base64")) {
  22. /* case of byte data */
  23. String name = "cid:" + UUID.randomUUID();
  24. byte[] contentBytes = DatatypeConverter.parseBase64Binary(source.split(",")[1]);
  25. byte[] checksum = DigestUtils.sha256(contentBytes);
  26. String attachmentBase64 = DatatypeConverter.printHexBinary(checksum);
  27. File file = fileService.findFileByMD5(attachmentBase64);
  28. if (file == null) {
  29. FileModel fileModel = new FileModel();
  30. fileModel.setData(contentBytes);
  31. fileModel.setName(name);
  32. try {
  33. file = fileService.createFile(fileModel);
  34. } catch (IOException e) {
  35. logger.error("Unable to create file from mail attachment.", e);
  36. }
  37. }
  38. String base = "https://";
  39. if(config.isNotProduction()) {
  40. // no ssl on dev
  41. base = "http://";
  42. }
  43. /* set <img> src to file URL */
  44. img.attr("src", base + config.getHostname() + "/files/" + file.getId() + "/" + name);
  45. }
  46. });
  47. return htmlBody.html();
  48. }
Add Comment
Please, Sign In to add comment