Remove unnecessary cast.
[Sone.git] / src / main / java / net / pterodactylus / sone / text / SoneTextParser.java
1 /*
2  * Sone - SoneTextParser.java - Copyright © 2010–2013 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.net.MalformedURLException;
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.Post;
30 import net.pterodactylus.sone.data.Sone;
31 import net.pterodactylus.sone.data.impl.DefaultSone;
32 import net.pterodactylus.sone.database.Database;
33 import net.pterodactylus.util.io.Closer;
34 import net.pterodactylus.util.logging.Logging;
35
36 import freenet.keys.FreenetURI;
37
38 import com.google.common.base.Optional;
39
40 /**
41  * {@link Parser} implementation that can recognize Freenet URIs.
42  *
43  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
44  */
45 public class SoneTextParser implements Parser<SoneTextParserContext> {
46
47         /** The logger. */
48         private static final Logger logger = Logging.getLogger(SoneTextParser.class);
49
50         /** Pattern to detect whitespace. */
51         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]");
52
53         /**
54          * Enumeration for all recognized link types.
55          *
56          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
57          */
58         private enum LinkType {
59
60                 /** Link is a KSK. */
61                 KSK("KSK@", true),
62
63                 /** Link is a CHK. */
64                 CHK("CHK@", true),
65
66                 /** Link is an SSK. */
67                 SSK("SSK@", true),
68
69                 /** Link is a USK. */
70                 USK("USK@", true),
71
72                 /** Link is HTTP. */
73                 HTTP("http://", false),
74
75                 /** Link is HTTPS. */
76                 HTTPS("https://", false),
77
78                 /** Link is a Sone. */
79                 SONE("sone://", false),
80
81                 /** Link is a post. */
82                 POST("post://", false);
83
84                 /** The scheme identifying this link type. */
85                 private final String scheme;
86                 private final boolean freenetLink;
87
88                 /**
89                  * Creates a new link type identified by the given scheme.
90                  *
91                  * @param scheme
92                  *            The scheme of the link type
93                  * @param freenetLink
94                  */
95                 private LinkType(String scheme, boolean freenetLink) {
96                         this.scheme = scheme;
97                         this.freenetLink = freenetLink;
98                 }
99
100                 /**
101                  * Returns the scheme of this link type.
102                  *
103                  * @return The scheme of this link type
104                  */
105                 public String getScheme() {
106                         return scheme;
107                 }
108
109                 public boolean isFreenetLink() {
110                         return freenetLink;
111                 }
112
113         }
114
115         private final Database database;
116
117         /**
118          * Creates a new freenet link parser.
119          *
120          * @param database
121          */
122         public SoneTextParser(Database database) {
123                 this.database = database;
124         }
125
126         //
127         // PART METHODS
128         //
129
130         @Override
131         public Iterable<Part> parse(SoneTextParserContext context, Reader source) throws IOException {
132                 PartContainer parts = new PartContainer();
133                 BufferedReader bufferedReader = (source instanceof BufferedReader) ? (BufferedReader) source : new BufferedReader(source);
134                 try {
135                         String line;
136                         boolean lastLineEmpty = true;
137                         int emptyLines = 0;
138                         while ((line = bufferedReader.readLine()) != null) {
139                                 if (line.trim().length() == 0) {
140                                         if (lastLineEmpty) {
141                                                 continue;
142                                         }
143                                         parts.add(new PlainTextPart("\n"));
144                                         ++emptyLines;
145                                         lastLineEmpty = emptyLines == 2;
146                                         continue;
147                                 }
148                                 emptyLines = 0;
149                                 /*
150                                  * lineComplete tracks whether the block you are parsing is the
151                                  * first block of the line. this is important because sometimes
152                                  * you have to add an additional line break.
153                                  */
154                                 boolean lineComplete = true;
155                                 while (line.length() > 0) {
156                                         int nextKsk = line.indexOf("KSK@");
157                                         int nextChk = line.indexOf("CHK@");
158                                         int nextSsk = line.indexOf("SSK@");
159                                         int nextUsk = line.indexOf("USK@");
160                                         int nextHttp = line.indexOf("http://");
161                                         int nextHttps = line.indexOf("https://");
162                                         int nextSone = line.indexOf("sone://");
163                                         int nextPost = line.indexOf("post://");
164                                         if ((nextKsk == -1) && (nextChk == -1) && (nextSsk == -1) && (nextUsk == -1) && (nextHttp == -1) && (nextHttps == -1) && (nextSone == -1) && (nextPost == -1)) {
165                                                 if (lineComplete && !lastLineEmpty) {
166                                                         parts.add(new PlainTextPart("\n" + line));
167                                                 } else {
168                                                         parts.add(new PlainTextPart(line));
169                                                 }
170                                                 break;
171                                         }
172                                         int next = Integer.MAX_VALUE;
173                                         LinkType linkType = null;
174                                         if ((nextKsk > -1) && (nextKsk < next)) {
175                                                 next = nextKsk;
176                                                 linkType = LinkType.KSK;
177                                         }
178                                         if ((nextChk > -1) && (nextChk < next)) {
179                                                 next = nextChk;
180                                                 linkType = LinkType.CHK;
181                                         }
182                                         if ((nextSsk > -1) && (nextSsk < next)) {
183                                                 next = nextSsk;
184                                                 linkType = LinkType.SSK;
185                                         }
186                                         if ((nextUsk > -1) && (nextUsk < next)) {
187                                                 next = nextUsk;
188                                                 linkType = LinkType.USK;
189                                         }
190                                         if ((nextHttp > -1) && (nextHttp < next)) {
191                                                 next = nextHttp;
192                                                 linkType = LinkType.HTTP;
193                                         }
194                                         if ((nextHttps > -1) && (nextHttps < next)) {
195                                                 next = nextHttps;
196                                                 linkType = LinkType.HTTPS;
197                                         }
198                                         if ((nextSone > -1) && (nextSone < next)) {
199                                                 next = nextSone;
200                                                 linkType = LinkType.SONE;
201                                         }
202                                         if ((nextPost > -1) && (nextPost < next)) {
203                                                 next = nextPost;
204                                                 linkType = LinkType.POST;
205                                         }
206
207                                         /* cut off “freenet:” from before keys. */
208                                         if (linkType.isFreenetLink() && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
209                                                 next -= 8;
210                                                 line = line.substring(0, next) + line.substring(next + 8);
211                                         }
212
213                                         /* if there is text before the next item, write it out. */
214                                         if (lineComplete && !lastLineEmpty) {
215                                                 parts.add(new PlainTextPart("\n"));
216                                         }
217                                         if (next > 0) {
218                                                 parts.add(new PlainTextPart(line.substring(0, next)));
219                                                 line = line.substring(next);
220                                         }
221                                         lineComplete = false;
222
223                                         Matcher matcher = whitespacePattern.matcher(line);
224                                         int nextSpace = matcher.find(0) ? matcher.start() : line.length();
225                                         String link = line.substring(0, nextSpace);
226                                         String name = link;
227                                         logger.log(Level.FINER, String.format("Found link: %s", link));
228                                         logger.log(Level.FINEST, String.format("CHK: %d, SSK: %d, USK: %d", nextChk, nextSsk, nextUsk));
229
230                                         /* if there is no text after the scheme, it’s not a link! */
231                                         if (link.equals(linkType.getScheme())) {
232                                                 parts.add(new PlainTextPart(linkType.getScheme()));
233                                                 line = line.substring(linkType.getScheme().length());
234                                                 continue;
235                                         }
236
237                                         if (linkType == LinkType.SONE) {
238                                                 if (line.length() >= (7 + 43)) {
239                                                         String soneId = line.substring(7, 50);
240                                                         Optional<Sone> sone = database.getSone(soneId);
241                                                         if (!sone.isPresent()) {
242                                                                 /*
243                                                                  * don’t use create=true above, we don’t want
244                                                                  * the empty shell.
245                                                                  */
246                                                                 sone = Optional.<Sone>of(new DefaultSone(database, soneId, false, null));
247                                                         }
248                                                         parts.add(new SonePart(sone.get()));
249                                                         line = line.substring(50);
250                                                 } else {
251                                                         parts.add(new PlainTextPart(line));
252                                                         line = "";
253                                                 }
254                                                 continue;
255                                         }
256                                         if (linkType == LinkType.POST) {
257                                                 if (line.length() >= (7 + 36)) {
258                                                         String postId = line.substring(7, 43);
259                                                         Optional<Post> post = database.getPost(postId);
260                                                         if (post.isPresent()) {
261                                                                 parts.add(new PostPart(post.get()));
262                                                         } else {
263                                                                 parts.add(new PlainTextPart(line.substring(0, 43)));
264                                                         }
265                                                         line = line.substring(43);
266                                                 } else {
267                                                         parts.add(new PlainTextPart(line));
268                                                         line = "";
269                                                 }
270                                                 continue;
271                                         }
272
273                                         if (linkType.isFreenetLink()) {
274                                                 FreenetURI uri;
275                                                 if (name.indexOf('?') > -1) {
276                                                         name = name.substring(0, name.indexOf('?'));
277                                                 }
278                                                 if (name.endsWith("/")) {
279                                                         name = name.substring(0, name.length() - 1);
280                                                 }
281                                                 try {
282                                                         uri = new FreenetURI(name);
283                                                         name = uri.lastMetaString();
284                                                         if (name == null) {
285                                                                 name = uri.getDocName();
286                                                         }
287                                                         if (name == null) {
288                                                                 name = link.substring(0, Math.min(9, link.length()));
289                                                         }
290                                                         boolean fromPostingSone = ((linkType == LinkType.SSK) || (linkType == LinkType.USK)) && (context != null) && (context.getPostingSone() != null) && link.substring(4, Math.min(link.length(), 47)).equals(context.getPostingSone().getId());
291                                                         parts.add(new FreenetLinkPart(link, name, fromPostingSone));
292                                                 } catch (MalformedURLException mue1) {
293                                                         /* not a valid link, insert as plain text. */
294                                                         parts.add(new PlainTextPart(link));
295                                                 } catch (NullPointerException npe1) {
296                                                         /* FreenetURI sometimes throws these, too. */
297                                                         parts.add(new PlainTextPart(link));
298                                                 } catch (ArrayIndexOutOfBoundsException aioobe1) {
299                                                         /* oh, and these, too. */
300                                                         parts.add(new PlainTextPart(link));
301                                                 }
302                                         } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
303                                                 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
304                                                 int firstSlash = name.indexOf('/');
305                                                 int lastSlash = name.lastIndexOf('/');
306                                                 if ((lastSlash - firstSlash) > 3) {
307                                                         name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
308                                                 }
309                                                 if (name.endsWith("/")) {
310                                                         name = name.substring(0, name.length() - 1);
311                                                 }
312                                                 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
313                                                         name = name.substring(4);
314                                                 }
315                                                 if (name.indexOf('?') > -1) {
316                                                         name = name.substring(0, name.indexOf('?'));
317                                                 }
318                                                 parts.add(new LinkPart(link, name));
319                                         }
320                                         line = line.substring(nextSpace);
321                                 }
322                                 lastLineEmpty = false;
323                         }
324                 } finally {
325                         if (bufferedReader != source) {
326                                 Closer.close(bufferedReader);
327                         }
328                 }
329                 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
330                         Part part = parts.getPart(partIndex);
331                         if (!(part instanceof PlainTextPart) || !"\n".equals(part.getText())) {
332                                 break;
333                         }
334                         parts.removePart(partIndex);
335                 }
336                 return parts;
337         }
338
339 }