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