2 * Sone - FreenetLinkParser.java - Copyright © 2010 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.text;
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;
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;
36 * {@link Parser} implementation that can recognize Freenet URIs.
38 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
40 public class FreenetLinkParser implements Parser<FreenetLinkParserContext> {
43 private static final Logger logger = Logging.getLogger(FreenetLinkParser.class);
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]");
49 * Enumeration for all recognized link types.
51 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
53 private enum LinkType {
61 /** Link is an SSK. */
75 /** The template factory. */
76 private final TemplateContextFactory templateContextFactory;
79 * Creates a new freenet link parser.
81 * @param templateContextFactory
82 * The template context factory
84 public FreenetLinkParser(TemplateContextFactory templateContextFactory) {
85 this.templateContextFactory = templateContextFactory;
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);
100 boolean lastLineEmpty = true;
102 while ((line = bufferedReader.readLine()) != null) {
104 if (line.length() == 0) {
108 parts.add(createPlainTextPart("\n"));
110 lastLineEmpty = emptyLines == 2;
114 boolean lineComplete = true;
115 while (line.length() > 0) {
116 int nextKsk = line.indexOf("KSK@");
117 int nextChk = line.indexOf("CHK@");
118 int nextSsk = line.indexOf("SSK@");
119 int nextUsk = line.indexOf("USK@");
120 int nextHttp = line.indexOf("http://");
121 int nextHttps = line.indexOf("https://");
122 if ((nextKsk == -1) && (nextChk == -1) && (nextSsk == -1) && (nextUsk == -1) && (nextHttp == -1) && (nextHttps == -1)) {
123 if (lineComplete && !lastLineEmpty) {
124 parts.add(createPlainTextPart("\n" + line));
126 parts.add(createPlainTextPart(line));
130 int next = Integer.MAX_VALUE;
131 LinkType linkType = null;
132 if ((nextKsk > -1) && (nextKsk < next)) {
134 linkType = LinkType.KSK;
136 if ((nextChk > -1) && (nextChk < next)) {
138 linkType = LinkType.CHK;
140 if ((nextSsk > -1) && (nextSsk < next)) {
142 linkType = LinkType.SSK;
144 if ((nextUsk > -1) && (nextUsk < next)) {
146 linkType = LinkType.USK;
148 if ((nextHttp > -1) && (nextHttp < next)) {
150 linkType = LinkType.HTTP;
152 if ((nextHttps > -1) && (nextHttps < next)) {
154 linkType = LinkType.HTTPS;
156 if ((next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
158 line = line.substring(0, next) + line.substring(next + 8);
160 Matcher matcher = whitespacePattern.matcher(line);
161 int nextSpace = matcher.find(next) ? matcher.start() : line.length();
162 if (nextSpace > (next + 4)) {
163 if (!lastLineEmpty && lineComplete) {
164 parts.add(createPlainTextPart("\n" + line.substring(0, next)));
166 parts.add(createPlainTextPart(line.substring(0, next)));
168 String link = line.substring(next, nextSpace);
170 logger.log(Level.FINER, "Found link: %s", link);
171 logger.log(Level.FINEST, "Next: %d, CHK: %d, SSK: %d, USK: %d", new Object[] { next, nextChk, nextSsk, nextUsk });
173 if ((linkType == LinkType.KSK) || (linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) {
175 if (name.indexOf('?') > -1) {
176 name = name.substring(0, name.indexOf('?'));
178 if (name.endsWith("/")) {
179 name = name.substring(0, name.length() - 1);
182 uri = new FreenetURI(name);
183 name = uri.lastMetaString();
185 name = uri.getDocName();
188 name = link.substring(0, Math.min(9, link.length()));
190 boolean fromPostingSone = ((linkType == LinkType.SSK) || (linkType == LinkType.USK)) && link.substring(4, Math.min(link.length(), 47)).equals(context.getPostingSone().getId());
191 parts.add(fromPostingSone ? createTrustedFreenetLinkPart(link, name) : createFreenetLinkPart(link, name));
192 } catch (MalformedURLException mue1) {
193 /* not a valid link, insert as plain text. */
194 parts.add(createPlainTextPart(link));
195 } catch (NullPointerException npe1) {
196 /* FreenetURI sometimes throws these, too. */
197 parts.add(createPlainTextPart(link));
198 } catch (ArrayIndexOutOfBoundsException aioobe1) {
199 /* oh, and these, too. */
200 parts.add(createPlainTextPart(link));
202 } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
203 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
204 int firstSlash = name.indexOf('/');
205 int lastSlash = name.lastIndexOf('/');
206 if ((lastSlash - firstSlash) > 3) {
207 name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
209 if (name.endsWith("/")) {
210 name = name.substring(0, name.length() - 1);
212 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
213 name = name.substring(4);
215 if (name.indexOf('?') > -1) {
216 name = name.substring(0, name.indexOf('?'));
218 link = "?_CHECKED_HTTP_=" + link;
219 parts.add(createInternetLinkPart(link, name));
221 line = line.substring(nextSpace);
223 if (!lastLineEmpty && lineComplete) {
224 parts.add(createPlainTextPart("\n" + line.substring(0, next + 4)));
226 parts.add(createPlainTextPart(line.substring(0, next + 4)));
228 line = line.substring(next + 4);
230 lineComplete = false;
232 lastLineEmpty = false;
234 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
235 if (!parts.getPart(partIndex).toString().equals("\n")) {
238 parts.removePart(partIndex);
248 * Creates a new plain text part based on a template.
251 * The text to display
252 * @return The part that displays the given text
254 private Part createPlainTextPart(String text) {
255 return new TemplatePart(templateContextFactory, TemplateParser.parse(new StringReader("<% text|html>"))).set("text", text);
259 * Creates a new part based on a template that links to a site within the
263 * The target of the link
265 * The name of the link
266 * @return The part that displays the link
268 private Part createInternetLinkPart(String link, String name) {
269 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);
273 * Creates a new part based on a template that links to a site within
277 * The target of the link
279 * The name of the link
280 * @return The part that displays the link
282 private Part createFreenetLinkPart(String link, String name) {
283 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);
287 * Creates a new part based on a template that links to a page in the
291 * The target of the link
293 * The name of the link
294 * @return The part that displays the link
296 private Part createTrustedFreenetLinkPart(String link, String name) {
297 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);