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.ArrayList;
30 import java.util.List;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
36 import javax.annotation.Nonnull;
37 import javax.annotation.Nullable;
39 import net.pterodactylus.sone.data.Post;
40 import net.pterodactylus.sone.data.Sone;
41 import net.pterodactylus.sone.data.impl.IdOnlySone;
42 import net.pterodactylus.sone.database.PostProvider;
43 import net.pterodactylus.sone.database.SoneProvider;
45 import com.google.common.base.Optional;
46 import org.bitpedia.util.Base32;
48 import freenet.keys.FreenetURI;
49 import freenet.support.Base64;
52 * {@link Parser} implementation that can recognize Freenet URIs.
54 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
56 public class SoneTextParser implements Parser<SoneTextParserContext> {
59 private static final Logger logger = getLogger(SoneTextParser.class.getName());
61 /** Pattern to detect whitespace. */
62 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]");
64 private static class NextLink {
66 private final int position;
67 private final String link;
68 private final String remainder;
69 private final LinkType linkType;
71 private NextLink(int position, String link, String remainder, LinkType linkType) {
72 this.position = position;
74 this.remainder = remainder;
75 this.linkType = linkType;
78 public int getPosition() {
82 public String getLink() {
86 public String getRemainder() {
90 public LinkType getLinkType() {
97 * Enumeration for all recognized link types.
99 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
101 private enum LinkType {
107 HTTP("http://", false),
108 HTTPS("https://", false),
109 SONE("sone://", false),
110 POST("post://", false),
114 public Optional<NextLink> findNext(String line) {
115 int nextFreemailSuffix = line.indexOf(".freemail");
116 if (nextFreemailSuffix < 54) {
117 /* 52 chars for the id, 1 on @, at least 1 for the local part. */
120 if (line.charAt(nextFreemailSuffix - 53) != '@') {
123 if (!line.substring(nextFreemailSuffix - 52, nextFreemailSuffix).matches("^[a-z2-7]*$")) {
126 int startOfLocalPart = nextFreemailSuffix - 54;
127 if (!isAllowedInLocalPart(line.charAt(startOfLocalPart))) {
130 while ((startOfLocalPart > 0) && isAllowedInLocalPart(line.charAt(startOfLocalPart - 1))) {
133 return of(new NextLink(startOfLocalPart, line.substring(startOfLocalPart, nextFreemailSuffix + 9), line.substring(nextFreemailSuffix + 9), this));
136 private boolean isAllowedInLocalPart(char character) {
137 return ((character >= 'A') && (character <= 'Z'))
138 || ((character >= 'a') && (character <= 'z'))
139 || ((character >= '0') && (character <= '9'))
140 || (character == '.') || (character == '-') || (character == '_');
144 private final String scheme;
145 private final boolean freenetLink;
147 LinkType(String scheme, boolean freenetLink) {
148 this.scheme = scheme;
149 this.freenetLink = freenetLink;
153 * Returns the scheme of this link type.
155 * @return The scheme of this link type
157 public String getScheme() {
161 public boolean isFreenetLink() {
165 public Optional<NextLink> findNext(String line) {
166 int nextLinkPosition = line.indexOf(getScheme());
167 if (nextLinkPosition == -1) {
170 int endOfLink = findEndOfLink(line.substring(nextLinkPosition));
171 return of(new NextLink(nextLinkPosition, line.substring(nextLinkPosition, nextLinkPosition + endOfLink), line.substring(nextLinkPosition + endOfLink), this));
174 private static int findEndOfLink(String line) {
175 Matcher matcher = whitespacePattern.matcher(line);
176 int endOfLink = matcher.find() ? matcher.start() : line.length();
177 while (isPunctuation(line.charAt(endOfLink - 1))) {
181 for (int i = 0; i < endOfLink; i++) {
182 switch (line.charAt(i)) {
188 if (openParens < 0) {
199 /** The Sone provider. */
200 private final SoneProvider soneProvider;
202 /** The post provider. */
203 private final PostProvider postProvider;
206 * Creates a new freenet link parser.
208 * @param soneProvider
210 * @param postProvider
213 public SoneTextParser(SoneProvider soneProvider, PostProvider postProvider) {
214 this.soneProvider = soneProvider;
215 this.postProvider = postProvider;
227 public Iterable<Part> parse(@Nonnull String source, @Nullable SoneTextParserContext context) {
228 List<Part> parts = new ArrayList<>();
229 try (Reader sourceReader = new StringReader(source);
230 BufferedReader bufferedReader = new BufferedReader(sourceReader)) {
232 boolean lastLineEmpty = true;
234 while ((line = bufferedReader.readLine()) != null) {
235 if (line.trim().length() == 0) {
239 parts.add(new PlainTextPart("\n"));
241 lastLineEmpty = emptyLines == 2;
246 * lineComplete tracks whether the block you are parsing is the
247 * first block of the line. this is important because sometimes
248 * you have to add an additional line break.
250 boolean lineComplete = true;
251 while (line.length() > 0) {
252 Optional<NextLink> nextLink = findNextLink(line);
253 if (!nextLink.isPresent()) {
254 if (lineComplete && !lastLineEmpty) {
255 parts.add(new PlainTextPart("\n" + line));
257 parts.add(new PlainTextPart(line));
261 LinkType linkType = nextLink.get().getLinkType();
262 int next = nextLink.get().getPosition();
264 /* cut off “freenet:” from before keys. */
265 if (linkType.isFreenetLink() && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
267 line = line.substring(0, next) + line.substring(next + 8);
270 /* if there is text before the next item, write it out. */
271 if (lineComplete && !lastLineEmpty) {
272 parts.add(new PlainTextPart("\n"));
275 parts.add(new PlainTextPart(line.substring(0, next)));
276 line = line.substring(next);
278 lineComplete = false;
280 String link = nextLink.get().getLink();
281 logger.log(Level.FINER, String.format("Found link: %s", link));
283 /* if there is no text after the scheme, it’s not a link! */
284 if (link.equals(linkType.getScheme())) {
285 parts.add(new PlainTextPart(linkType.getScheme()));
286 line = line.substring(linkType.getScheme().length());
292 renderSoneLink(parts, link);
295 renderPostLink(parts, link);
301 renderFreenetLink(parts, link, linkType, context);
305 renderHttpLink(parts, link, linkType);
308 renderFreemailLink(parts, link);
311 line = nextLink.get().getRemainder();
313 lastLineEmpty = false;
315 } catch (IOException ioe1) {
316 // a buffered reader around a string reader should never throw.
317 throw new RuntimeException(ioe1);
319 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
320 Part part = parts.get(partIndex);
321 if (!(part instanceof PlainTextPart) || !"\n".equals(part.getText())) {
324 parts.remove(partIndex);
329 public static Optional<NextLink> findNextLink(String line) {
330 int earliestLinkPosition = Integer.MAX_VALUE;
331 NextLink earliestNextLink = null;
332 for (LinkType possibleLinkType : LinkType.values()) {
333 Optional<NextLink> nextLink = possibleLinkType.findNext(line);
334 if (nextLink.isPresent()) {
335 if (nextLink.get().getPosition() < earliestLinkPosition) {
336 earliestNextLink = nextLink.get();
340 return Optional.fromNullable(earliestNextLink);
343 private void renderSoneLink(List<Part> parts, String line) {
344 if (line.length() >= (7 + 43)) {
345 String soneId = line.substring(7, 50);
346 Optional<Sone> sone = soneProvider.getSone(soneId);
347 parts.add(new SonePart(sone.or(new IdOnlySone(soneId))));
349 parts.add(new PlainTextPart(line));
353 private void renderPostLink(List<Part> parts, String line) {
354 if (line.length() >= (7 + 36)) {
355 String postId = line.substring(7, 43);
356 Optional<Post> post = postProvider.getPost(postId);
357 if (post.isPresent()) {
358 parts.add(new PostPart(post.get()));
360 parts.add(new PlainTextPart(line.substring(0, 43)));
363 parts.add(new PlainTextPart(line));
367 private void renderFreenetLink(List<Part> parts, String link, LinkType linkType, @Nullable SoneTextParserContext context) {
369 String linkWithoutParameters = link;
370 if (name.indexOf('?') > -1) {
371 linkWithoutParameters = name = name.substring(0, name.indexOf('?'));
373 if (name.endsWith("/")) {
374 name = name.substring(0, name.length() - 1);
377 FreenetURI uri = new FreenetURI(name);
378 name = uri.lastMetaString();
380 name = uri.getDocName();
383 name = link.substring(0, Math.min(9, link.length()));
385 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());
386 parts.add(new FreenetLinkPart(link, name, linkWithoutParameters, fromPostingSone));
387 } catch (MalformedURLException mue1) {
388 /* not a valid link, insert as plain text. */
389 parts.add(new PlainTextPart(link));
390 } catch (NullPointerException npe1) {
391 /* FreenetURI sometimes throws these, too. */
392 parts.add(new PlainTextPart(link));
393 } catch (ArrayIndexOutOfBoundsException aioobe1) {
394 /* oh, and these, too. */
395 parts.add(new PlainTextPart(link));
399 private void renderHttpLink(List<Part> parts, String link, LinkType linkType) {
400 String name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
401 int firstSlash = name.indexOf('/');
402 int lastSlash = name.lastIndexOf('/');
403 if ((lastSlash - firstSlash) > 3) {
404 name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
406 if (name.endsWith("/")) {
407 name = name.substring(0, name.length() - 1);
409 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
410 name = name.substring(4);
412 if (name.indexOf('?') > -1) {
413 name = name.substring(0, name.indexOf('?'));
415 parts.add(new LinkPart(link, name));
418 private void renderFreemailLink(List<Part> parts, String line) {
419 int separator = line.indexOf('@');
420 String freemailId = line.substring(separator + 1, separator + 53);
421 String identityId = Base64.encode(Base32.decode(freemailId));
422 String emailLocalPart = line.substring(0, separator);
423 parts.add(new FreemailPart(emailLocalPart, freemailId, identityId));
426 private static boolean isPunctuation(char character) {
427 return (character == '.') || (character == ',') || (character == '!') || (character == '?');