src/org/sonews/storage/DrupalMessage.java
author František Kučera <franta-hg@frantovo.cz>
Tue Oct 25 10:39:57 2011 +0200 (2011-10-25)
changeset 108 fdc075324ef3
parent 105 d566d08c20d6
child 109 03cc47e9daee
permissions -rw-r--r--
SMTP: correct escaping of messages containing lines with single dot.
     1 /*
     2  *   SONEWS News Server
     3  *   see AUTHORS for the list of contributors
     4  *
     5  *   This program is free software: you can redistribute it and/or modify
     6  *   it under the terms of the GNU General Public License as published by
     7  *   the Free Software Foundation, either version 3 of the License, or
     8  *   (at your option) any later version.
     9  *
    10  *   This program is distributed in the hope that it will be useful,
    11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  *   GNU General Public License for more details.
    14  *
    15  *   You should have received a copy of the GNU General Public License
    16  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17  */
    18 package org.sonews.storage;
    19 
    20 import java.io.BufferedReader;
    21 import java.io.ByteArrayInputStream;
    22 import java.io.ByteArrayOutputStream;
    23 import java.io.IOException;
    24 import java.io.InputStream;
    25 import java.io.InputStreamReader;
    26 import java.io.PrintStream;
    27 import java.io.StringReader;
    28 import java.io.StringWriter;
    29 import java.io.UnsupportedEncodingException;
    30 import java.sql.ResultSet;
    31 import java.sql.SQLException;
    32 import java.util.ArrayList;
    33 import java.util.Date;
    34 import java.util.Enumeration;
    35 import java.util.logging.Level;
    36 import java.util.logging.Logger;
    37 import javax.mail.Header;
    38 import javax.mail.MessagingException;
    39 import javax.mail.Multipart;
    40 import javax.mail.Session;
    41 import javax.mail.internet.InternetAddress;
    42 import javax.mail.internet.MimeBodyPart;
    43 import javax.mail.internet.MimeMessage;
    44 import javax.mail.internet.MimeMultipart;
    45 import javax.xml.parsers.DocumentBuilder;
    46 import javax.xml.parsers.DocumentBuilderFactory;
    47 import javax.xml.parsers.ParserConfigurationException;
    48 import javax.xml.transform.Transformer;
    49 import javax.xml.transform.TransformerException;
    50 import javax.xml.transform.TransformerFactory;
    51 import javax.xml.transform.dom.DOMSource;
    52 import javax.xml.transform.stream.StreamResult;
    53 import javax.xml.transform.stream.StreamSource;
    54 import org.sonews.daemon.NNTPConnection;
    55 import org.sonews.util.io.Resource;
    56 import org.w3c.dom.Document;
    57 import org.xml.sax.SAXException;
    58 
    59 /**
    60  * This is MimeMessage which enables custom Message-ID header
    61  * (this header will not be overwritten by the default one like in MimeMessage).
    62  * 
    63  * Also add header and body separate serialization.
    64  * 
    65  * And can be deserialized from SQL ResultSet
    66  * 
    67  * @author František Kučera (frantovo.cz)
    68  */
    69 public class DrupalMessage extends MimeMessage {
    70 
    71 	private static final Logger log = Logger.getLogger(DrupalMessage.class.getName());
    72 	private static final String MESSAGE_ID_HEADER = "Message-ID";
    73 	private static final String CRLF = "\r\n";
    74 	public static final String CHARSET = "UTF-8";
    75 	private static final String XHTML_CONTENT_TYPE = "text/html; charset=" + CHARSET;
    76 	private static final String ZNAKČKA_KONCE_ŘÁDKU = "◆";
    77 	private String messageID;
    78 	private Long parentID;
    79 	private Long groupID;
    80 	private TransformerFactory transformerFactory;
    81 	private DocumentBuilderFactory documentBuilderFactory;
    82 
    83 	/**
    84 	 * Initializes XML factories (Transformer, DocumentBuilder).
    85 	 */
    86 	private void initFactories() {
    87 		transformerFactory = TransformerFactory.newInstance();
    88 		documentBuilderFactory = DocumentBuilderFactory.newInstance();
    89 		/**
    90 		 * Komentáře nás nepotřebujeme 
    91 		 * (a museli bychom je brát v úvahu při dělení odstavců:
    92 		 * v současné verzi XSLT odstavcovače by nám případný komentář
    93 		 * rozdělil text na dva odstavce, přestože to má být odstavec jede).
    94 		 */
    95 		documentBuilderFactory.setIgnoringComments(true);
    96 	}
    97 
    98 	/**
    99 	 * Constructs MIME message from SQL result.
   100 	 * @param rs ResultSet containing message data. No {@link ResultSet#next()} will be called, just values from current row will be read.
   101 	 * @param constructBody true if whole message should be constructed | false if we need only message headers (body will be dummy).
   102 	 */
   103 	public DrupalMessage(ResultSet rs, String myDomain, boolean constructBody) throws SQLException, UnsupportedEncodingException, MessagingException, TransformerException, IOException, ParserConfigurationException, SAXException {
   104 		super(Session.getDefaultInstance(System.getProperties()));
   105 		initFactories();
   106 
   107 		groupID = rs.getLong("group_id");
   108 		addHeader("Message-id", constructMessageId(rs.getInt("id"), groupID, rs.getString("group_name"), myDomain));
   109 		addHeader("Newsgroups", rs.getString("group_name"));
   110 		setFrom(new InternetAddress(rs.getString("sender_email"), rs.getString("sender_name")));
   111 		setSubject(rs.getString("subject"));
   112 		setSentDate(new Date(rs.getLong("created")));
   113 
   114 		parentID = rs.getLong("parent_id");
   115 		if (parentID > 0) {
   116 			String parentMessageID = constructMessageId(parentID, rs.getInt("group_id"), rs.getString("group_name"), myDomain);
   117 			addHeader("In-Reply-To", parentMessageID);
   118 			addHeader("References", parentMessageID);
   119 		}
   120 
   121 		if (constructBody) {
   122 			Multipart multipart = new MimeMultipart("alternative");
   123 			setContent(multipart);
   124 
   125 			/** XHTML part */
   126 			MimeBodyPart htmlPart = new MimeBodyPart();
   127 			String xhtmlText = readXhtmlText(
   128 					rs.getString("text"),
   129 					rs.getString("subject"),
   130 					rs.getInt("parent_id"),
   131 					rs.getString("urlBase"),
   132 					rs.getString("wwwRead"),
   133 					rs.getString("wwwPost"));
   134 			htmlPart.setContent(xhtmlText, XHTML_CONTENT_TYPE);
   135 
   136 			/** Plain text part */
   137 			MimeBodyPart textPart = new MimeBodyPart();
   138 			String plainText = formatedToPlainText(xhtmlText);
   139 			textPart.setText(plainText);
   140 			//addHeader("Lines", String.valueOf(plainText.split("\n").length));
   141 
   142 			/**
   143 			 * Thunderbirdu záleží, v jakém pořadí části jsou 
   144 			 * (když je prostý text druhý, html se nezobrazí),
   145 			 * KNode zobrazuje HTML správně, i když je na prvním místě.
   146 			 */
   147 			multipart.addBodyPart(textPart);
   148 			multipart.addBodyPart(htmlPart);
   149 		} else {
   150 			/** empty body, just headers */
   151 			setText("");
   152 		}
   153 	}
   154 
   155 	/**
   156 	 * Constructs MIME message from article posted by user.
   157 	 * @param article article that came through NNTP.
   158 	 * @throws MessagingException 
   159 	 */
   160 	public DrupalMessage(Article article) throws MessagingException {
   161 		super(Session.getDefaultInstance(System.getProperties()), serializeArticle(article));
   162 		initFactories();
   163 
   164 		String[] parentHeaders = getHeader("In-Reply-To");
   165 		if (parentHeaders != null && parentHeaders.length == 1) {
   166 			String parentMessageID = parentHeaders[0];
   167 			parentID = parseArticleID(parentMessageID);
   168 			groupID = parseGroupID(parentMessageID);
   169 		} else {
   170 			throw new MessagingException("Message posted by user must have exactly one In-Reply-To header.");
   171 		}
   172 	}
   173 
   174 	private static InputStream serializeArticle(Article a) {
   175 		byte articleHeaders[] = a.getHeaderSource().getBytes();
   176 		byte delimiter[] = (NNTPConnection.NEWLINE + NNTPConnection.NEWLINE).getBytes();
   177 		byte body[] = a.getBody();
   178 
   179 		byte message[] = new byte[articleHeaders.length + delimiter.length + body.length];
   180 
   181 		System.arraycopy(articleHeaders, 0, message, 0, articleHeaders.length);
   182 		System.arraycopy(delimiter, 0, message, articleHeaders.length, delimiter.length);
   183 		System.arraycopy(body, 0, message, articleHeaders.length + delimiter.length, body.length);
   184 
   185 		return new ByteArrayInputStream(message);
   186 	}
   187 
   188 	/**
   189 	 * @param xhtmlText well-formed XHTML
   190 	 * @return plain text representation of this formated text
   191 	 */
   192 	private String formatedToPlainText(String xhtmlText) {
   193 		try {
   194 			Transformer textTransformer = transformerFactory.newTransformer(new StreamSource(Resource.getAsStream("helpers/mimeTextPart.xsl")));
   195 
   196 			StringReader input = new StringReader(xhtmlText);
   197 			StringWriter output = new StringWriter(xhtmlText.length());
   198 			textTransformer.transform(new StreamSource(input), new StreamResult(output));
   199 
   200 			return output.toString();
   201 		} catch (Exception e) {
   202 			/**
   203 			 * TODO: lepší ošetření chyby
   204 			 */
   205 			log.log(Level.WARNING, "Error while transforming article to plain text", e);
   206 			return "Při transformaci příspěvku bohužel došlo k chybě.";
   207 		}
   208 	}
   209 
   210 	private DOMSource readDOM(String xml) throws ParserConfigurationException, SAXException, IOException {
   211 		DocumentBuilder db = documentBuilderFactory.newDocumentBuilder();
   212 		Document d = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
   213 		return new DOMSource(d);
   214 	}
   215 
   216 	private String readXhtmlText(String sourceText, String subject, long parentId, String urlBase, String wwwRead, String wwwPost) throws TransformerException, IOException, ParserConfigurationException, SAXException {
   217 		/**
   218 		 * TODO: 
   219 		 *		- znovupoužívat XSL transformér (nejen v instanci)
   220 		 *		- používat cache, ukládat si vygenerované články
   221 		 */
   222 		String wrappedText = makeSimpleXHTML(sourceText);
   223 
   224 		Transformer paragraphTransformer = transformerFactory.newTransformer(new StreamSource(Resource.getAsStream("helpers/mimeXhtmlPart-make-paragraphs.xsl")));
   225 		String paragraphedText;
   226 		boolean tidyWasUsed = false;
   227 		try {
   228 			StringWriter output = new StringWriter(2 * wrappedText.length());
   229 			paragraphTransformer.transform(readDOM(wrappedText), new StreamResult(output));
   230 			paragraphedText = output.toString();
   231 		} catch (Exception e) {
   232 			log.log(Level.FINER, "HTML input was shitty – Tidy had to be called.", e);
   233 			StringWriter output = new StringWriter(2 * wrappedText.length());
   234 			paragraphTransformer.transform(readDOM(tidyXhtml(wrappedText)), new StreamResult(output));
   235 			paragraphedText = output.toString();
   236 			tidyWasUsed = true;
   237 		}
   238 
   239 		Transformer xhtmlTransformer = transformerFactory.newTransformer(new StreamSource(Resource.getAsStream("helpers/mimeXhtmlPart.xsl")));
   240 		xhtmlTransformer.setParameter("isRoot", (parentId == 0));
   241 		xhtmlTransformer.setParameter("title", subject);
   242 		xhtmlTransformer.setParameter("urlBase", urlBase);
   243 		xhtmlTransformer.setParameter("wwwRead", wwwRead);
   244 		xhtmlTransformer.setParameter("wwwPost", wwwPost);
   245 		xhtmlTransformer.setParameter("headComment", String.format("Drupal-NNTP bridge. Transformed: %1$tc. Tidy had to be used: %2$b", new Date(), tidyWasUsed));
   246 		StringReader paragraphedReader = new StringReader(paragraphedText);
   247 		StringWriter xhtmlWriter = new StringWriter(2 * paragraphedText.length());
   248 		xhtmlTransformer.transform(new StreamSource(paragraphedReader), new StreamResult(xhtmlWriter));
   249 
   250 		return xhtmlWriter.toString();
   251 	}
   252 
   253 	/**
   254 	 * Does not parse XML works just with text.
   255 	 * @param body XHTML fragment that should be put between &lt;body&gt; and &lt;/body&gt;
   256 	 * @return simple XHTML document (body wrapped in html and body tags)
   257 	 */
   258 	private static String makeSimpleXHTML(String body) {
   259 		return "<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>" + body + "</body></html>";
   260 	}
   261 
   262 	/**
   263 	 * Does not parse XML works just with text.
   264 	 * @param xhtml whole XHTML page
   265 	 * @return content between &lt;body&gt; and &lt;/body&gt; tags.
   266 	 */
   267 	private static String makeFragmentXHTML(String xhtml) {
   268 		final String startTag = "<body>";
   269 		final String endTag = "</body>";
   270 
   271 		int start = xhtml.indexOf(startTag) + startTag.length();
   272 		int end = xhtml.lastIndexOf(endTag);
   273 
   274 		return xhtml.substring(start, end);
   275 	}
   276 
   277 	/**
   278 	 * TODO: refaktorovat, přesunout
   279 	 */
   280 	private static String tidyXhtml(String inputText) throws IOException {
   281 		/*
   282 		 * Viz https://sourceforge.net/tracker/index.php?func=detail&aid=3424437&group_id=27659&atid=390966
   283 		 *
   284 		 * TODO:
   285 		 *		- použít delší zástupný řetězec, ne jen jeden znak
   286 		 *		- umísťovat ho jen tam, kde už nějaký text je (ne mezi >\s*<)
   287 		 */
   288 		inputText = označKonceŘádků(inputText);
   289 
   290 		Runtime r = Runtime.getRuntime();
   291 		Process p = r.exec(new String[]{"tidy", // http://tidy.sourceforge.net
   292 					"-asxml", // well formed XHTML
   293 					"-numeric", // číselné entity
   294 					"-utf8", // kódování
   295 					"--show-warnings", "false", // žádná varování nás nezajímají
   296 					"--show-errors", "0", // ani chyby
   297 					"--doctype", "omit", // doctype nepotřebujeme (doplníme si případně vlastní v XSLT)
   298 					"--logical-emphasis", "true", // em a strong místo i a b
   299 					"--literal-attributes", "true", // zachovat mezery a konce řádků v atributech
   300 					"--force-output", "true" // neznámé značky zahodíme, vložíme jen jejich obsah
   301 				});
   302 
   303 		PrintStream vstupProcesu = new PrintStream(p.getOutputStream());
   304 		vstupProcesu.print(inputText);
   305 		vstupProcesu.close();
   306 
   307 		String outputText = streamToString(p.getInputStream());
   308 
   309 		outputText = vraťKonceŘádků(outputText);
   310 
   311 		return outputText;
   312 	}
   313 
   314 	private static String označKonceŘádků(String text) {
   315 		text = text.replaceAll(">\\s+<", "> <");
   316 		text = text.replaceAll("\\n", ZNAKČKA_KONCE_ŘÁDKU + "\n");
   317 		return text;
   318 	}
   319 
   320 	private static String vraťKonceŘádků(String text) {
   321 		text = text.replaceAll(ZNAKČKA_KONCE_ŘÁDKU + "\\n", "\n");
   322 		text = text.replaceAll(ZNAKČKA_KONCE_ŘÁDKU, "\n");
   323 		return text;
   324 	}
   325 
   326 	/**
   327 	 * TODO: refaktorovat, přesunout
   328 	 */
   329 	private static String streamToString(InputStream proud) throws IOException {
   330 		StringBuilder výsledek = new StringBuilder();
   331 		BufferedReader buf = new BufferedReader(new InputStreamReader(proud));
   332 		while (true) {
   333 			String radek = buf.readLine();
   334 			if (radek == null) {
   335 				break;
   336 			} else {
   337 				výsledek.append(radek);
   338 				výsledek.append("\n");
   339 			}
   340 		}
   341 		return výsledek.toString();
   342 	}
   343 
   344 	public static String constructMessageId(long articleID, long groupID, String groupName, String domainName) {
   345 		StringBuilder sb = new StringBuilder();
   346 		sb.append("<");
   347 		sb.append(articleID);
   348 		sb.append("-");
   349 		sb.append(groupID);
   350 		sb.append("-");
   351 		sb.append(groupName);
   352 		sb.append("@");
   353 		sb.append(domainName);
   354 		sb.append(">");
   355 		return sb.toString();
   356 	}
   357 
   358 	/**
   359 	 * @return article ID of parent of this message | or null, if this is root article and not reply to another one
   360 	 */
   361 	public Long getParentID() {
   362 		return parentID;
   363 	}
   364 
   365 	/**
   366 	 * @return group ID of this message | or null, if this message is not reply to any other one – which is wrong because we have to know the group
   367 	 */
   368 	public Long getGroupID() {
   369 		return groupID;
   370 	}
   371 
   372 	/**
   373 	 * 
   374 	 * @param messageID &lt;{0}-{1}-{2}@domain.tld&gt; where {0} is nntp_id and {1} is group_id and {2} is group_name
   375 	 * @return array where [0] = nntp_id and [1] = group_id and [2] = group_name or returns null if messageID is invalid
   376 	 */
   377 	private static String[] parseMessageID(String messageID) {
   378 		if (messageID.matches("<[0-9]+\\-[0-9]+\\-[a-z0-9\\.]+@.+>")) {
   379 			return messageID.substring(1).split("@")[0].split("\\-");
   380 		} else {
   381 			return null;
   382 		}
   383 	}
   384 
   385 	public static Long parseArticleID(String messageID) {
   386 		String[] localPart = parseMessageID(messageID);
   387 		if (localPart == null) {
   388 			return null;
   389 		} else {
   390 			return Long.parseLong(localPart[0]);
   391 		}
   392 	}
   393 
   394 	public static Long parseGroupID(String messageID) {
   395 		String[] localPart = parseMessageID(messageID);
   396 		if (localPart == null) {
   397 			return null;
   398 		} else {
   399 			return Long.parseLong(localPart[1]);
   400 			// If needed:
   401 			// parseGroupName() will be same as this method, just with:
   402 			// return localPart[2];
   403 		}
   404 	}
   405 
   406 	@Override
   407 	public void setHeader(String name, String value) throws MessagingException {
   408 		super.setHeader(name, value);
   409 
   410 		if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
   411 			messageID = value;
   412 		}
   413 	}
   414 
   415 	@Override
   416 	public final void addHeader(String name, String value) throws MessagingException {
   417 		super.addHeader(name, value);
   418 
   419 		if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
   420 			messageID = value;
   421 		}
   422 	}
   423 
   424 	@Override
   425 	public void removeHeader(String name) throws MessagingException {
   426 		super.removeHeader(name);
   427 
   428 		if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
   429 			messageID = null;
   430 		}
   431 	}
   432 
   433 	public void setMessageID(String messageID) {
   434 		this.messageID = messageID;
   435 	}
   436 
   437 	@Override
   438 	protected void updateMessageID() throws MessagingException {
   439 		if (messageID == null) {
   440 			super.updateMessageID();
   441 		} else {
   442 			setHeader(MESSAGE_ID_HEADER, messageID);
   443 		}
   444 	}
   445 
   446 	/**
   447 	 * Call {@link #saveChanges()} before this method, if you want all headers including such ones like:
   448 	 * 
   449 	 * <pre>MIME-Version: 1.0
   450 	 *Content-Type: multipart/alternative;</pre>
   451 	 * 
   452 	 * @return serialized headers
   453 	 * @throws MessagingException if getAllHeaders() fails
   454 	 */
   455 	public String getHeaders() throws MessagingException {
   456 		StringBuilder sb = new StringBuilder();
   457 		for (Enumeration eh = getAllHeaderLines(); eh.hasMoreElements();) {
   458 			sb.append(eh.nextElement());
   459 			sb.append(CRLF);
   460 		}
   461 		return sb.toString();
   462 	}
   463 
   464 	public byte[] getBody() throws IOException, MessagingException {
   465 		saveChanges();
   466 
   467 		ArrayList<String> skipHeaders = new ArrayList<String>();
   468 		for (Enumeration eh = getAllHeaders(); eh.hasMoreElements();) {
   469 			Header h = (Header) eh.nextElement();
   470 			skipHeaders.add(h.getName());
   471 		}
   472 
   473 		ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
   474 		writeTo(baos, skipHeaders.toArray(new String[skipHeaders.size()]));
   475 		return baos.toByteArray();
   476 	}
   477 
   478 	/**
   479 	 * Transforms message content to valid XHTML and strips html and body tags.
   480 	 * When receiving message from user through NNTP 
   481 	 * this method is used to get text that should be saved into databse.
   482 	 * @return XHTML fragment – content between &lt;body&gt; and &lt;/body&gt; tags.
   483 	 */
   484 	public String getBodyXhtmlFragment() throws StorageBackendException {
   485 		/**
   486 		 * TODO: podporovat i zprávy přímo v HTML a multipart.
   487 		 */
   488 		try {
   489 			Object c = getContent();
   490 			if (isMimeType("text/plain") && c instanceof String) {
   491 				String xhtml = readXhtmlText(
   492 						(String) c,
   493 						getSubject(),
   494 						getParentID(),
   495 						null,
   496 						null,
   497 						null);
   498 				return makeFragmentXHTML(xhtml);
   499 			} else {
   500 				throw new StorageBackendException("Only text/plain messages are supported for now – post it as plain text please.");
   501 			}
   502 		} catch (Exception e) {
   503 			throw new StorageBackendException(e);
   504 		}
   505 	}
   506 	
   507 	public String getBodyPlainText() throws StorageBackendException {
   508 		/**
   509 		 * TODO: netransformovat XHTML 2x
   510 		 */
   511 		return formatedToPlainText(makeSimpleXHTML(getBodyXhtmlFragment()));
   512 	}
   513 }