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