1ef77d2286fdc58d544c176716c46479b2672123
[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.util.logging.Logging;
31 import net.pterodactylus.util.template.TemplateFactory;
32 import freenet.keys.FreenetURI;
33
34 /**
35  * {@link Parser} implementation that can recognize Freenet URIs.
36  *
37  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
38  */
39 public class FreenetLinkParser implements Parser<FreenetLinkParserContext> {
40
41         /** The logger. */
42         private static final Logger logger = Logging.getLogger(FreenetLinkParser.class);
43
44         /** Pattern to detect whitespace. */
45         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]");
46
47         /**
48          * Enumeration for all recognized link types.
49          *
50          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
51          */
52         private enum LinkType {
53
54                 /** Link is a KSK. */
55                 KSK,
56
57                 /** Link is a CHK. */
58                 CHK,
59
60                 /** Link is an SSK. */
61                 SSK,
62
63                 /** Link is a USK. */
64                 USK,
65
66                 /** Link is HTTP. */
67                 HTTP,
68
69                 /** Link is HTTPS. */
70                 HTTPS;
71
72         }
73
74         /** The template factory. */
75         private final TemplateFactory templateFactory;
76
77         /**
78          * Creates a new freenet link parser.
79          *
80          * @param templateFactory
81          *            The template factory
82          */
83         public FreenetLinkParser(TemplateFactory templateFactory) {
84                 this.templateFactory = templateFactory;
85         }
86
87         //
88         // PART METHODS
89         //
90
91         /**
92          * {@inheritDoc}
93          */
94         @Override
95         public Part parse(FreenetLinkParserContext context, Reader source) throws IOException {
96                 PartContainer parts = new PartContainer();
97                 BufferedReader bufferedReader = (source instanceof BufferedReader) ? (BufferedReader) source : new BufferedReader(source);
98                 String line;
99                 while ((line = bufferedReader.readLine()) != null) {
100                         line = line.trim() + "\n";
101                         while (line.length() > 0) {
102                                 int nextKsk = line.indexOf("KSK@");
103                                 int nextChk = line.indexOf("CHK@");
104                                 int nextSsk = line.indexOf("SSK@");
105                                 int nextUsk = line.indexOf("USK@");
106                                 int nextHttp = line.indexOf("http://");
107                                 int nextHttps = line.indexOf("https://");
108                                 if ((nextKsk == -1) && (nextChk == -1) && (nextSsk == -1) && (nextUsk == -1) && (nextHttp == -1) && (nextHttps == -1)) {
109                                         parts.add(createPlainTextPart(line));
110                                         break;
111                                 }
112                                 int next = Integer.MAX_VALUE;
113                                 LinkType linkType = null;
114                                 if ((nextKsk > -1) && (nextKsk < next)) {
115                                         next = nextKsk;
116                                         linkType = LinkType.KSK;
117                                 }
118                                 if ((nextChk > -1) && (nextChk < next)) {
119                                         next = nextChk;
120                                         linkType = LinkType.CHK;
121                                 }
122                                 if ((nextSsk > -1) && (nextSsk < next)) {
123                                         next = nextSsk;
124                                         linkType = LinkType.SSK;
125                                 }
126                                 if ((nextUsk > -1) && (nextUsk < next)) {
127                                         next = nextUsk;
128                                         linkType = LinkType.USK;
129                                 }
130                                 if ((nextHttp > -1) && (nextHttp < next)) {
131                                         next = nextHttp;
132                                         linkType = LinkType.HTTP;
133                                 }
134                                 if ((nextHttps > -1) && (nextHttps < next)) {
135                                         next = nextHttps;
136                                         linkType = LinkType.HTTPS;
137                                 }
138                                 if ((next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
139                                         next -= 8;
140                                         line = line.substring(0, next) + line.substring(next + 8);
141                                 }
142                                 Matcher matcher = whitespacePattern.matcher(line);
143                                 int nextSpace = matcher.find(next) ? matcher.start() : line.length();
144                                 if (nextSpace > (next + 4)) {
145                                         parts.add(createPlainTextPart(line.substring(0, next)));
146                                         String link = line.substring(next, nextSpace);
147                                         String name = link;
148                                         logger.log(Level.FINER, "Found link: %s", link);
149                                         logger.log(Level.FINEST, "Next: %d, CHK: %d, SSK: %d, USK: %d", new Object[] { next, nextChk, nextSsk, nextUsk });
150
151                                         if ((linkType == LinkType.KSK) || (linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) {
152                                                 FreenetURI uri;
153                                                 if (name.indexOf('?') > -1) {
154                                                         name = name.substring(0, name.indexOf('?'));
155                                                 }
156                                                 if (name.endsWith("/")) {
157                                                         name = name.substring(0, name.length() - 1);
158                                                 }
159                                                 try {
160                                                         uri = new FreenetURI(name);
161                                                         name = uri.lastMetaString();
162                                                         if (name == null) {
163                                                                 name = uri.getDocName();
164                                                         }
165                                                         if (name == null) {
166                                                                 name = link.substring(0, Math.min(9, link.length()));
167                                                         }
168                                                         boolean fromPostingSone = ((linkType == LinkType.SSK) || (linkType == LinkType.USK)) && link.substring(4, Math.min(link.length(), 47)).equals(context.getPostingSone().getId());
169                                                         parts.add(fromPostingSone ? createTrustedFreenetLinkPart(link, name) : createFreenetLinkPart(link, name));
170                                                 } catch (MalformedURLException mue1) {
171                                                         /* not a valid link, insert as plain text. */
172                                                         parts.add(createPlainTextPart(link));
173                                                 } catch (NullPointerException npe1) {
174                                                         /* FreenetURI sometimes throws these, too. */
175                                                         parts.add(createPlainTextPart(link));
176                                                 } catch (ArrayIndexOutOfBoundsException aioobe1) {
177                                                         /* oh, and these, too. */
178                                                         parts.add(createPlainTextPart(link));
179                                                 }
180                                         } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
181                                                 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
182                                                 int firstSlash = name.indexOf('/');
183                                                 int lastSlash = name.lastIndexOf('/');
184                                                 if ((lastSlash - firstSlash) > 3) {
185                                                         name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
186                                                 }
187                                                 if (name.endsWith("/")) {
188                                                         name = name.substring(0, name.length() - 1);
189                                                 }
190                                                 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
191                                                         name = name.substring(4);
192                                                 }
193                                                 if (name.indexOf('?') > -1) {
194                                                         name = name.substring(0, name.indexOf('?'));
195                                                 }
196                                                 link = "?_CHECKED_HTTP_=" + link;
197                                                 parts.add(createInternetLinkPart(link, name));
198                                         }
199                                         line = line.substring(nextSpace);
200                                 } else {
201                                         parts.add(createPlainTextPart(line.substring(0, next + 4)));
202                                         line = line.substring(next + 4);
203                                 }
204                         }
205                 }
206                 return parts;
207         }
208
209         //
210         // PRIVATE METHODS
211         //
212
213         /**
214          * Creates a new plain text part based on a template.
215          *
216          * @param text
217          *            The text to display
218          * @return The part that displays the given text
219          */
220         private Part createPlainTextPart(String text) {
221                 return new TemplatePart(templateFactory.createTemplate(new StringReader("<% text|html>"))).set("text", text);
222         }
223
224         /**
225          * Creates a new part based on a template that links to a site within the
226          * normal internet.
227          *
228          * @param link
229          *            The target of the link
230          * @param name
231          *            The name of the link
232          * @return The part that displays the link
233          */
234         private Part createInternetLinkPart(String link, String name) {
235                 return new TemplatePart(templateFactory.createTemplate(new StringReader("<a class=\"internet\" href=\"/<% link|html>\" title=\"<% link|html>\"><% name|html></a>"))).set("link", link).set("name", name);
236         }
237
238         /**
239          * Creates a new part based on a template that links to a site within
240          * freenet.
241          *
242          * @param link
243          *            The target of the link
244          * @param name
245          *            The name of the link
246          * @return The part that displays the link
247          */
248         private Part createFreenetLinkPart(String link, String name) {
249                 return new TemplatePart(templateFactory.createTemplate(new StringReader("<a class=\"freenet\" href=\"/<% link|html>\" title=\"<% link|html>\"><% name|html></a>"))).set("link", link).set("name", name);
250         }
251
252         /**
253          * Creates a new part based on a template that links to a page in the
254          * poster’s keyspace.
255          *
256          * @param link
257          *            The target of the link
258          * @param name
259          *            The name of the link
260          * @return The part that displays the link
261          */
262         private Part createTrustedFreenetLinkPart(String link, String name) {
263                 return new TemplatePart(templateFactory.createTemplate(new StringReader("<a class=\"freenet-trusted\" href=\"/<% link|html>\" title=\"<% link|html>\"><% name|html></a>"))).set("link", link).set("name", name);
264         }
265
266 }