2 * Sone - SoneTextParser.java - Copyright Ā© 2010ā2015 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.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;
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;
38 import com.google.common.base.Optional;
40 import freenet.keys.FreenetURI;
43 * {@link Parser} implementation that can recognize Freenet URIs.
45 * @author <a href="mailto:bombe@pterodactylus.net">David āBombeā Roden</a>
47 public class SoneTextParser implements Parser<SoneTextParserContext> {
50 private static final Logger logger = getLogger(SoneTextParser.class.getName());
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]");
56 * Enumeration for all recognized link types.
58 * @author <a href="mailto:bombe@pterodactylus.net">David āBombeā Roden</a>
60 private enum LinkType {
66 HTTP("http://", false),
67 HTTPS("https://", false),
68 SONE("sone://", false),
69 POST("post://", false);
71 private final String scheme;
72 private final boolean freenetLink;
74 LinkType(String scheme, boolean freenetLink) {
76 this.freenetLink = freenetLink;
80 * Returns the scheme of this link type.
82 * @return The scheme of this link type
84 public String getScheme() {
88 public boolean isFreenetLink() {
94 /** The Sone provider. */
95 private final SoneProvider soneProvider;
97 /** The post provider. */
98 private final PostProvider postProvider;
101 * Creates a new freenet link parser.
103 * @param soneProvider
105 * @param postProvider
108 public SoneTextParser(SoneProvider soneProvider, PostProvider postProvider) {
109 this.soneProvider = soneProvider;
110 this.postProvider = postProvider;
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);
126 boolean lastLineEmpty = true;
128 while ((line = bufferedReader.readLine()) != null) {
129 if (line.trim().length() == 0) {
133 parts.add(new PlainTextPart("\n"));
135 lastLineEmpty = emptyLines == 2;
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.
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));
151 parts.add(new PlainTextPart(line));
155 LinkType linkType = nextLink.get().getLinkType();
156 int next = nextLink.get().getPosition();
158 /* cut off āfreenet:ā from before keys. */
159 if (linkType.isFreenetLink() && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
161 line = line.substring(0, next) + line.substring(next + 8);
164 /* if there is text before the next item, write it out. */
165 if (lineComplete && !lastLineEmpty) {
166 parts.add(new PlainTextPart("\n"));
169 parts.add(new PlainTextPart(line.substring(0, next)));
170 line = line.substring(next);
172 lineComplete = false;
174 Matcher matcher = whitespacePattern.matcher(line);
175 int nextSpace = matcher.find(0) ? matcher.start() : line.length();
176 String link = line.substring(0, nextSpace);
178 logger.log(Level.FINER, String.format("Found link: %s", link));
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());
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()) {
193 * donāt use create=true above, we donāt want
196 sone = Optional.<Sone>of(new IdOnlySone(soneId));
198 parts.add(new SonePart(sone.get()));
199 line = line.substring(50);
201 parts.add(new PlainTextPart(line));
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()));
213 parts.add(new PlainTextPart(line.substring(0, 43)));
215 line = line.substring(43);
217 parts.add(new PlainTextPart(line));
223 if (linkType.isFreenetLink()) {
225 if (name.indexOf('?') > -1) {
226 name = name.substring(0, name.indexOf('?'));
228 if (name.endsWith("/")) {
229 name = name.substring(0, name.length() - 1);
232 uri = new FreenetURI(name);
233 name = uri.lastMetaString();
235 name = uri.getDocName();
238 name = link.substring(0, Math.min(9, link.length()));
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));
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);
259 if (name.endsWith("/")) {
260 name = name.substring(0, name.length() - 1);
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);
265 if (name.indexOf('?') > -1) {
266 name = name.substring(0, name.indexOf('?'));
268 parts.add(new LinkPart(link, name));
270 line = line.substring(nextSpace);
272 lastLineEmpty = false;
275 if (bufferedReader != source) {
276 Closer.close(bufferedReader);
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())) {
284 parts.removePart(partIndex);
289 private static class NextLink {
291 private final int position;
292 private final LinkType linkType;
294 private NextLink(int position, LinkType linkType) {
295 this.position = position;
296 this.linkType = linkType;
299 public int getPosition() {
303 public LinkType getLinkType() {
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;
319 return earliestLinkPosition < Integer.MAX_VALUE ?
320 Optional.of(new NextLink(earliestLinkPosition, linkType)) : Optional.<NextLink>absent();