2 * Sone - SoneTextParser.java - Copyright © 2010–2016 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program 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 General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.text;
20 import static com.google.common.base.Optional.absent;
21 import static com.google.common.base.Optional.of;
22 import static java.util.logging.Logger.getLogger;
24 import java.io.BufferedReader;
25 import java.io.IOException;
26 import java.io.Reader;
27 import java.io.StringReader;
28 import java.net.MalformedURLException;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
34 import javax.annotation.Nonnull;
35 import javax.annotation.Nullable;
37 import net.pterodactylus.sone.data.Post;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.sone.data.impl.IdOnlySone;
40 import net.pterodactylus.sone.database.PostProvider;
41 import net.pterodactylus.sone.database.SoneProvider;
43 import com.google.common.base.Optional;
44 import org.bitpedia.util.Base32;
46 import freenet.keys.FreenetURI;
47 import freenet.support.Base64;
50 * {@link Parser} implementation that can recognize Freenet URIs.
52 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
54 public class SoneTextParser implements Parser<SoneTextParserContext> {
57 private static final Logger logger = getLogger(SoneTextParser.class.getName());
59 /** Pattern to detect whitespace. */
60 private static final Pattern whitespacePattern = Pattern.compile("[\\u000a\u0020\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u200c\u200d\u202f\u205f\u2060\u2800\u3000]");
62 private static class NextLink {
64 private final int position;
65 private final String link;
66 private final String remainder;
67 private final LinkType linkType;
69 private NextLink(int position, String link, String remainder, LinkType linkType) {
70 this.position = position;
72 this.remainder = remainder;
73 this.linkType = linkType;
76 public int getPosition() {
80 public String getLink() {
84 public String getRemainder() {
88 public LinkType getLinkType() {
95 * Enumeration for all recognized link types.
97 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
99 private enum LinkType {
105 HTTP("http://", false),
106 HTTPS("https://", false),
107 SONE("sone://", false),
108 POST("post://", false),
112 public Optional<NextLink> findNext(String line) {
113 int nextFreemailSuffix = line.indexOf(".freemail");
114 if (nextFreemailSuffix < 54) {
115 /* 52 chars for the id, 1 on @, at least 1 for the local part. */
118 if (line.charAt(nextFreemailSuffix - 53) != '@') {
121 if (!line.substring(nextFreemailSuffix - 52, nextFreemailSuffix).matches("^[a-z2-7]*$")) {
124 int startOfLocalPart = nextFreemailSuffix - 54;
125 if (!isAllowedInLocalPart(line.charAt(startOfLocalPart))) {
128 while ((startOfLocalPart > 0) && isAllowedInLocalPart(line.charAt(startOfLocalPart - 1))) {
131 return of(new NextLink(startOfLocalPart, line.substring(startOfLocalPart, nextFreemailSuffix + 9), line.substring(nextFreemailSuffix + 9), this));
134 private boolean isAllowedInLocalPart(char character) {
135 return ((character >= 'A') && (character <= 'Z'))
136 || ((character >= 'a') && (character <= 'z'))
137 || ((character >= '0') && (character <= '9'))
138 || (character == '.') || (character == '-') || (character == '_');
142 private final String scheme;
143 private final boolean freenetLink;
145 LinkType(String scheme, boolean freenetLink) {
146 this.scheme = scheme;
147 this.freenetLink = freenetLink;
151 * Returns the scheme of this link type.
153 * @return The scheme of this link type
155 public String getScheme() {
159 public boolean isFreenetLink() {
163 public Optional<NextLink> findNext(String line) {
164 int nextLinkPosition = line.indexOf(getScheme());
165 if (nextLinkPosition == -1) {
168 int endOfLink = findEndOfLink(line.substring(nextLinkPosition));
169 return of(new NextLink(nextLinkPosition, line.substring(nextLinkPosition, nextLinkPosition + endOfLink), line.substring(nextLinkPosition + endOfLink), this));
172 private static int findEndOfLink(String line) {
173 Matcher matcher = whitespacePattern.matcher(line);
174 int endOfLink = matcher.find() ? matcher.start() : line.length();
175 while (isPunctuation(line.charAt(endOfLink - 1))) {
179 for (int i = 0; i < endOfLink; i++) {
180 switch (line.charAt(i)) {
186 if (openParens < 0) {
197 /** The Sone provider. */
198 private final SoneProvider soneProvider;
200 /** The post provider. */
201 private final PostProvider postProvider;
204 * Creates a new freenet link parser.
206 * @param soneProvider
208 * @param postProvider
211 public SoneTextParser(SoneProvider soneProvider, PostProvider postProvider) {
212 this.soneProvider = soneProvider;
213 this.postProvider = postProvider;
225 public Iterable<Part> parse(@Nonnull String source, @Nullable SoneTextParserContext context) {
226 PartContainer parts = new PartContainer();
227 try (Reader sourceReader = new StringReader(source);
228 BufferedReader bufferedReader = new BufferedReader(sourceReader)) {
230 boolean lastLineEmpty = true;
232 while ((line = bufferedReader.readLine()) != null) {
233 if (line.trim().length() == 0) {
237 parts.add(new PlainTextPart("\n"));
239 lastLineEmpty = emptyLines == 2;
244 * lineComplete tracks whether the block you are parsing is the
245 * first block of the line. this is important because sometimes
246 * you have to add an additional line break.
248 boolean lineComplete = true;
249 while (line.length() > 0) {
250 Optional<NextLink> nextLink = findNextLink(line);
251 if (!nextLink.isPresent()) {
252 if (lineComplete && !lastLineEmpty) {
253 parts.add(new PlainTextPart("\n" + line));
255 parts.add(new PlainTextPart(line));
259 LinkType linkType = nextLink.get().getLinkType();
260 int next = nextLink.get().getPosition();
262 /* cut off “freenet:” from before keys. */
263 if (linkType.isFreenetLink() && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
265 line = line.substring(0, next) + line.substring(next + 8);
268 /* if there is text before the next item, write it out. */
269 if (lineComplete && !lastLineEmpty) {
270 parts.add(new PlainTextPart("\n"));
273 parts.add(new PlainTextPart(line.substring(0, next)));
274 line = line.substring(next);
276 lineComplete = false;
278 String link = nextLink.get().getLink();
279 logger.log(Level.FINER, String.format("Found link: %s", link));
281 /* if there is no text after the scheme, it’s not a link! */
282 if (link.equals(linkType.getScheme())) {
283 parts.add(new PlainTextPart(linkType.getScheme()));
284 line = line.substring(linkType.getScheme().length());
290 renderSoneLink(parts, link);
293 renderPostLink(parts, link);
299 renderFreenetLink(parts, link, linkType, context);
303 renderHttpLink(parts, link, linkType);
306 renderFreemailLink(parts, link);
309 line = nextLink.get().getRemainder();
311 lastLineEmpty = false;
313 } catch (IOException ioe1) {
314 // a buffered reader around a string reader should never throw.
315 throw new RuntimeException(ioe1);
317 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
318 Part part = parts.getPart(partIndex);
319 if (!(part instanceof PlainTextPart) || !"\n".equals(part.getText())) {
322 parts.removePart(partIndex);
327 public static Optional<NextLink> findNextLink(String line) {
328 int earliestLinkPosition = Integer.MAX_VALUE;
329 NextLink earliestNextLink = null;
330 for (LinkType possibleLinkType : LinkType.values()) {
331 Optional<NextLink> nextLink = possibleLinkType.findNext(line);
332 if (nextLink.isPresent()) {
333 if (nextLink.get().getPosition() < earliestLinkPosition) {
334 earliestNextLink = nextLink.get();
338 return Optional.fromNullable(earliestNextLink);
341 private void renderSoneLink(PartContainer parts, String line) {
342 if (line.length() >= (7 + 43)) {
343 String soneId = line.substring(7, 50);
344 Optional<Sone> sone = soneProvider.getSone(soneId);
345 parts.add(new SonePart(sone.or(new IdOnlySone(soneId))));
347 parts.add(new PlainTextPart(line));
351 private void renderPostLink(PartContainer parts, String line) {
352 if (line.length() >= (7 + 36)) {
353 String postId = line.substring(7, 43);
354 Optional<Post> post = postProvider.getPost(postId);
355 if (post.isPresent()) {
356 parts.add(new PostPart(post.get()));
358 parts.add(new PlainTextPart(line.substring(0, 43)));
361 parts.add(new PlainTextPart(line));
365 private void renderFreenetLink(PartContainer parts, String link, LinkType linkType, @Nullable SoneTextParserContext context) {
367 String linkWithoutParameters = link;
368 if (name.indexOf('?') > -1) {
369 linkWithoutParameters = name = name.substring(0, name.indexOf('?'));
371 if (name.endsWith("/")) {
372 name = name.substring(0, name.length() - 1);
375 FreenetURI uri = new FreenetURI(name);
376 name = uri.lastMetaString();
378 name = uri.getDocName();
381 name = link.substring(0, Math.min(9, link.length()));
383 boolean fromPostingSone = ((linkType == LinkType.SSK) || (linkType == LinkType.USK)) && (context != null) && (context.getPostingSone() != null) && link.substring(4, Math.min(link.length(), 47)).equals(context.getPostingSone().getId());
384 parts.add(new FreenetLinkPart(link, name, linkWithoutParameters, fromPostingSone));
385 } catch (MalformedURLException mue1) {
386 /* not a valid link, insert as plain text. */
387 parts.add(new PlainTextPart(link));
388 } catch (NullPointerException npe1) {
389 /* FreenetURI sometimes throws these, too. */
390 parts.add(new PlainTextPart(link));
391 } catch (ArrayIndexOutOfBoundsException aioobe1) {
392 /* oh, and these, too. */
393 parts.add(new PlainTextPart(link));
397 private void renderHttpLink(PartContainer parts, String link, LinkType linkType) {
398 String name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
399 int firstSlash = name.indexOf('/');
400 int lastSlash = name.lastIndexOf('/');
401 if ((lastSlash - firstSlash) > 3) {
402 name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
404 if (name.endsWith("/")) {
405 name = name.substring(0, name.length() - 1);
407 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
408 name = name.substring(4);
410 if (name.indexOf('?') > -1) {
411 name = name.substring(0, name.indexOf('?'));
413 parts.add(new LinkPart(link, name));
416 private void renderFreemailLink(PartContainer parts, String line) {
417 int separator = line.indexOf('@');
418 String freemailId = line.substring(separator + 1, separator + 53);
419 String identityId = Base64.encode(Base32.decode(freemailId));
420 String emailLocalPart = line.substring(0, separator);
421 parts.add(new FreemailPart(emailLocalPart, freemailId, identityId));
424 private static boolean isPunctuation(char character) {
425 return (character == '.') || (character == ',') || (character == '!') || (character == '?');