Add test for delete reply command and actually delete the reply
[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 com.google.common.base.Optional.absent;
21 import static com.google.common.base.Optional.of;
22 import static java.util.logging.Logger.getLogger;
23
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;
35
36 import javax.annotation.Nonnull;
37 import javax.annotation.Nullable;
38
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;
44
45 import com.google.common.base.Optional;
46 import org.bitpedia.util.Base32;
47
48 import freenet.keys.FreenetURI;
49 import freenet.support.Base64;
50
51 /**
52  * {@link Parser} implementation that can recognize Freenet URIs.
53  *
54  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
55  */
56 public class SoneTextParser implements Parser<SoneTextParserContext> {
57
58         /** The logger. */
59         private static final Logger logger = getLogger(SoneTextParser.class.getName());
60
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]");
63
64         private static class NextLink {
65
66                 private final int position;
67                 private final String link;
68                 private final String remainder;
69                 private final LinkType linkType;
70
71                 private NextLink(int position, String link, String remainder, LinkType linkType) {
72                         this.position = position;
73                         this.link = link;
74                         this.remainder = remainder;
75                         this.linkType = linkType;
76                 }
77
78                 public int getPosition() {
79                         return position;
80                 }
81
82                 public String getLink() {
83                         return link;
84                 }
85
86                 public String getRemainder() {
87                         return remainder;
88                 }
89
90                 public LinkType getLinkType() {
91                         return linkType;
92                 }
93
94         }
95
96         /**
97          * Enumeration for all recognized link types.
98          *
99          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
100          */
101         private enum LinkType {
102
103                 KSK("KSK@", true),
104                 CHK("CHK@", true),
105                 SSK("SSK@", true),
106                 USK("USK@", true),
107                 HTTP("http://", false),
108                 HTTPS("https://", false),
109                 SONE("sone://", false),
110                 POST("post://", false),
111
112                 FREEMAIL("", true) {
113                         @Override
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. */
118                                         return absent();
119                                 }
120                                 if (line.charAt(nextFreemailSuffix - 53) != '@') {
121                                         return absent();
122                                 }
123                                 if (!line.substring(nextFreemailSuffix - 52, nextFreemailSuffix).matches("^[a-z2-7]*$")) {
124                                         return absent();
125                                 }
126                                 int startOfLocalPart = nextFreemailSuffix - 54;
127                                 if (!isAllowedInLocalPart(line.charAt(startOfLocalPart))) {
128                                         return absent();
129                                 }
130                                 while ((startOfLocalPart > 0) && isAllowedInLocalPart(line.charAt(startOfLocalPart - 1))) {
131                                         startOfLocalPart--;
132                                 }
133                                 return of(new NextLink(startOfLocalPart, line.substring(startOfLocalPart, nextFreemailSuffix + 9), line.substring(nextFreemailSuffix + 9), this));
134                         }
135
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 == '_');
141                         }
142                 };
143
144                 private final String scheme;
145                 private final boolean freenetLink;
146
147                 LinkType(String scheme, boolean freenetLink) {
148                         this.scheme = scheme;
149                         this.freenetLink = freenetLink;
150                 }
151
152                 /**
153                  * Returns the scheme of this link type.
154                  *
155                  * @return The scheme of this link type
156                  */
157                 public String getScheme() {
158                         return scheme;
159                 }
160
161                 public boolean isFreenetLink() {
162                         return freenetLink;
163                 }
164
165                 public Optional<NextLink> findNext(String line) {
166                         int nextLinkPosition = line.indexOf(getScheme());
167                         if (nextLinkPosition == -1) {
168                                 return absent();
169                         }
170                         int endOfLink = findEndOfLink(line.substring(nextLinkPosition));
171                         return of(new NextLink(nextLinkPosition, line.substring(nextLinkPosition, nextLinkPosition + endOfLink), line.substring(nextLinkPosition + endOfLink), this));
172                 }
173
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))) {
178                                 endOfLink--;
179                         }
180                         int openParens = 0;
181                         for (int i = 0; i < endOfLink; i++) {
182                                 switch (line.charAt(i)) {
183                                         case '(':
184                                                 openParens++;
185                                                 break;
186                                         case ')':
187                                                 openParens--;
188                                                 if (openParens < 0) {
189                                                         return i;
190                                                 }
191                                         default:
192                                 }
193                         }
194                         return endOfLink;
195                 }
196
197         }
198
199         /** The Sone provider. */
200         private final SoneProvider soneProvider;
201
202         /** The post provider. */
203         private final PostProvider postProvider;
204
205         /**
206          * Creates a new freenet link parser.
207          *
208          * @param soneProvider
209          *            The Sone provider
210          * @param postProvider
211          *            The post provider
212          */
213         public SoneTextParser(SoneProvider soneProvider, PostProvider postProvider) {
214                 this.soneProvider = soneProvider;
215                 this.postProvider = postProvider;
216         }
217
218         //
219         // PART METHODS
220         //
221
222         /**
223          * {@inheritDoc}
224          */
225         @Nonnull
226         @Override
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)) {
231                         String line;
232                         boolean lastLineEmpty = true;
233                         int emptyLines = 0;
234                         while ((line = bufferedReader.readLine()) != null) {
235                                 if (line.trim().length() == 0) {
236                                         if (lastLineEmpty) {
237                                                 continue;
238                                         }
239                                         parts.add(new PlainTextPart("\n"));
240                                         ++emptyLines;
241                                         lastLineEmpty = emptyLines == 2;
242                                         continue;
243                                 }
244                                 emptyLines = 0;
245                                 /*
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.
249                                  */
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));
256                                                 } else {
257                                                         parts.add(new PlainTextPart(line));
258                                                 }
259                                                 break;
260                                         }
261                                         LinkType linkType = nextLink.get().getLinkType();
262                                         int next = nextLink.get().getPosition();
263
264                                         /* cut off “freenet:” from before keys. */
265                                         if (linkType.isFreenetLink() && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
266                                                 next -= 8;
267                                                 line = line.substring(0, next) + line.substring(next + 8);
268                                         }
269
270                                         /* if there is text before the next item, write it out. */
271                                         if (lineComplete && !lastLineEmpty) {
272                                                 parts.add(new PlainTextPart("\n"));
273                                         }
274                                         if (next > 0) {
275                                                 parts.add(new PlainTextPart(line.substring(0, next)));
276                                                 line = line.substring(next);
277                                         }
278                                         lineComplete = false;
279
280                                         String link = nextLink.get().getLink();
281                                         logger.log(Level.FINER, String.format("Found link: %s", link));
282
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());
287                                                 continue;
288                                         }
289
290                                         switch (linkType) {
291                                                 case SONE:
292                                                         renderSoneLink(parts, link);
293                                                         break;
294                                                 case POST:
295                                                         renderPostLink(parts, link);
296                                                         break;
297                                                 case KSK:
298                                                 case CHK:
299                                                 case SSK:
300                                                 case USK:
301                                                         renderFreenetLink(parts, link, linkType, context);
302                                                         break;
303                                                 case HTTP:
304                                                 case HTTPS:
305                                                         renderHttpLink(parts, link, linkType);
306                                                         break;
307                                                 case FREEMAIL:
308                                                         renderFreemailLink(parts, link);
309                                         }
310
311                                         line = nextLink.get().getRemainder();
312                                 }
313                                 lastLineEmpty = false;
314                         }
315                 } catch (IOException ioe1) {
316                         // a buffered reader around a string reader should never throw.
317                         throw new RuntimeException(ioe1);
318                 }
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())) {
322                                 break;
323                         }
324                         parts.remove(partIndex);
325                 }
326                 return parts;
327         }
328
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();
337                                 }
338                         }
339                 }
340                 return Optional.fromNullable(earliestNextLink);
341         }
342
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))));
348                 } else {
349                         parts.add(new PlainTextPart(line));
350                 }
351         }
352
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()));
359                         } else {
360                                 parts.add(new PlainTextPart(line.substring(0, 43)));
361                         }
362                 } else {
363                         parts.add(new PlainTextPart(line));
364                 }
365         }
366
367         private void renderFreenetLink(List<Part> parts, String link, LinkType linkType, @Nullable SoneTextParserContext context) {
368                 String name = link;
369                 String linkWithoutParameters = link;
370                 if (name.indexOf('?') > -1) {
371                         linkWithoutParameters = name = name.substring(0, name.indexOf('?'));
372                 }
373                 if (name.endsWith("/")) {
374                         name = name.substring(0, name.length() - 1);
375                 }
376                 try {
377                         FreenetURI uri = new FreenetURI(name);
378                         name = uri.lastMetaString();
379                         if (name == null) {
380                                 name = uri.getDocName();
381                         }
382                         if (name == null) {
383                                 name = link.substring(0, Math.min(9, link.length()));
384                         }
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));
396                 }
397         }
398
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);
405                 }
406                 if (name.endsWith("/")) {
407                         name = name.substring(0, name.length() - 1);
408                 }
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);
411                 }
412                 if (name.indexOf('?') > -1) {
413                         name = name.substring(0, name.indexOf('?'));
414                 }
415                 parts.add(new LinkPart(link, name));
416         }
417
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));
424         }
425
426         private static boolean isPunctuation(char character) {
427                 return (character == '.') || (character == ',') || (character == '!') || (character == '?');
428         }
429
430 }