Store in post part whether the internal ID was used to create this part
[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                                         Optional<NextLink> nextLink = NextLink.findNextLink(line);
147                                         if (!nextLink.isPresent()) {
148                                                 if (lineComplete && !lastLineEmpty) {
149                                                         parts.add(new PlainTextPart("\n" + line));
150                                                 } else {
151                                                         parts.add(new PlainTextPart(line));
152                                                 }
153                                                 break;
154                                         }
155                                         LinkType linkType = nextLink.get().getLinkType();
156                                         int next = nextLink.get().getPosition();
157
158                                         /* cut off “freenet:” from before keys. */
159                                         if (linkType.isFreenetLink() && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
160                                                 next -= 8;
161                                                 line = line.substring(0, next) + line.substring(next + 8);
162                                         }
163
164                                         /* if there is text before the next item, write it out. */
165                                         if (lineComplete && !lastLineEmpty) {
166                                                 parts.add(new PlainTextPart("\n"));
167                                         }
168                                         if (next > 0) {
169                                                 parts.add(new PlainTextPart(line.substring(0, next)));
170                                                 line = line.substring(next);
171                                         }
172                                         lineComplete = false;
173
174                                         Matcher matcher = whitespacePattern.matcher(line);
175                                         int nextSpace = matcher.find(0) ? matcher.start() : line.length();
176                                         String link = line.substring(0, nextSpace);
177                                         String name = link;
178                                         logger.log(Level.FINER, String.format("Found link: %s", link));
179
180                                         /* if there is no text after the scheme, it’s not a link! */
181                                         if (link.equals(linkType.getScheme())) {
182                                                 parts.add(new PlainTextPart(linkType.getScheme()));
183                                                 line = line.substring(linkType.getScheme().length());
184                                                 continue;
185                                         }
186
187                                         if (linkType == LinkType.SONE) {
188                                                 if (line.length() >= (7 + 43)) {
189                                                         String soneId = line.substring(7, 50);
190                                                         Optional<Sone> sone = soneProvider.getSone(soneId);
191                                                         if (!sone.isPresent()) {
192                                                                 /*
193                                                                  * don’t use create=true above, we don’t want
194                                                                  * the empty shell.
195                                                                  */
196                                                                 sone = Optional.<Sone>of(new IdOnlySone(soneId));
197                                                         }
198                                                         parts.add(new SonePart(sone.get()));
199                                                         line = line.substring(50);
200                                                 } else {
201                                                         parts.add(new PlainTextPart(line));
202                                                         line = "";
203                                                 }
204                                                 continue;
205                                         }
206                                         if (linkType == LinkType.POST) {
207                                                 Optional<Post> post = postProvider.getPost(link.substring(7));
208                                                 if (post.isPresent()) {
209                                                         parts.add(new PostPart(post.get(), link.substring(7).equals(post.get().getInternalId())));
210                                                 } else {
211                                                         parts.add(new PlainTextPart(link));
212                                                 }
213                                                 line = line.substring(link.length());
214                                                 continue;
215                                         }
216
217                                         if (linkType.isFreenetLink()) {
218                                                 FreenetURI uri;
219                                                 if (name.indexOf('?') > -1) {
220                                                         name = name.substring(0, name.indexOf('?'));
221                                                 }
222                                                 if (name.endsWith("/")) {
223                                                         name = name.substring(0, name.length() - 1);
224                                                 }
225                                                 try {
226                                                         uri = new FreenetURI(name);
227                                                         name = uri.lastMetaString();
228                                                         if (name == null) {
229                                                                 name = uri.getDocName();
230                                                         }
231                                                         if (name == null) {
232                                                                 name = link.substring(0, Math.min(9, link.length()));
233                                                         }
234                                                         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());
235                                                         parts.add(new FreenetLinkPart(link, name, fromPostingSone));
236                                                 } catch (MalformedURLException mue1) {
237                                                         /* not a valid link, insert as plain text. */
238                                                         parts.add(new PlainTextPart(link));
239                                                 } catch (NullPointerException npe1) {
240                                                         /* FreenetURI sometimes throws these, too. */
241                                                         parts.add(new PlainTextPart(link));
242                                                 } catch (ArrayIndexOutOfBoundsException aioobe1) {
243                                                         /* oh, and these, too. */
244                                                         parts.add(new PlainTextPart(link));
245                                                 }
246                                         } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
247                                                 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
248                                                 int firstSlash = name.indexOf('/');
249                                                 int lastSlash = name.lastIndexOf('/');
250                                                 if ((lastSlash - firstSlash) > 3) {
251                                                         name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
252                                                 }
253                                                 if (name.endsWith("/")) {
254                                                         name = name.substring(0, name.length() - 1);
255                                                 }
256                                                 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
257                                                         name = name.substring(4);
258                                                 }
259                                                 if (name.indexOf('?') > -1) {
260                                                         name = name.substring(0, name.indexOf('?'));
261                                                 }
262                                                 parts.add(new LinkPart(link, name));
263                                         }
264                                         line = line.substring(nextSpace);
265                                 }
266                                 lastLineEmpty = false;
267                         }
268                 } finally {
269                         if (bufferedReader != source) {
270                                 Closer.close(bufferedReader);
271                         }
272                 }
273                 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
274                         Part part = parts.getPart(partIndex);
275                         if (!(part instanceof PlainTextPart) || !"\n".equals(part.getText())) {
276                                 break;
277                         }
278                         parts.removePart(partIndex);
279                 }
280                 return parts;
281         }
282
283         private static class NextLink {
284
285                 private final int position;
286                 private final LinkType linkType;
287
288                 private NextLink(int position, LinkType linkType) {
289                         this.position = position;
290                         this.linkType = linkType;
291                 }
292
293                 public int getPosition() {
294                         return position;
295                 }
296
297                 public LinkType getLinkType() {
298                         return linkType;
299                 }
300
301                 public static Optional<NextLink> findNextLink(String line) {
302                         int earliestLinkPosition = Integer.MAX_VALUE;
303                         LinkType linkType = null;
304                         for (LinkType possibleLinkType : LinkType.values()) {
305                                 int nextLinkPosition = line.indexOf(possibleLinkType.getScheme());
306                                 if (nextLinkPosition > -1) {
307                                         if (nextLinkPosition < earliestLinkPosition) {
308                                                 earliestLinkPosition = nextLinkPosition;
309                                                 linkType = possibleLinkType;
310                                         }
311                                 }
312                         }
313                         return earliestLinkPosition < Integer.MAX_VALUE ?
314                                         Optional.of(new NextLink(earliestLinkPosition, linkType)) : Optional.<NextLink>absent();
315                 }
316
317         }
318
319 }