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