Merge branch 'release-0.9.6'
[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.Reader;
25 import java.io.StringReader;
26 import java.net.MalformedURLException;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
31
32 import javax.annotation.Nonnull;
33 import javax.annotation.Nullable;
34
35 import net.pterodactylus.sone.data.Post;
36 import net.pterodactylus.sone.data.Sone;
37 import net.pterodactylus.sone.data.impl.IdOnlySone;
38 import net.pterodactylus.sone.database.PostProvider;
39 import net.pterodactylus.sone.database.SoneProvider;
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                 try (Reader sourceReader = new StringReader(source);
128                                 BufferedReader bufferedReader = new BufferedReader(sourceReader)) {
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                 }
216                 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
217                         Part part = parts.getPart(partIndex);
218                         if (!(part instanceof PlainTextPart) || !"\n".equals(part.getText())) {
219                                 break;
220                         }
221                         parts.removePart(partIndex);
222                 }
223                 return parts;
224         }
225
226         private void renderSoneLink(PartContainer parts, String line) {
227                 if (line.length() >= (7 + 43)) {
228                         String soneId = line.substring(7, 50);
229                         Optional<Sone> sone = soneProvider.getSone(soneId);
230                         parts.add(new SonePart(sone.or(new IdOnlySone(soneId))));
231                 } else {
232                         parts.add(new PlainTextPart(line));
233                 }
234         }
235
236         private void renderPostLink(PartContainer parts, String line) {
237                 if (line.length() >= (7 + 36)) {
238                         String postId = line.substring(7, 43);
239                         Optional<Post> post = postProvider.getPost(postId);
240                         if (post.isPresent()) {
241                                 parts.add(new PostPart(post.get()));
242                         } else {
243                                 parts.add(new PlainTextPart(line.substring(0, 43)));
244                         }
245                 } else {
246                         parts.add(new PlainTextPart(line));
247                 }
248         }
249
250         private void renderFreenetLink(PartContainer parts, String link, LinkType linkType, @Nullable SoneTextParserContext context) {
251                 String name = link;
252                 if (name.indexOf('?') > -1) {
253                         name = name.substring(0, name.indexOf('?'));
254                 }
255                 if (name.endsWith("/")) {
256                         name = name.substring(0, name.length() - 1);
257                 }
258                 try {
259                         FreenetURI uri = new FreenetURI(name);
260                         name = uri.lastMetaString();
261                         if (name == null) {
262                                 name = uri.getDocName();
263                         }
264                         if (name == null) {
265                                 name = link.substring(0, Math.min(9, link.length()));
266                         }
267                         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());
268                         parts.add(new FreenetLinkPart(link, name, fromPostingSone));
269                 } catch (MalformedURLException mue1) {
270                         /* not a valid link, insert as plain text. */
271                         parts.add(new PlainTextPart(link));
272                 } catch (NullPointerException npe1) {
273                         /* FreenetURI sometimes throws these, too. */
274                         parts.add(new PlainTextPart(link));
275                 } catch (ArrayIndexOutOfBoundsException aioobe1) {
276                         /* oh, and these, too. */
277                         parts.add(new PlainTextPart(link));
278                 }
279         }
280
281         private void renderHttpLink(PartContainer parts, String link, LinkType linkType) {
282                 String name;
283                 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
284                 int firstSlash = name.indexOf('/');
285                 int lastSlash = name.lastIndexOf('/');
286                 if ((lastSlash - firstSlash) > 3) {
287                         name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
288                 }
289                 if (name.endsWith("/")) {
290                         name = name.substring(0, name.length() - 1);
291                 }
292                 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
293                         name = name.substring(4);
294                 }
295                 if (name.indexOf('?') > -1) {
296                         name = name.substring(0, name.indexOf('?'));
297                 }
298                 parts.add(new LinkPart(link, name));
299         }
300
301         private int findEndOfLink(String line) {
302                 Matcher matcher = whitespacePattern.matcher(line);
303                 int endOfLink = matcher.find() ? matcher.start() : line.length();
304                 while ((endOfLink > 0) && isPunctuation(line.charAt(endOfLink - 1))) {
305                         endOfLink--;
306                 }
307                 int openParens = 0;
308                 for (int i = 0; i < endOfLink; i++) {
309                         switch (line.charAt(i)) {
310                                 case '(':
311                                         openParens++;
312                                         break;
313                                 case ')':
314                                         openParens--;
315                                         if (openParens < 0) {
316                                                 return i;
317                                         }
318                                 default:
319                         }
320                 }
321                 return endOfLink;
322         }
323
324         private static boolean isPunctuation(char character) {
325                 return (character == '.') || (character == ',');
326         }
327
328         private static class NextLink {
329
330                 private final int position;
331                 private final LinkType linkType;
332
333                 private NextLink(int position, LinkType linkType) {
334                         this.position = position;
335                         this.linkType = linkType;
336                 }
337
338                 public int getPosition() {
339                         return position;
340                 }
341
342                 public LinkType getLinkType() {
343                         return linkType;
344                 }
345
346                 public static Optional<NextLink> findNextLink(String line) {
347                         int earliestLinkPosition = Integer.MAX_VALUE;
348                         LinkType linkType = null;
349                         for (LinkType possibleLinkType : LinkType.values()) {
350                                 int nextLinkPosition = line.indexOf(possibleLinkType.getScheme());
351                                 if (nextLinkPosition > -1) {
352                                         if (nextLinkPosition < earliestLinkPosition) {
353                                                 earliestLinkPosition = nextLinkPosition;
354                                                 linkType = possibleLinkType;
355                                         }
356                                 }
357                         }
358                         return earliestLinkPosition < Integer.MAX_VALUE ?
359                                         Optional.of(new NextLink(earliestLinkPosition, linkType)) : Optional.<NextLink>absent();
360                 }
361
362         }
363
364 }