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