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