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