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