2 * Sone - SoneTextParser.java - Copyright © 2010–2013 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 com.google.common.base.Optional.absent;
21 import static com.google.common.base.Optional.of;
22 import static com.google.common.collect.FluentIterable.from;
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;
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;
43 import com.google.common.base.Optional;
44 import freenet.keys.FreenetURI;
47 * {@link Parser} implementation that can recognize Freenet URIs.
49 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
51 public class SoneTextParser implements Parser<SoneTextParserContext> {
54 private static final Logger logger = Logging.getLogger(SoneTextParser.class);
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]");
60 * Enumeration for all recognized link types.
62 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
64 private enum LinkType {
67 KSK("KSK@", true, false),
70 CHK("CHK@", true, false),
72 /** Link is an SSK. */
73 SSK("SSK@", true, false),
76 USK("USK@", true, false),
79 HTTP("http://", false, true),
82 HTTPS("https://", false, true),
84 /** Link is a Sone. */
85 SONE("sone://", false, false),
87 /** Link is a post. */
88 POST("post://", false, false);
90 /** The scheme identifying this link type. */
91 private final String scheme;
92 private final boolean freenetLink;
93 private final boolean internetLink;
96 * Creates a new link type identified by the given scheme.
99 * The scheme of the link type
102 private LinkType(String scheme, boolean freenetLink, boolean internetLink) {
103 this.scheme = scheme;
104 this.freenetLink = freenetLink;
105 this.internetLink = internetLink;
109 * Returns the scheme of this link type.
111 * @return The scheme of this link type
113 public String getScheme() {
117 public boolean isFreenetLink() {
121 public boolean isInternetLink() {
127 private final Database database;
130 * Creates a new freenet link parser.
134 public SoneTextParser(Database database) {
135 this.database = database;
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);
148 boolean lastLineEmpty = true;
150 while ((line = bufferedReader.readLine()) != null) {
151 if (line.trim().length() == 0) {
155 parts.add(new PlainTextPart("\n"));
157 lastLineEmpty = emptyLines == 2;
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.
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));
173 parts.add(new PlainTextPart(line));
178 int next = nextLink.get().getNextIndex();
179 LinkType linkType = nextLink.get().getLinkType();
181 /* cut off “freenet:” from before keys. */
182 if (linkType.isFreenetLink() && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
184 line = line.substring(0, next) + line.substring(next + 8);
187 /* if there is text before the next item, write it out. */
188 if (lineComplete && !lastLineEmpty) {
189 parts.add(new PlainTextPart("\n"));
192 parts.add(new PlainTextPart(line.substring(0, next)));
193 line = line.substring(next);
195 lineComplete = false;
197 int nextSpace = findNextWhitespace(line);
198 String link = line.substring(0, nextSpace);
200 logger.log(Level.FINER, String.format("Found link: %s", link));
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());
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()) {
215 * don’t use create=true above, we don’t want
218 sone = Optional.<Sone>of(new DefaultSone(database, soneId, false, null));
220 parts.add(new SonePart(sone.get()));
221 line = line.substring(50);
223 parts.add(new PlainTextPart(line));
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()));
235 parts.add(new PlainTextPart(line.substring(0, 43)));
237 line = line.substring(43);
239 parts.add(new PlainTextPart(line));
245 if (linkType.isFreenetLink()) {
247 if (name.indexOf('?') > -1) {
248 name = name.substring(0, name.indexOf('?'));
250 if (name.endsWith("/")) {
251 name = name.substring(0, name.length() - 1);
254 uri = new FreenetURI(name);
255 name = uri.lastMetaString();
257 name = uri.getDocName();
260 name = link.substring(0, Math.min(9, link.length()));
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));
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);
281 if (name.endsWith("/")) {
282 name = name.substring(0, name.length() - 1);
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);
287 if (name.indexOf('?') > -1) {
288 name = name.substring(0, name.indexOf('?'));
290 parts.add(new LinkPart(link, name));
292 line = line.substring(nextSpace);
294 lastLineEmpty = false;
297 if (bufferedReader != source) {
298 Closer.close(bufferedReader);
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())) {
306 parts.removePart(partIndex);
311 private int findNextWhitespace(String line) {
312 Matcher matcher = whitespacePattern.matcher(line);
313 return matcher.find(0) ? matcher.start() : line.length();
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());
321 linkTypeIndexes.put(linkType, index);
324 if (linkTypeIndexes.isEmpty()) {
327 Entry<LinkType, Integer> smallestEntry = from(linkTypeIndexes.entrySet()).toSortedList(locateSmallestIndex()).get(0);
328 return of(new NextLink(smallestEntry.getValue(), smallestEntry.getKey()));
331 private Comparator<Entry<LinkType, Integer>> locateSmallestIndex() {
332 return new Comparator<Entry<LinkType, Integer>>() {
334 public int compare(Entry<LinkType, Integer> leftEntry, Entry<LinkType, Integer> rightEntry) {
335 return leftEntry.getValue() - rightEntry.getValue();
341 * Container for position and type of the next link in a line.
343 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
345 private static class NextLink {
347 private final int nextIndex;
348 private final LinkType linkType;
350 private NextLink(int nextIndex, LinkType linkType) {
351 this.nextIndex = nextIndex;
352 this.linkType = linkType;
355 private int getNextIndex() {
359 private LinkType getLinkType() {