Merge branch 'release-0.9.5'
[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                                         Matcher matcher = whitespacePattern.matcher(line);
179                                         int nextSpace = matcher.find(0) ? matcher.start() : line.length();
180                                         String link = line.substring(0, nextSpace);
181                                         String name = link;
182                                         logger.log(Level.FINER, String.format("Found link: %s", link));
183
184                                         /* if there is no text after the scheme, it’s not a link! */
185                                         if (link.equals(linkType.getScheme())) {
186                                                 parts.add(new PlainTextPart(linkType.getScheme()));
187                                                 line = line.substring(linkType.getScheme().length());
188                                                 continue;
189                                         }
190
191                                         if (linkType == LinkType.SONE) {
192                                                 if (line.length() >= (7 + 43)) {
193                                                         String soneId = line.substring(7, 50);
194                                                         Optional<Sone> sone = soneProvider.getSone(soneId);
195                                                         if (!sone.isPresent()) {
196                                                                 /*
197                                                                  * don’t use create=true above, we don’t want
198                                                                  * the empty shell.
199                                                                  */
200                                                                 sone = Optional.<Sone>of(new IdOnlySone(soneId));
201                                                         }
202                                                         parts.add(new SonePart(sone.get()));
203                                                         line = line.substring(50);
204                                                 } else {
205                                                         parts.add(new PlainTextPart(line));
206                                                         line = "";
207                                                 }
208                                                 continue;
209                                         }
210                                         if (linkType == LinkType.POST) {
211                                                 if (line.length() >= (7 + 36)) {
212                                                         String postId = line.substring(7, 43);
213                                                         Optional<Post> post = postProvider.getPost(postId);
214                                                         if (post.isPresent()) {
215                                                                 parts.add(new PostPart(post.get()));
216                                                         } else {
217                                                                 parts.add(new PlainTextPart(line.substring(0, 43)));
218                                                         }
219                                                         line = line.substring(43);
220                                                 } else {
221                                                         parts.add(new PlainTextPart(line));
222                                                         line = "";
223                                                 }
224                                                 continue;
225                                         }
226
227                                         if (linkType.isFreenetLink()) {
228                                                 FreenetURI uri;
229                                                 if (name.indexOf('?') > -1) {
230                                                         name = name.substring(0, name.indexOf('?'));
231                                                 }
232                                                 if (name.endsWith("/")) {
233                                                         name = name.substring(0, name.length() - 1);
234                                                 }
235                                                 try {
236                                                         uri = new FreenetURI(name);
237                                                         name = uri.lastMetaString();
238                                                         if (name == null) {
239                                                                 name = uri.getDocName();
240                                                         }
241                                                         if (name == null) {
242                                                                 name = link.substring(0, Math.min(9, link.length()));
243                                                         }
244                                                         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());
245                                                         parts.add(new FreenetLinkPart(link, name, fromPostingSone));
246                                                 } catch (MalformedURLException mue1) {
247                                                         /* not a valid link, insert as plain text. */
248                                                         parts.add(new PlainTextPart(link));
249                                                 } catch (NullPointerException npe1) {
250                                                         /* FreenetURI sometimes throws these, too. */
251                                                         parts.add(new PlainTextPart(link));
252                                                 } catch (ArrayIndexOutOfBoundsException aioobe1) {
253                                                         /* oh, and these, too. */
254                                                         parts.add(new PlainTextPart(link));
255                                                 }
256                                         } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
257                                                 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
258                                                 int firstSlash = name.indexOf('/');
259                                                 int lastSlash = name.lastIndexOf('/');
260                                                 if ((lastSlash - firstSlash) > 3) {
261                                                         name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
262                                                 }
263                                                 if (name.endsWith("/")) {
264                                                         name = name.substring(0, name.length() - 1);
265                                                 }
266                                                 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
267                                                         name = name.substring(4);
268                                                 }
269                                                 if (name.indexOf('?') > -1) {
270                                                         name = name.substring(0, name.indexOf('?'));
271                                                 }
272                                                 parts.add(new LinkPart(link, name));
273                                         }
274                                         line = line.substring(nextSpace);
275                                 }
276                                 lastLineEmpty = false;
277                         }
278                 } catch (IOException ioe1) {
279                         // a buffered reader around a string reader should never throw.
280                         throw new RuntimeException(ioe1);
281                 } finally {
282                         Closer.close(bufferedReader);
283                 }
284                 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
285                         Part part = parts.getPart(partIndex);
286                         if (!(part instanceof PlainTextPart) || !"\n".equals(part.getText())) {
287                                 break;
288                         }
289                         parts.removePart(partIndex);
290                 }
291                 return parts;
292         }
293
294         private static class NextLink {
295
296                 private final int position;
297                 private final LinkType linkType;
298
299                 private NextLink(int position, LinkType linkType) {
300                         this.position = position;
301                         this.linkType = linkType;
302                 }
303
304                 public int getPosition() {
305                         return position;
306                 }
307
308                 public LinkType getLinkType() {
309                         return linkType;
310                 }
311
312                 public static Optional<NextLink> findNextLink(String line) {
313                         int earliestLinkPosition = Integer.MAX_VALUE;
314                         LinkType linkType = null;
315                         for (LinkType possibleLinkType : LinkType.values()) {
316                                 int nextLinkPosition = line.indexOf(possibleLinkType.getScheme());
317                                 if (nextLinkPosition > -1) {
318                                         if (nextLinkPosition < earliestLinkPosition) {
319                                                 earliestLinkPosition = nextLinkPosition;
320                                                 linkType = possibleLinkType;
321                                         }
322                                 }
323                         }
324                         return earliestLinkPosition < Integer.MAX_VALUE ?
325                                         Optional.of(new NextLink(earliestLinkPosition, linkType)) : Optional.<NextLink>absent();
326                 }
327
328         }
329
330 }