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