Improve parsing of sone:// and post:// links.
[Sone.git] / src / main / java / net / pterodactylus / sone / text / FreenetLinkParser.java
1 /*
2  * Sone - FreenetLinkParser.java - Copyright © 2010 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.io.StringReader;
24 import java.net.MalformedURLException;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29
30 import net.pterodactylus.sone.core.Core;
31 import net.pterodactylus.sone.data.Post;
32 import net.pterodactylus.sone.data.Sone;
33 import net.pterodactylus.sone.template.SoneAccessor;
34 import net.pterodactylus.util.logging.Logging;
35 import net.pterodactylus.util.template.TemplateContextFactory;
36 import net.pterodactylus.util.template.TemplateParser;
37 import freenet.keys.FreenetURI;
38
39 /**
40  * {@link Parser} implementation that can recognize Freenet URIs.
41  *
42  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
43  */
44 public class FreenetLinkParser implements Parser<FreenetLinkParserContext> {
45
46         /** The logger. */
47         private static final Logger logger = Logging.getLogger(FreenetLinkParser.class);
48
49         /** Pattern to detect whitespace. */
50         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]");
51
52         /**
53          * Enumeration for all recognized link types.
54          *
55          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
56          */
57         private enum LinkType {
58
59                 /** Link is a KSK. */
60                 KSK,
61
62                 /** Link is a CHK. */
63                 CHK,
64
65                 /** Link is an SSK. */
66                 SSK,
67
68                 /** Link is a USK. */
69                 USK,
70
71                 /** Link is HTTP. */
72                 HTTP,
73
74                 /** Link is HTTPS. */
75                 HTTPS,
76
77                 /** Link is a Sone. */
78                 SONE,
79
80                 /** Link is a post. */
81                 POST,
82
83         }
84
85         /** The core. */
86         private final Core core;
87
88         /** The template factory. */
89         private final TemplateContextFactory templateContextFactory;
90
91         /**
92          * Creates a new freenet link parser.
93          *
94          * @param core
95          *            The core
96          * @param templateContextFactory
97          *            The template context factory
98          */
99         public FreenetLinkParser(Core core, TemplateContextFactory templateContextFactory) {
100                 this.core = core;
101                 this.templateContextFactory = templateContextFactory;
102         }
103
104         //
105         // PART METHODS
106         //
107
108         /**
109          * {@inheritDoc}
110          */
111         @Override
112         public Part parse(FreenetLinkParserContext context, Reader source) throws IOException {
113                 PartContainer parts = new PartContainer();
114                 BufferedReader bufferedReader = (source instanceof BufferedReader) ? (BufferedReader) source : new BufferedReader(source);
115                 String line;
116                 boolean lastLineEmpty = true;
117                 int emptyLines = 0;
118                 while ((line = bufferedReader.readLine()) != null) {
119                         if (line.trim().length() == 0) {
120                                 if (lastLineEmpty) {
121                                         continue;
122                                 }
123                                 parts.add(createPlainTextPart("\n"));
124                                 ++emptyLines;
125                                 lastLineEmpty = emptyLines == 2;
126                                 continue;
127                         }
128                         emptyLines = 0;
129                         boolean lineComplete = true;
130                         while (line.length() > 0) {
131                                 int nextKsk = line.indexOf("KSK@");
132                                 int nextChk = line.indexOf("CHK@");
133                                 int nextSsk = line.indexOf("SSK@");
134                                 int nextUsk = line.indexOf("USK@");
135                                 int nextHttp = line.indexOf("http://");
136                                 int nextHttps = line.indexOf("https://");
137                                 int nextSone = line.indexOf("sone://");
138                                 int nextPost = line.indexOf("post://");
139                                 if ((nextKsk == -1) && (nextChk == -1) && (nextSsk == -1) && (nextUsk == -1) && (nextHttp == -1) && (nextHttps == -1) && (nextSone == -1) && (nextPost == -1)) {
140                                         if (lineComplete && !lastLineEmpty) {
141                                                 parts.add(createPlainTextPart("\n" + line));
142                                         } else {
143                                                 parts.add(createPlainTextPart(line));
144                                         }
145                                         break;
146                                 }
147                                 int next = Integer.MAX_VALUE;
148                                 LinkType linkType = null;
149                                 if ((nextKsk > -1) && (nextKsk < next)) {
150                                         next = nextKsk;
151                                         linkType = LinkType.KSK;
152                                 }
153                                 if ((nextChk > -1) && (nextChk < next)) {
154                                         next = nextChk;
155                                         linkType = LinkType.CHK;
156                                 }
157                                 if ((nextSsk > -1) && (nextSsk < next)) {
158                                         next = nextSsk;
159                                         linkType = LinkType.SSK;
160                                 }
161                                 if ((nextUsk > -1) && (nextUsk < next)) {
162                                         next = nextUsk;
163                                         linkType = LinkType.USK;
164                                 }
165                                 if ((nextHttp > -1) && (nextHttp < next)) {
166                                         next = nextHttp;
167                                         linkType = LinkType.HTTP;
168                                 }
169                                 if ((nextHttps > -1) && (nextHttps < next)) {
170                                         next = nextHttps;
171                                         linkType = LinkType.HTTPS;
172                                 }
173                                 if ((nextSone > -1) && (nextSone < next)) {
174                                         next = nextSone;
175                                         linkType = LinkType.SONE;
176                                 }
177                                 if ((nextPost > -1) && (nextPost < next)) {
178                                         next = nextPost;
179                                         linkType = LinkType.POST;
180                                 }
181                                 if (linkType == LinkType.SONE) {
182                                         if (next > 0) {
183                                                 parts.add(createPlainTextPart(line.substring(0, next)));
184                                         }
185                                         if (line.length() >= (next + 7 + 43)) {
186                                                 String soneId = line.substring(next + 7, next + 50);
187                                                 Sone sone = core.getSone(soneId, false);
188                                                 if (sone != null) {
189                                                         parts.add(createInSoneLinkPart("viewSone.html?sone=" + soneId, SoneAccessor.getNiceName(sone)));
190                                                 } else {
191                                                         parts.add(createPlainTextPart(line.substring(next, next + 50)));
192                                                 }
193                                                 line = line.substring(next + 50);
194                                         } else {
195                                                 parts.add(createPlainTextPart(line.substring(next)));
196                                                 line = "";
197                                         }
198                                         continue;
199                                 }
200                                 if (linkType == LinkType.POST) {
201                                         if (next > 0) {
202                                                 parts.add(createPlainTextPart(line.substring(0, next)));
203                                         }
204                                         if (line.length() >= (next + 7 + 36)) {
205                                                 String postId = line.substring(next + 7, next + 43);
206                                                 Post post = core.getPost(postId, false);
207                                                 if ((post != null) && (post.getSone() != null)) {
208                                                         String postText = post.getText();
209                                                         postText = postText.substring(0, Math.min(postText.length(), 20)) + "…";
210                                                         Sone postSone = post.getSone();
211                                                         parts.add(createInSoneLinkPart("viewPost.html?post=" + postId, postText, (postSone == null) ? postText : SoneAccessor.getNiceName(post.getSone())));
212                                                 } else {
213                                                         parts.add(createPlainTextPart(line.substring(next, next + 43)));
214                                                 }
215                                                 line = line.substring(next + 43);
216                                         } else {
217                                                 parts.add(createPlainTextPart(line.substring(next)));
218                                                 line = "";
219                                         }
220                                         continue;
221                                 }
222                                 if ((next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
223                                         next -= 8;
224                                         line = line.substring(0, next) + line.substring(next + 8);
225                                 }
226                                 Matcher matcher = whitespacePattern.matcher(line);
227                                 int nextSpace = matcher.find(next) ? matcher.start() : line.length();
228                                 if (nextSpace > (next + 4)) {
229                                         if (!lastLineEmpty && lineComplete) {
230                                                 parts.add(createPlainTextPart("\n" + line.substring(0, next)));
231                                         } else {
232                                                 parts.add(createPlainTextPart(line.substring(0, next)));
233                                         }
234                                         String link = line.substring(next, nextSpace);
235                                         String name = link;
236                                         logger.log(Level.FINER, "Found link: %s", link);
237                                         logger.log(Level.FINEST, "Next: %d, CHK: %d, SSK: %d, USK: %d", new Object[] { next, nextChk, nextSsk, nextUsk });
238
239                                         if ((linkType == LinkType.KSK) || (linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) {
240                                                 FreenetURI uri;
241                                                 if (name.indexOf('?') > -1) {
242                                                         name = name.substring(0, name.indexOf('?'));
243                                                 }
244                                                 if (name.endsWith("/")) {
245                                                         name = name.substring(0, name.length() - 1);
246                                                 }
247                                                 try {
248                                                         uri = new FreenetURI(name);
249                                                         name = uri.lastMetaString();
250                                                         if (name == null) {
251                                                                 name = uri.getDocName();
252                                                         }
253                                                         if (name == null) {
254                                                                 name = link.substring(0, Math.min(9, link.length()));
255                                                         }
256                                                         boolean fromPostingSone = ((linkType == LinkType.SSK) || (linkType == LinkType.USK)) && link.substring(4, Math.min(link.length(), 47)).equals(context.getPostingSone().getId());
257                                                         parts.add(fromPostingSone ? createTrustedFreenetLinkPart(link, name) : createFreenetLinkPart(link, name));
258                                                 } catch (MalformedURLException mue1) {
259                                                         /* not a valid link, insert as plain text. */
260                                                         parts.add(createPlainTextPart(link));
261                                                 } catch (NullPointerException npe1) {
262                                                         /* FreenetURI sometimes throws these, too. */
263                                                         parts.add(createPlainTextPart(link));
264                                                 } catch (ArrayIndexOutOfBoundsException aioobe1) {
265                                                         /* oh, and these, too. */
266                                                         parts.add(createPlainTextPart(link));
267                                                 }
268                                         } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
269                                                 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
270                                                 int firstSlash = name.indexOf('/');
271                                                 int lastSlash = name.lastIndexOf('/');
272                                                 if ((lastSlash - firstSlash) > 3) {
273                                                         name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
274                                                 }
275                                                 if (name.endsWith("/")) {
276                                                         name = name.substring(0, name.length() - 1);
277                                                 }
278                                                 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
279                                                         name = name.substring(4);
280                                                 }
281                                                 if (name.indexOf('?') > -1) {
282                                                         name = name.substring(0, name.indexOf('?'));
283                                                 }
284                                                 link = "?_CHECKED_HTTP_=" + link;
285                                                 parts.add(createInternetLinkPart(link, name));
286                                         }
287                                         line = line.substring(nextSpace);
288                                 } else {
289                                         if (!lastLineEmpty && lineComplete) {
290                                                 parts.add(createPlainTextPart("\n" + line.substring(0, next + 4)));
291                                         } else {
292                                                 parts.add(createPlainTextPart(line.substring(0, next + 4)));
293                                         }
294                                         line = line.substring(next + 4);
295                                 }
296                                 lineComplete = false;
297                         }
298                         lastLineEmpty = false;
299                 }
300                 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
301                         if (!parts.getPart(partIndex).toString().equals("\n")) {
302                                 break;
303                         }
304                         parts.removePart(partIndex);
305                 }
306                 return parts;
307         }
308
309         //
310         // PRIVATE METHODS
311         //
312
313         /**
314          * Creates a new plain text part based on a template.
315          *
316          * @param text
317          *            The text to display
318          * @return The part that displays the given text
319          */
320         private Part createPlainTextPart(String text) {
321                 return new TemplatePart(templateContextFactory, TemplateParser.parse(new StringReader("<% text|html>"))).set("text", text);
322         }
323
324         /**
325          * Creates a new part based on a template that links to a site within the
326          * normal internet.
327          *
328          * @param link
329          *            The target of the link
330          * @param name
331          *            The name of the link
332          * @return The part that displays the link
333          */
334         private Part createInternetLinkPart(String link, String name) {
335                 return new TemplatePart(templateContextFactory, TemplateParser.parse(new StringReader("<a class=\"internet\" href=\"/<% link|html>\" title=\"<% link|html>\"><% name|html></a>"))).set("link", link).set("name", name);
336         }
337
338         /**
339          * Creates a new part based on a template that links to a site within
340          * freenet.
341          *
342          * @param link
343          *            The target of the link
344          * @param name
345          *            The name of the link
346          * @return The part that displays the link
347          */
348         private Part createFreenetLinkPart(String link, String name) {
349                 return new TemplatePart(templateContextFactory, TemplateParser.parse(new StringReader("<a class=\"freenet\" href=\"/<% link|html>\" title=\"<% link|html>\"><% name|html></a>"))).set("link", link).set("name", name);
350         }
351
352         /**
353          * Creates a new part based on a template that links to a page in the
354          * poster’s keyspace.
355          *
356          * @param link
357          *            The target of the link
358          * @param name
359          *            The name of the link
360          * @return The part that displays the link
361          */
362         private Part createTrustedFreenetLinkPart(String link, String name) {
363                 return new TemplatePart(templateContextFactory, TemplateParser.parse(new StringReader("<a class=\"freenet-trusted\" href=\"/<% link|html>\" title=\"<% link|html>\"><% name|html></a>"))).set("link", link).set("name", name);
364         }
365
366         /**
367          * Creates a new part based on a template that links to a page in Sone.
368          *
369          * @param link
370          *            The target of the link
371          * @param name
372          *            The name of the link
373          * @return The part that displays the link
374          */
375         private Part createInSoneLinkPart(String link, String name) {
376                 return createInSoneLinkPart(link, name, name);
377         }
378
379         /**
380          * Creates a new part based on a template that links to a page in Sone.
381          *
382          * @param link
383          *            The target of the link
384          * @param name
385          *            The name of the link
386          * @param title
387          *            The title attribute of the link
388          * @return The part that displays the link
389          */
390         private Part createInSoneLinkPart(String link, String name, String title) {
391                 return new TemplatePart(templateContextFactory, TemplateParser.parse(new StringReader("<a class=\"in-sone\" href=\"<%link|html>\" title=\"<%title|html>\"><%name|html></a>"))).set("link", link).set("name", name).set("title", title);
392         }
393
394 }