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