Ignore commas at the end of links, too
[Sone.git] / src / main / java / net / pterodactylus / sone / text / SoneTextParser.java
1 /*
2  * Sone - SoneTextParser.java - Copyright © 2010–2016 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.text;
19
20 import static java.util.logging.Logger.getLogger;
21
22 import java.io.BufferedReader;
23 import java.io.IOException;
24 import java.io.StringReader;
25 import java.net.MalformedURLException;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30
31 import javax.annotation.Nonnull;
32 import javax.annotation.Nullable;
33
34 import net.pterodactylus.sone.data.Post;
35 import net.pterodactylus.sone.data.Sone;
36 import net.pterodactylus.sone.data.impl.IdOnlySone;
37 import net.pterodactylus.sone.database.PostProvider;
38 import net.pterodactylus.sone.database.SoneProvider;
39 import net.pterodactylus.util.io.Closer;
40
41 import com.google.common.base.Optional;
42
43 import freenet.keys.FreenetURI;
44
45 /**
46  * {@link Parser} implementation that can recognize Freenet URIs.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 public class SoneTextParser implements Parser<SoneTextParserContext> {
51
52         /** The logger. */
53         private static final Logger logger = getLogger(SoneTextParser.class.getName());
54
55         /** Pattern to detect whitespace. */
56         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]");
57
58         /**
59          * Enumeration for all recognized link types.
60          *
61          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
62          */
63         private enum LinkType {
64
65                 KSK("KSK@", true),
66                 CHK("CHK@", true),
67                 SSK("SSK@", true),
68                 USK("USK@", true),
69                 HTTP("http://", false),
70                 HTTPS("https://", false),
71                 SONE("sone://", false),
72                 POST("post://", false);
73
74                 private final String scheme;
75                 private final boolean freenetLink;
76
77                 LinkType(String scheme, boolean freenetLink) {
78                         this.scheme = scheme;
79                         this.freenetLink = freenetLink;
80                 }
81
82                 /**
83                  * Returns the scheme of this link type.
84                  *
85                  * @return The scheme of this link type
86                  */
87                 public String getScheme() {
88                         return scheme;
89                 }
90
91                 public boolean isFreenetLink() {
92                         return freenetLink;
93                 }
94
95         }
96
97         /** The Sone provider. */
98         private final SoneProvider soneProvider;
99
100         /** The post provider. */
101         private final PostProvider postProvider;
102
103         /**
104          * Creates a new freenet link parser.
105          *
106          * @param soneProvider
107          *            The Sone provider
108          * @param postProvider
109          *            The post provider
110          */
111         public SoneTextParser(SoneProvider soneProvider, PostProvider postProvider) {
112                 this.soneProvider = soneProvider;
113                 this.postProvider = postProvider;
114         }
115
116         //
117         // PART METHODS
118         //
119
120         /**
121          * {@inheritDoc}
122          */
123         @Nonnull
124         @Override
125         public Iterable<Part> parse(@Nonnull String source, @Nullable SoneTextParserContext context) {
126                 PartContainer parts = new PartContainer();
127                 BufferedReader bufferedReader = new BufferedReader(new StringReader(source));
128                 try {
129                         String line;
130                         boolean lastLineEmpty = true;
131                         int emptyLines = 0;
132                         while ((line = bufferedReader.readLine()) != null) {
133                                 if (line.trim().length() == 0) {
134                                         if (lastLineEmpty) {
135                                                 continue;
136                                         }
137                                         parts.add(new PlainTextPart("\n"));
138                                         ++emptyLines;
139                                         lastLineEmpty = emptyLines == 2;
140                                         continue;
141                                 }
142                                 emptyLines = 0;
143                                 /*
144                                  * lineComplete tracks whether the block you are parsing is the
145                                  * first block of the line. this is important because sometimes
146                                  * you have to add an additional line break.
147                                  */
148                                 boolean lineComplete = true;
149                                 while (line.length() > 0) {
150                                         Optional<NextLink> nextLink = NextLink.findNextLink(line);
151                                         if (!nextLink.isPresent()) {
152                                                 if (lineComplete && !lastLineEmpty) {
153                                                         parts.add(new PlainTextPart("\n" + line));
154                                                 } else {
155                                                         parts.add(new PlainTextPart(line));
156                                                 }
157                                                 break;
158                                         }
159                                         LinkType linkType = nextLink.get().getLinkType();
160                                         int next = nextLink.get().getPosition();
161
162                                         /* cut off “freenet:” from before keys. */
163                                         if (linkType.isFreenetLink() && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
164                                                 next -= 8;
165                                                 line = line.substring(0, next) + line.substring(next + 8);
166                                         }
167
168                                         /* if there is text before the next item, write it out. */
169                                         if (lineComplete && !lastLineEmpty) {
170                                                 parts.add(new PlainTextPart("\n"));
171                                         }
172                                         if (next > 0) {
173                                                 parts.add(new PlainTextPart(line.substring(0, next)));
174                                                 line = line.substring(next);
175                                         }
176                                         lineComplete = false;
177
178                                         int endOfLink = findEndOfLink(line);
179                                         String link = line.substring(0, endOfLink);
180                                         String name = link;
181                                         logger.log(Level.FINER, String.format("Found link: %s", link));
182
183                                         /* if there is no text after the scheme, it’s not a link! */
184                                         if (link.equals(linkType.getScheme())) {
185                                                 parts.add(new PlainTextPart(linkType.getScheme()));
186                                                 line = line.substring(linkType.getScheme().length());
187                                                 continue;
188                                         }
189
190                                         if (linkType == LinkType.SONE) {
191                                                 if (line.length() >= (7 + 43)) {
192                                                         String soneId = line.substring(7, 50);
193                                                         Optional<Sone> sone = soneProvider.getSone(soneId);
194                                                         if (!sone.isPresent()) {
195                                                                 /*
196                                                                  * don’t use create=true above, we don’t want
197                                                                  * the empty shell.
198                                                                  */
199                                                                 sone = Optional.<Sone>of(new IdOnlySone(soneId));
200                                                         }
201                                                         parts.add(new SonePart(sone.get()));
202                                                         line = line.substring(50);
203                                                 } else {
204                                                         parts.add(new PlainTextPart(line));
205                                                         line = "";
206                                                 }
207                                                 continue;
208                                         }
209                                         if (linkType == LinkType.POST) {
210                                                 if (line.length() >= (7 + 36)) {
211                                                         String postId = line.substring(7, 43);
212                                                         Optional<Post> post = postProvider.getPost(postId);
213                                                         if (post.isPresent()) {
214                                                                 parts.add(new PostPart(post.get()));
215                                                         } else {
216                                                                 parts.add(new PlainTextPart(line.substring(0, 43)));
217                                                         }
218                                                         line = line.substring(43);
219                                                 } else {
220                                                         parts.add(new PlainTextPart(line));
221                                                         line = "";
222                                                 }
223                                                 continue;
224                                         }
225
226                                         if (linkType.isFreenetLink()) {
227                                                 FreenetURI uri;
228                                                 if (name.indexOf('?') > -1) {
229                                                         name = name.substring(0, name.indexOf('?'));
230                                                 }
231                                                 if (name.endsWith("/")) {
232                                                         name = name.substring(0, name.length() - 1);
233                                                 }
234                                                 try {
235                                                         uri = new FreenetURI(name);
236                                                         name = uri.lastMetaString();
237                                                         if (name == null) {
238                                                                 name = uri.getDocName();
239                                                         }
240                                                         if (name == null) {
241                                                                 name = link.substring(0, Math.min(9, link.length()));
242                                                         }
243                                                         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());
244                                                         parts.add(new FreenetLinkPart(link, name, fromPostingSone));
245                                                 } catch (MalformedURLException mue1) {
246                                                         /* not a valid link, insert as plain text. */
247                                                         parts.add(new PlainTextPart(link));
248                                                 } catch (NullPointerException npe1) {
249                                                         /* FreenetURI sometimes throws these, too. */
250                                                         parts.add(new PlainTextPart(link));
251                                                 } catch (ArrayIndexOutOfBoundsException aioobe1) {
252                                                         /* oh, and these, too. */
253                                                         parts.add(new PlainTextPart(link));
254                                                 }
255                                         } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
256                                                 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
257                                                 int firstSlash = name.indexOf('/');
258                                                 int lastSlash = name.lastIndexOf('/');
259                                                 if ((lastSlash - firstSlash) > 3) {
260                                                         name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
261                                                 }
262                                                 if (name.endsWith("/")) {
263                                                         name = name.substring(0, name.length() - 1);
264                                                 }
265                                                 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
266                                                         name = name.substring(4);
267                                                 }
268                                                 if (name.indexOf('?') > -1) {
269                                                         name = name.substring(0, name.indexOf('?'));
270                                                 }
271                                                 parts.add(new LinkPart(link, name));
272                                         }
273                                         line = line.substring(endOfLink);
274                                 }
275                                 lastLineEmpty = false;
276                         }
277                 } catch (IOException ioe1) {
278                         // a buffered reader around a string reader should never throw.
279                         throw new RuntimeException(ioe1);
280                 } finally {
281                         Closer.close(bufferedReader);
282                 }
283                 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
284                         Part part = parts.getPart(partIndex);
285                         if (!(part instanceof PlainTextPart) || !"\n".equals(part.getText())) {
286                                 break;
287                         }
288                         parts.removePart(partIndex);
289                 }
290                 return parts;
291         }
292
293         private int findEndOfLink(String line) {
294                 Matcher matcher = whitespacePattern.matcher(line);
295                 if (!matcher.find(0)) {
296                         return line.length();
297                 }
298                 int nextWhitespace = matcher.start();
299                 int lastPunctuation = nextWhitespace;
300                 while (isPunctuation(line.charAt(lastPunctuation - 1))) {
301                         lastPunctuation -= 1;
302                 }
303                 if (lastPunctuation < nextWhitespace) {
304                         return lastPunctuation;
305                 }
306                 int openParens = 0;
307                 for (int i = 0; i < nextWhitespace; i++) {
308                         switch (line.charAt(i)) {
309                                 case '(':
310                                         openParens++;
311                                         break;
312                                 case ')':
313                                         openParens--;
314                                         if (openParens < 0) {
315                                                 return i;
316                                         }
317                                 default:
318                         }
319                 }
320                 return nextWhitespace;
321         }
322
323         private boolean isPunctuation(char character) {
324                 return (character == '.') || (character == ',');
325         }
326
327         private static class NextLink {
328
329                 private final int position;
330                 private final LinkType linkType;
331
332                 private NextLink(int position, LinkType linkType) {
333                         this.position = position;
334                         this.linkType = linkType;
335                 }
336
337                 public int getPosition() {
338                         return position;
339                 }
340
341                 public LinkType getLinkType() {
342                         return linkType;
343                 }
344
345                 public static Optional<NextLink> findNextLink(String line) {
346                         int earliestLinkPosition = Integer.MAX_VALUE;
347                         LinkType linkType = null;
348                         for (LinkType possibleLinkType : LinkType.values()) {
349                                 int nextLinkPosition = line.indexOf(possibleLinkType.getScheme());
350                                 if (nextLinkPosition > -1) {
351                                         if (nextLinkPosition < earliestLinkPosition) {
352                                                 earliestLinkPosition = nextLinkPosition;
353                                                 linkType = possibleLinkType;
354                                         }
355                                 }
356                         }
357                         return earliestLinkPosition < Integer.MAX_VALUE ?
358                                         Optional.of(new NextLink(earliestLinkPosition, linkType)) : Optional.<NextLink>absent();
359                 }
360
361         }
362
363 }