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