Remove request from parser context
[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                                         logger.log(Level.FINER, String.format("Found link: %s", link));
181
182                                         /* if there is no text after the scheme, it’s not a link! */
183                                         if (link.equals(linkType.getScheme())) {
184                                                 parts.add(new PlainTextPart(linkType.getScheme()));
185                                                 line = line.substring(linkType.getScheme().length());
186                                                 continue;
187                                         }
188
189                                         switch (linkType) {
190                                                 case SONE:
191                                                         renderSoneLink(parts, link);
192                                                         break;
193                                                 case POST:
194                                                         renderPostLink(parts, link);
195                                                         break;
196                                                 case KSK:
197                                                 case CHK:
198                                                 case SSK:
199                                                 case USK:
200                                                         renderFreenetLink(parts, link, linkType, context);
201                                                         break;
202                                                 case HTTP:
203                                                 case HTTPS:
204                                                         renderHttpLink(parts, link, linkType);
205                                                         break;
206                                         }
207
208                                         line = line.substring(endOfLink);
209                                 }
210                                 lastLineEmpty = false;
211                         }
212                 } catch (IOException ioe1) {
213                         // a buffered reader around a string reader should never throw.
214                         throw new RuntimeException(ioe1);
215                 } finally {
216                         Closer.close(bufferedReader);
217                 }
218                 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
219                         Part part = parts.getPart(partIndex);
220                         if (!(part instanceof PlainTextPart) || !"\n".equals(part.getText())) {
221                                 break;
222                         }
223                         parts.removePart(partIndex);
224                 }
225                 return parts;
226         }
227
228         private void renderSoneLink(PartContainer parts, String line) {
229                 if (line.length() >= (7 + 43)) {
230                         String soneId = line.substring(7, 50);
231                         Optional<Sone> sone = soneProvider.getSone(soneId);
232                         parts.add(new SonePart(sone.or(new IdOnlySone(soneId))));
233                 } else {
234                         parts.add(new PlainTextPart(line));
235                 }
236         }
237
238         private void renderPostLink(PartContainer parts, String line) {
239                 if (line.length() >= (7 + 36)) {
240                         String postId = line.substring(7, 43);
241                         Optional<Post> post = postProvider.getPost(postId);
242                         if (post.isPresent()) {
243                                 parts.add(new PostPart(post.get()));
244                         } else {
245                                 parts.add(new PlainTextPart(line.substring(0, 43)));
246                         }
247                 } else {
248                         parts.add(new PlainTextPart(line));
249                 }
250         }
251
252         private void renderFreenetLink(PartContainer parts, String link, LinkType linkType, @Nullable SoneTextParserContext context) {
253                 String name = link;
254                 if (name.indexOf('?') > -1) {
255                         name = name.substring(0, name.indexOf('?'));
256                 }
257                 if (name.endsWith("/")) {
258                         name = name.substring(0, name.length() - 1);
259                 }
260                 try {
261                         FreenetURI uri = new FreenetURI(name);
262                         name = uri.lastMetaString();
263                         if (name == null) {
264                                 name = uri.getDocName();
265                         }
266                         if (name == null) {
267                                 name = link.substring(0, Math.min(9, link.length()));
268                         }
269                         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());
270                         parts.add(new FreenetLinkPart(link, name, fromPostingSone));
271                 } catch (MalformedURLException mue1) {
272                         /* not a valid link, insert as plain text. */
273                         parts.add(new PlainTextPart(link));
274                 } catch (NullPointerException npe1) {
275                         /* FreenetURI sometimes throws these, too. */
276                         parts.add(new PlainTextPart(link));
277                 } catch (ArrayIndexOutOfBoundsException aioobe1) {
278                         /* oh, and these, too. */
279                         parts.add(new PlainTextPart(link));
280                 }
281         }
282
283         private void renderHttpLink(PartContainer parts, String link, LinkType linkType) {
284                 String name;
285                 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
286                 int firstSlash = name.indexOf('/');
287                 int lastSlash = name.lastIndexOf('/');
288                 if ((lastSlash - firstSlash) > 3) {
289                         name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
290                 }
291                 if (name.endsWith("/")) {
292                         name = name.substring(0, name.length() - 1);
293                 }
294                 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
295                         name = name.substring(4);
296                 }
297                 if (name.indexOf('?') > -1) {
298                         name = name.substring(0, name.indexOf('?'));
299                 }
300                 parts.add(new LinkPart(link, name));
301         }
302
303         private int findEndOfLink(String line) {
304                 Matcher matcher = whitespacePattern.matcher(line);
305                 if (!matcher.find(0)) {
306                         return line.length();
307                 }
308                 int nextWhitespace = matcher.start();
309                 int lastPunctuation = nextWhitespace;
310                 while (isPunctuation(line.charAt(lastPunctuation - 1))) {
311                         lastPunctuation -= 1;
312                 }
313                 if (lastPunctuation < nextWhitespace) {
314                         return lastPunctuation;
315                 }
316                 int openParens = 0;
317                 for (int i = 0; i < nextWhitespace; i++) {
318                         switch (line.charAt(i)) {
319                                 case '(':
320                                         openParens++;
321                                         break;
322                                 case ')':
323                                         openParens--;
324                                         if (openParens < 0) {
325                                                 return i;
326                                         }
327                                 default:
328                         }
329                 }
330                 return nextWhitespace;
331         }
332
333         private boolean isPunctuation(char character) {
334                 return (character == '.') || (character == ',');
335         }
336
337         private static class NextLink {
338
339                 private final int position;
340                 private final LinkType linkType;
341
342                 private NextLink(int position, LinkType linkType) {
343                         this.position = position;
344                         this.linkType = linkType;
345                 }
346
347                 public int getPosition() {
348                         return position;
349                 }
350
351                 public LinkType getLinkType() {
352                         return linkType;
353                 }
354
355                 public static Optional<NextLink> findNextLink(String line) {
356                         int earliestLinkPosition = Integer.MAX_VALUE;
357                         LinkType linkType = null;
358                         for (LinkType possibleLinkType : LinkType.values()) {
359                                 int nextLinkPosition = line.indexOf(possibleLinkType.getScheme());
360                                 if (nextLinkPosition > -1) {
361                                         if (nextLinkPosition < earliestLinkPosition) {
362                                                 earliestLinkPosition = nextLinkPosition;
363                                                 linkType = possibleLinkType;
364                                         }
365                                 }
366                         }
367                         return earliestLinkPosition < Integer.MAX_VALUE ?
368                                         Optional.of(new NextLink(earliestLinkPosition, linkType)) : Optional.<NextLink>absent();
369                 }
370
371         }
372
373 }