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