Update years in copyright line
[Sone.git] / src / main / java / net / pterodactylus / sone / text / SoneTextParser.java
1 /*
2  * Sone - SoneTextParser.java - Copyright © 2010–2015 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                                                 if (line.length() >= (7 + 36)) {
208                                                         String postId = line.substring(7, 43);
209                                                         Optional<Post> post = postProvider.getPost(postId);
210                                                         if (post.isPresent()) {
211                                                                 parts.add(new PostPart(post.get()));
212                                                         } else {
213                                                                 parts.add(new PlainTextPart(line.substring(0, 43)));
214                                                         }
215                                                         line = line.substring(43);
216                                                 } else {
217                                                         parts.add(new PlainTextPart(line));
218                                                         line = "";
219                                                 }
220                                                 continue;
221                                         }
222
223                                         if (linkType.isFreenetLink()) {
224                                                 FreenetURI uri;
225                                                 if (name.indexOf('?') > -1) {
226                                                         name = name.substring(0, name.indexOf('?'));
227                                                 }
228                                                 if (name.endsWith("/")) {
229                                                         name = name.substring(0, name.length() - 1);
230                                                 }
231                                                 try {
232                                                         uri = new FreenetURI(name);
233                                                         name = uri.lastMetaString();
234                                                         if (name == null) {
235                                                                 name = uri.getDocName();
236                                                         }
237                                                         if (name == null) {
238                                                                 name = link.substring(0, Math.min(9, link.length()));
239                                                         }
240                                                         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());
241                                                         parts.add(new FreenetLinkPart(link, name, fromPostingSone));
242                                                 } catch (MalformedURLException mue1) {
243                                                         /* not a valid link, insert as plain text. */
244                                                         parts.add(new PlainTextPart(link));
245                                                 } catch (NullPointerException npe1) {
246                                                         /* FreenetURI sometimes throws these, too. */
247                                                         parts.add(new PlainTextPart(link));
248                                                 } catch (ArrayIndexOutOfBoundsException aioobe1) {
249                                                         /* oh, and these, too. */
250                                                         parts.add(new PlainTextPart(link));
251                                                 }
252                                         } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
253                                                 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
254                                                 int firstSlash = name.indexOf('/');
255                                                 int lastSlash = name.lastIndexOf('/');
256                                                 if ((lastSlash - firstSlash) > 3) {
257                                                         name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
258                                                 }
259                                                 if (name.endsWith("/")) {
260                                                         name = name.substring(0, name.length() - 1);
261                                                 }
262                                                 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
263                                                         name = name.substring(4);
264                                                 }
265                                                 if (name.indexOf('?') > -1) {
266                                                         name = name.substring(0, name.indexOf('?'));
267                                                 }
268                                                 parts.add(new LinkPart(link, name));
269                                         }
270                                         line = line.substring(nextSpace);
271                                 }
272                                 lastLineEmpty = false;
273                         }
274                 } finally {
275                         if (bufferedReader != source) {
276                                 Closer.close(bufferedReader);
277                         }
278                 }
279                 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
280                         Part part = parts.getPart(partIndex);
281                         if (!(part instanceof PlainTextPart) || !"\n".equals(part.getText())) {
282                                 break;
283                         }
284                         parts.removePart(partIndex);
285                 }
286                 return parts;
287         }
288
289         private static class NextLink {
290
291                 private final int position;
292                 private final LinkType linkType;
293
294                 private NextLink(int position, LinkType linkType) {
295                         this.position = position;
296                         this.linkType = linkType;
297                 }
298
299                 public int getPosition() {
300                         return position;
301                 }
302
303                 public LinkType getLinkType() {
304                         return linkType;
305                 }
306
307                 public static Optional<NextLink> findNextLink(String line) {
308                         int earliestLinkPosition = Integer.MAX_VALUE;
309                         LinkType linkType = null;
310                         for (LinkType possibleLinkType : LinkType.values()) {
311                                 int nextLinkPosition = line.indexOf(possibleLinkType.getScheme());
312                                 if (nextLinkPosition > -1) {
313                                         if (nextLinkPosition < earliestLinkPosition) {
314                                                 earliestLinkPosition = nextLinkPosition;
315                                                 linkType = possibleLinkType;
316                                         }
317                                 }
318                         }
319                         return earliestLinkPosition < Integer.MAX_VALUE ?
320                                         Optional.of(new NextLink(earliestLinkPosition, linkType)) : Optional.<NextLink>absent();
321                 }
322
323         }
324
325 }