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