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