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