2 * Sone - SoneTextParser.java - Copyright © 2010–2016 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.text;
20 import static java.util.logging.Logger.getLogger;
22 import java.io.BufferedReader;
23 import java.io.IOException;
24 import java.io.StringReader;
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;
31 import javax.annotation.Nonnull;
32 import javax.annotation.Nullable;
34 import net.pterodactylus.sone.data.Post;
35 import net.pterodactylus.sone.data.Sone;
36 import net.pterodactylus.sone.data.impl.IdOnlySone;
37 import net.pterodactylus.sone.database.PostProvider;
38 import net.pterodactylus.sone.database.SoneProvider;
39 import net.pterodactylus.util.io.Closer;
41 import com.google.common.base.Optional;
43 import freenet.keys.FreenetURI;
46 * {@link Parser} implementation that can recognize Freenet URIs.
48 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50 public class SoneTextParser implements Parser<SoneTextParserContext> {
53 private static final Logger logger = getLogger(SoneTextParser.class.getName());
55 /** Pattern to detect whitespace. */
56 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]");
59 * Enumeration for all recognized link types.
61 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
63 private enum LinkType {
69 HTTP("http://", false),
70 HTTPS("https://", false),
71 SONE("sone://", false),
72 POST("post://", false);
74 private final String scheme;
75 private final boolean freenetLink;
77 LinkType(String scheme, boolean freenetLink) {
79 this.freenetLink = freenetLink;
83 * Returns the scheme of this link type.
85 * @return The scheme of this link type
87 public String getScheme() {
91 public boolean isFreenetLink() {
97 /** The Sone provider. */
98 private final SoneProvider soneProvider;
100 /** The post provider. */
101 private final PostProvider postProvider;
104 * Creates a new freenet link parser.
106 * @param soneProvider
108 * @param postProvider
111 public SoneTextParser(SoneProvider soneProvider, PostProvider postProvider) {
112 this.soneProvider = soneProvider;
113 this.postProvider = postProvider;
125 public Iterable<Part> parse(@Nonnull String source, @Nullable SoneTextParserContext context) {
126 PartContainer parts = new PartContainer();
127 BufferedReader bufferedReader = new BufferedReader(new StringReader(source));
130 boolean lastLineEmpty = true;
132 while ((line = bufferedReader.readLine()) != null) {
133 if (line.trim().length() == 0) {
137 parts.add(new PlainTextPart("\n"));
139 lastLineEmpty = emptyLines == 2;
144 * lineComplete tracks whether the block you are parsing is the
145 * first block of the line. this is important because sometimes
146 * you have to add an additional line break.
148 boolean lineComplete = true;
149 while (line.length() > 0) {
150 Optional<NextLink> nextLink = NextLink.findNextLink(line);
151 if (!nextLink.isPresent()) {
152 if (lineComplete && !lastLineEmpty) {
153 parts.add(new PlainTextPart("\n" + line));
155 parts.add(new PlainTextPart(line));
159 LinkType linkType = nextLink.get().getLinkType();
160 int next = nextLink.get().getPosition();
162 /* cut off “freenet:” from before keys. */
163 if (linkType.isFreenetLink() && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
165 line = line.substring(0, next) + line.substring(next + 8);
168 /* if there is text before the next item, write it out. */
169 if (lineComplete && !lastLineEmpty) {
170 parts.add(new PlainTextPart("\n"));
173 parts.add(new PlainTextPart(line.substring(0, next)));
174 line = line.substring(next);
176 lineComplete = false;
178 Matcher matcher = whitespacePattern.matcher(line);
179 int nextSpace = matcher.find(0) ? matcher.start() : line.length();
180 String link = line.substring(0, nextSpace);
182 logger.log(Level.FINER, String.format("Found link: %s", link));
184 /* if there is no text after the scheme, it’s not a link! */
185 if (link.equals(linkType.getScheme())) {
186 parts.add(new PlainTextPart(linkType.getScheme()));
187 line = line.substring(linkType.getScheme().length());
191 if (linkType == LinkType.SONE) {
192 if (line.length() >= (7 + 43)) {
193 String soneId = line.substring(7, 50);
194 Optional<Sone> sone = soneProvider.getSone(soneId);
195 if (!sone.isPresent()) {
197 * don’t use create=true above, we don’t want
200 sone = Optional.<Sone>of(new IdOnlySone(soneId));
202 parts.add(new SonePart(sone.get()));
203 line = line.substring(50);
205 parts.add(new PlainTextPart(line));
210 if (linkType == LinkType.POST) {
211 if (line.length() >= (7 + 36)) {
212 String postId = line.substring(7, 43);
213 Optional<Post> post = postProvider.getPost(postId);
214 if (post.isPresent()) {
215 parts.add(new PostPart(post.get()));
217 parts.add(new PlainTextPart(line.substring(0, 43)));
219 line = line.substring(43);
221 parts.add(new PlainTextPart(line));
227 if (linkType.isFreenetLink()) {
229 if (name.indexOf('?') > -1) {
230 name = name.substring(0, name.indexOf('?'));
232 if (name.endsWith("/")) {
233 name = name.substring(0, name.length() - 1);
236 uri = new FreenetURI(name);
237 name = uri.lastMetaString();
239 name = uri.getDocName();
242 name = link.substring(0, Math.min(9, link.length()));
244 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());
245 parts.add(new FreenetLinkPart(link, name, fromPostingSone));
246 } catch (MalformedURLException mue1) {
247 /* not a valid link, insert as plain text. */
248 parts.add(new PlainTextPart(link));
249 } catch (NullPointerException npe1) {
250 /* FreenetURI sometimes throws these, too. */
251 parts.add(new PlainTextPart(link));
252 } catch (ArrayIndexOutOfBoundsException aioobe1) {
253 /* oh, and these, too. */
254 parts.add(new PlainTextPart(link));
256 } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
257 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
258 int firstSlash = name.indexOf('/');
259 int lastSlash = name.lastIndexOf('/');
260 if ((lastSlash - firstSlash) > 3) {
261 name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
263 if (name.endsWith("/")) {
264 name = name.substring(0, name.length() - 1);
266 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
267 name = name.substring(4);
269 if (name.indexOf('?') > -1) {
270 name = name.substring(0, name.indexOf('?'));
272 parts.add(new LinkPart(link, name));
274 line = line.substring(nextSpace);
276 lastLineEmpty = false;
278 } catch (IOException ioe1) {
279 // a buffered reader around a string reader should never throw.
280 throw new RuntimeException(ioe1);
282 Closer.close(bufferedReader);
284 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
285 Part part = parts.getPart(partIndex);
286 if (!(part instanceof PlainTextPart) || !"\n".equals(part.getText())) {
289 parts.removePart(partIndex);
294 private static class NextLink {
296 private final int position;
297 private final LinkType linkType;
299 private NextLink(int position, LinkType linkType) {
300 this.position = position;
301 this.linkType = linkType;
304 public int getPosition() {
308 public LinkType getLinkType() {
312 public static Optional<NextLink> findNextLink(String line) {
313 int earliestLinkPosition = Integer.MAX_VALUE;
314 LinkType linkType = null;
315 for (LinkType possibleLinkType : LinkType.values()) {
316 int nextLinkPosition = line.indexOf(possibleLinkType.getScheme());
317 if (nextLinkPosition > -1) {
318 if (nextLinkPosition < earliestLinkPosition) {
319 earliestLinkPosition = nextLinkPosition;
320 linkType = possibleLinkType;
324 return earliestLinkPosition < Integer.MAX_VALUE ?
325 Optional.of(new NextLink(earliestLinkPosition, linkType)) : Optional.<NextLink>absent();