Extract an interface out of Sone.
[Sone.git] / src / main / java / net / pterodactylus / sone / text / SoneTextParser.java
1 /*
2  * Sone - SoneTextParser.java - Copyright © 2010–2013 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 java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.Reader;
23 import java.net.MalformedURLException;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 import net.pterodactylus.sone.data.Post;
30 import net.pterodactylus.sone.data.Sone;
31 import net.pterodactylus.sone.data.SoneImpl;
32 import net.pterodactylus.sone.database.PostProvider;
33 import net.pterodactylus.sone.database.SoneProvider;
34 import net.pterodactylus.util.io.Closer;
35 import net.pterodactylus.util.logging.Logging;
36
37 import com.google.common.base.Optional;
38
39 import freenet.keys.FreenetURI;
40
41 /**
42  * {@link Parser} implementation that can recognize Freenet URIs.
43  *
44  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
45  */
46 public class SoneTextParser implements Parser<SoneTextParserContext> {
47
48         /** The logger. */
49         private static final Logger logger = Logging.getLogger(SoneTextParser.class);
50
51         /** Pattern to detect whitespace. */
52         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]");
53
54         /**
55          * Enumeration for all recognized link types.
56          *
57          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
58          */
59         private enum LinkType {
60
61                 /** Link is a KSK. */
62                 KSK("KSK@"),
63
64                 /** Link is a CHK. */
65                 CHK("CHK@"),
66
67                 /** Link is an SSK. */
68                 SSK("SSK@"),
69
70                 /** Link is a USK. */
71                 USK("USK@"),
72
73                 /** Link is HTTP. */
74                 HTTP("http://"),
75
76                 /** Link is HTTPS. */
77                 HTTPS("https://"),
78
79                 /** Link is a Sone. */
80                 SONE("sone://"),
81
82                 /** Link is a post. */
83                 POST("post://");
84
85                 /** The scheme identifying this link type. */
86                 private final String scheme;
87
88                 /**
89                  * Creates a new link type identified by the given scheme.
90                  *
91                  * @param scheme
92                  *            The scheme of the link type
93                  */
94                 private LinkType(String scheme) {
95                         this.scheme = scheme;
96                 }
97
98                 /**
99                  * Returns the scheme of this link type.
100                  *
101                  * @return The scheme of this link type
102                  */
103                 public String getScheme() {
104                         return scheme;
105                 }
106
107         }
108
109         /** The Sone provider. */
110         private final SoneProvider soneProvider;
111
112         /** The post provider. */
113         private final PostProvider postProvider;
114
115         /**
116          * Creates a new freenet link parser.
117          *
118          * @param soneProvider
119          *            The Sone provider
120          * @param postProvider
121          *            The post provider
122          */
123         public SoneTextParser(SoneProvider soneProvider, PostProvider postProvider) {
124                 this.soneProvider = soneProvider;
125                 this.postProvider = postProvider;
126         }
127
128         //
129         // PART METHODS
130         //
131
132         /**
133          * {@inheritDoc}
134          */
135         @Override
136         public Iterable<Part> parse(SoneTextParserContext context, Reader source) throws IOException {
137                 PartContainer parts = new PartContainer();
138                 BufferedReader bufferedReader = (source instanceof BufferedReader) ? (BufferedReader) source : new BufferedReader(source);
139                 try {
140                         String line;
141                         boolean lastLineEmpty = true;
142                         int emptyLines = 0;
143                         while ((line = bufferedReader.readLine()) != null) {
144                                 if (line.trim().length() == 0) {
145                                         if (lastLineEmpty) {
146                                                 continue;
147                                         }
148                                         parts.add(new PlainTextPart("\n"));
149                                         ++emptyLines;
150                                         lastLineEmpty = emptyLines == 2;
151                                         continue;
152                                 }
153                                 emptyLines = 0;
154                                 /*
155                                  * lineComplete tracks whether the block you are parsing is the
156                                  * first block of the line. this is important because sometimes
157                                  * you have to add an additional line break.
158                                  */
159                                 boolean lineComplete = true;
160                                 while (line.length() > 0) {
161                                         int nextKsk = line.indexOf("KSK@");
162                                         int nextChk = line.indexOf("CHK@");
163                                         int nextSsk = line.indexOf("SSK@");
164                                         int nextUsk = line.indexOf("USK@");
165                                         int nextHttp = line.indexOf("http://");
166                                         int nextHttps = line.indexOf("https://");
167                                         int nextSone = line.indexOf("sone://");
168                                         int nextPost = line.indexOf("post://");
169                                         if ((nextKsk == -1) && (nextChk == -1) && (nextSsk == -1) && (nextUsk == -1) && (nextHttp == -1) && (nextHttps == -1) && (nextSone == -1) && (nextPost == -1)) {
170                                                 if (lineComplete && !lastLineEmpty) {
171                                                         parts.add(new PlainTextPart("\n" + line));
172                                                 } else {
173                                                         parts.add(new PlainTextPart(line));
174                                                 }
175                                                 break;
176                                         }
177                                         int next = Integer.MAX_VALUE;
178                                         LinkType linkType = null;
179                                         if ((nextKsk > -1) && (nextKsk < next)) {
180                                                 next = nextKsk;
181                                                 linkType = LinkType.KSK;
182                                         }
183                                         if ((nextChk > -1) && (nextChk < next)) {
184                                                 next = nextChk;
185                                                 linkType = LinkType.CHK;
186                                         }
187                                         if ((nextSsk > -1) && (nextSsk < next)) {
188                                                 next = nextSsk;
189                                                 linkType = LinkType.SSK;
190                                         }
191                                         if ((nextUsk > -1) && (nextUsk < next)) {
192                                                 next = nextUsk;
193                                                 linkType = LinkType.USK;
194                                         }
195                                         if ((nextHttp > -1) && (nextHttp < next)) {
196                                                 next = nextHttp;
197                                                 linkType = LinkType.HTTP;
198                                         }
199                                         if ((nextHttps > -1) && (nextHttps < next)) {
200                                                 next = nextHttps;
201                                                 linkType = LinkType.HTTPS;
202                                         }
203                                         if ((nextSone > -1) && (nextSone < next)) {
204                                                 next = nextSone;
205                                                 linkType = LinkType.SONE;
206                                         }
207                                         if ((nextPost > -1) && (nextPost < next)) {
208                                                 next = nextPost;
209                                                 linkType = LinkType.POST;
210                                         }
211
212                                         /* cut off “freenet:” from before keys. */
213                                         if (((linkType == LinkType.KSK) || (linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
214                                                 next -= 8;
215                                                 line = line.substring(0, next) + line.substring(next + 8);
216                                         }
217
218                                         /* if there is text before the next item, write it out. */
219                                         if (lineComplete && !lastLineEmpty) {
220                                                 parts.add(new PlainTextPart("\n"));
221                                         }
222                                         if (next > 0) {
223                                                 parts.add(new PlainTextPart(line.substring(0, next)));
224                                                 line = line.substring(next);
225                                                 next = 0;
226                                         }
227                                         lineComplete = false;
228
229                                         Matcher matcher = whitespacePattern.matcher(line);
230                                         int nextSpace = matcher.find(0) ? matcher.start() : line.length();
231                                         String link = line.substring(0, nextSpace);
232                                         String name = link;
233                                         logger.log(Level.FINER, String.format("Found link: %s", link));
234                                         logger.log(Level.FINEST, String.format("CHK: %d, SSK: %d, USK: %d", nextChk, nextSsk, nextUsk));
235
236                                         /* if there is no text after the scheme, it’s not a link! */
237                                         if (link.equals(linkType.getScheme())) {
238                                                 parts.add(new PlainTextPart(linkType.getScheme()));
239                                                 line = line.substring(linkType.getScheme().length());
240                                                 continue;
241                                         }
242
243                                         if (linkType == LinkType.SONE) {
244                                                 if (line.length() >= (7 + 43)) {
245                                                         String soneId = line.substring(7, 50);
246                                                         Optional<Sone> sone = soneProvider.getSone(soneId);
247                                                         if (!sone.isPresent()) {
248                                                                 /*
249                                                                  * don’t use create=true above, we don’t want
250                                                                  * the empty shell.
251                                                                  */
252                                                                 sone = Optional.<Sone>of(new SoneImpl(soneId, false));
253                                                         }
254                                                         parts.add(new SonePart(sone.get()));
255                                                         line = line.substring(50);
256                                                 } else {
257                                                         parts.add(new PlainTextPart(line));
258                                                         line = "";
259                                                 }
260                                                 continue;
261                                         }
262                                         if (linkType == LinkType.POST) {
263                                                 if (line.length() >= (7 + 36)) {
264                                                         String postId = line.substring(7, 43);
265                                                         Optional<Post> post = postProvider.getPost(postId);
266                                                         if (post.isPresent()) {
267                                                                 parts.add(new PostPart(post.get()));
268                                                         } else {
269                                                                 parts.add(new PlainTextPart(line.substring(0, 43)));
270                                                         }
271                                                         line = line.substring(43);
272                                                 } else {
273                                                         parts.add(new PlainTextPart(line));
274                                                         line = "";
275                                                 }
276                                                 continue;
277                                         }
278
279                                         if ((linkType == LinkType.KSK) || (linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) {
280                                                 FreenetURI uri;
281                                                 if (name.indexOf('?') > -1) {
282                                                         name = name.substring(0, name.indexOf('?'));
283                                                 }
284                                                 if (name.endsWith("/")) {
285                                                         name = name.substring(0, name.length() - 1);
286                                                 }
287                                                 try {
288                                                         uri = new FreenetURI(name);
289                                                         name = uri.lastMetaString();
290                                                         if (name == null) {
291                                                                 name = uri.getDocName();
292                                                         }
293                                                         if (name == null) {
294                                                                 name = link.substring(0, Math.min(9, link.length()));
295                                                         }
296                                                         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());
297                                                         parts.add(new FreenetLinkPart(link, name, fromPostingSone));
298                                                 } catch (MalformedURLException mue1) {
299                                                         /* not a valid link, insert as plain text. */
300                                                         parts.add(new PlainTextPart(link));
301                                                 } catch (NullPointerException npe1) {
302                                                         /* FreenetURI sometimes throws these, too. */
303                                                         parts.add(new PlainTextPart(link));
304                                                 } catch (ArrayIndexOutOfBoundsException aioobe1) {
305                                                         /* oh, and these, too. */
306                                                         parts.add(new PlainTextPart(link));
307                                                 }
308                                         } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
309                                                 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
310                                                 int firstSlash = name.indexOf('/');
311                                                 int lastSlash = name.lastIndexOf('/');
312                                                 if ((lastSlash - firstSlash) > 3) {
313                                                         name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
314                                                 }
315                                                 if (name.endsWith("/")) {
316                                                         name = name.substring(0, name.length() - 1);
317                                                 }
318                                                 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
319                                                         name = name.substring(4);
320                                                 }
321                                                 if (name.indexOf('?') > -1) {
322                                                         name = name.substring(0, name.indexOf('?'));
323                                                 }
324                                                 parts.add(new LinkPart(link, name));
325                                         }
326                                         line = line.substring(nextSpace);
327                                 }
328                                 lastLineEmpty = false;
329                         }
330                 } finally {
331                         if (bufferedReader != source) {
332                                 Closer.close(bufferedReader);
333                         }
334                 }
335                 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
336                         Part part = parts.getPart(partIndex);
337                         if (!(part instanceof PlainTextPart) || !"\n".equals(((PlainTextPart) part).getText())) {
338                                 break;
339                         }
340                         parts.removePart(partIndex);
341                 }
342                 return parts;
343         }
344
345 }