Allow null contexts.
[Sone.git] / src / main / java / net / pterodactylus / sone / text / SoneTextParser.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.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.core.Core;
30 import net.pterodactylus.sone.data.Post;
31 import net.pterodactylus.sone.data.Sone;
32 import net.pterodactylus.util.logging.Logging;
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 SoneTextParser implements Parser<SoneTextParserContext> {
41
42         /** The logger. */
43         private static final Logger logger = Logging.getLogger(SoneTextParser.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                 /** Link is a Sone. */
74                 SONE,
75
76                 /** Link is a post. */
77                 POST,
78
79         }
80
81         /** The core. */
82         private final Core core;
83
84         /**
85          * Creates a new freenet link parser.
86          *
87          * @param core
88          *            The core
89          */
90         public SoneTextParser(Core core) {
91                 this.core = core;
92         }
93
94         //
95         // PART METHODS
96         //
97
98         /**
99          * {@inheritDoc}
100          */
101         @Override
102         public Iterable<Part> parse(SoneTextParserContext context, Reader source) throws IOException {
103                 PartContainer parts = new PartContainer();
104                 BufferedReader bufferedReader = (source instanceof BufferedReader) ? (BufferedReader) source : new BufferedReader(source);
105                 String line;
106                 boolean lastLineEmpty = true;
107                 int emptyLines = 0;
108                 while ((line = bufferedReader.readLine()) != null) {
109                         if (line.trim().length() == 0) {
110                                 if (lastLineEmpty) {
111                                         continue;
112                                 }
113                                 parts.add(new PlainTextPart("\n"));
114                                 ++emptyLines;
115                                 lastLineEmpty = emptyLines == 2;
116                                 continue;
117                         }
118                         emptyLines = 0;
119                         boolean lineComplete = true;
120                         while (line.length() > 0) {
121                                 int nextKsk = line.indexOf("KSK@");
122                                 int nextChk = line.indexOf("CHK@");
123                                 int nextSsk = line.indexOf("SSK@");
124                                 int nextUsk = line.indexOf("USK@");
125                                 int nextHttp = line.indexOf("http://");
126                                 int nextHttps = line.indexOf("https://");
127                                 int nextSone = line.indexOf("sone://");
128                                 int nextPost = line.indexOf("post://");
129                                 if ((nextKsk == -1) && (nextChk == -1) && (nextSsk == -1) && (nextUsk == -1) && (nextHttp == -1) && (nextHttps == -1) && (nextSone == -1) && (nextPost == -1)) {
130                                         if (lineComplete && !lastLineEmpty) {
131                                                 parts.add(new PlainTextPart("\n" + line));
132                                         } else {
133                                                 parts.add(new PlainTextPart(line));
134                                         }
135                                         break;
136                                 }
137                                 int next = Integer.MAX_VALUE;
138                                 LinkType linkType = null;
139                                 if ((nextKsk > -1) && (nextKsk < next)) {
140                                         next = nextKsk;
141                                         linkType = LinkType.KSK;
142                                 }
143                                 if ((nextChk > -1) && (nextChk < next)) {
144                                         next = nextChk;
145                                         linkType = LinkType.CHK;
146                                 }
147                                 if ((nextSsk > -1) && (nextSsk < next)) {
148                                         next = nextSsk;
149                                         linkType = LinkType.SSK;
150                                 }
151                                 if ((nextUsk > -1) && (nextUsk < next)) {
152                                         next = nextUsk;
153                                         linkType = LinkType.USK;
154                                 }
155                                 if ((nextHttp > -1) && (nextHttp < next)) {
156                                         next = nextHttp;
157                                         linkType = LinkType.HTTP;
158                                 }
159                                 if ((nextHttps > -1) && (nextHttps < next)) {
160                                         next = nextHttps;
161                                         linkType = LinkType.HTTPS;
162                                 }
163                                 if ((nextSone > -1) && (nextSone < next)) {
164                                         next = nextSone;
165                                         linkType = LinkType.SONE;
166                                 }
167                                 if ((nextPost > -1) && (nextPost < next)) {
168                                         next = nextPost;
169                                         linkType = LinkType.POST;
170                                 }
171                                 if (linkType == LinkType.SONE) {
172                                         if (next > 0) {
173                                                 parts.add(new PlainTextPart(line.substring(0, next)));
174                                         }
175                                         if (line.length() >= (next + 7 + 43)) {
176                                                 String soneId = line.substring(next + 7, next + 50);
177                                                 Sone sone = core.getSone(soneId, false);
178                                                 if (sone != null) {
179                                                         parts.add(new SonePart(sone));
180                                                 } else {
181                                                         parts.add(new PlainTextPart(line.substring(next, next + 50)));
182                                                 }
183                                                 line = line.substring(next + 50);
184                                         } else {
185                                                 parts.add(new PlainTextPart(line.substring(next)));
186                                                 line = "";
187                                         }
188                                         continue;
189                                 }
190                                 if (linkType == LinkType.POST) {
191                                         if (next > 0) {
192                                                 parts.add(new PlainTextPart(line.substring(0, next)));
193                                         }
194                                         if (line.length() >= (next + 7 + 36)) {
195                                                 String postId = line.substring(next + 7, next + 43);
196                                                 Post post = core.getPost(postId, false);
197                                                 if ((post != null) && (post.getSone() != null)) {
198                                                         String postText = post.getText();
199                                                         postText = postText.substring(0, Math.min(postText.length(), 20)) + "…";
200                                                         parts.add(new PostPart(post));
201                                                 } else {
202                                                         parts.add(new PlainTextPart(line.substring(next, next + 43)));
203                                                 }
204                                                 line = line.substring(next + 43);
205                                         } else {
206                                                 parts.add(new PlainTextPart(line.substring(next)));
207                                                 line = "";
208                                         }
209                                         continue;
210                                 }
211                                 if ((next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
212                                         next -= 8;
213                                         line = line.substring(0, next) + line.substring(next + 8);
214                                 }
215                                 Matcher matcher = whitespacePattern.matcher(line);
216                                 int nextSpace = matcher.find(next) ? matcher.start() : line.length();
217                                 if (nextSpace > (next + 4)) {
218                                         if (!lastLineEmpty && lineComplete) {
219                                                 parts.add(new PlainTextPart("\n" + line.substring(0, next)));
220                                         } else {
221                                                 parts.add(new PlainTextPart(line.substring(0, next)));
222                                         }
223                                         String link = line.substring(next, nextSpace);
224                                         String name = link;
225                                         logger.log(Level.FINER, "Found link: %s", link);
226                                         logger.log(Level.FINEST, "Next: %d, CHK: %d, SSK: %d, USK: %d", new Object[] { next, nextChk, nextSsk, nextUsk });
227
228                                         if ((linkType == LinkType.KSK) || (linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) {
229                                                 FreenetURI uri;
230                                                 if (name.indexOf('?') > -1) {
231                                                         name = name.substring(0, name.indexOf('?'));
232                                                 }
233                                                 if (name.endsWith("/")) {
234                                                         name = name.substring(0, name.length() - 1);
235                                                 }
236                                                 try {
237                                                         uri = new FreenetURI(name);
238                                                         name = uri.lastMetaString();
239                                                         if (name == null) {
240                                                                 name = uri.getDocName();
241                                                         }
242                                                         if (name == null) {
243                                                                 name = link.substring(0, Math.min(9, link.length()));
244                                                         }
245                                                         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());
246                                                         parts.add(new FreenetLinkPart(link, name, fromPostingSone));
247                                                 } catch (MalformedURLException mue1) {
248                                                         /* not a valid link, insert as plain text. */
249                                                         parts.add(new PlainTextPart(link));
250                                                 } catch (NullPointerException npe1) {
251                                                         /* FreenetURI sometimes throws these, too. */
252                                                         parts.add(new PlainTextPart(link));
253                                                 } catch (ArrayIndexOutOfBoundsException aioobe1) {
254                                                         /* oh, and these, too. */
255                                                         parts.add(new PlainTextPart(link));
256                                                 }
257                                         } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
258                                                 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
259                                                 int firstSlash = name.indexOf('/');
260                                                 int lastSlash = name.lastIndexOf('/');
261                                                 if ((lastSlash - firstSlash) > 3) {
262                                                         name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
263                                                 }
264                                                 if (name.endsWith("/")) {
265                                                         name = name.substring(0, name.length() - 1);
266                                                 }
267                                                 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
268                                                         name = name.substring(4);
269                                                 }
270                                                 if (name.indexOf('?') > -1) {
271                                                         name = name.substring(0, name.indexOf('?'));
272                                                 }
273                                                 parts.add(new LinkPart(link, name));
274                                         }
275                                         line = line.substring(nextSpace);
276                                 } else {
277                                         if (!lastLineEmpty && lineComplete) {
278                                                 parts.add(new PlainTextPart("\n" + line.substring(0, next + 4)));
279                                         } else {
280                                                 parts.add(new PlainTextPart(line.substring(0, next + 4)));
281                                         }
282                                         line = line.substring(next + 4);
283                                 }
284                                 lineComplete = false;
285                         }
286                         lastLineEmpty = false;
287                 }
288                 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
289                         Part part = parts.getPart(partIndex);
290                         if (!(part instanceof PlainTextPart) || !"\n".equals(((PlainTextPart) part).getText())) {
291                                 break;
292                         }
293                         parts.removePart(partIndex);
294                 }
295                 return parts;
296         }
297
298 }