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 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.Album;
32 import net.pterodactylus.sone.data.Post;
33 import net.pterodactylus.sone.data.Sone;
34 import net.pterodactylus.sone.data.impl.IdOnlySone;
35 import net.pterodactylus.sone.database.AlbumProvider;
36 import net.pterodactylus.sone.database.PostProvider;
37 import net.pterodactylus.sone.database.SoneProvider;
38 import net.pterodactylus.util.io.Closer;
40 import com.google.common.base.Optional;
42 import freenet.keys.FreenetURI;
45 * {@link Parser} implementation that can recognize Freenet URIs.
47 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49 public class SoneTextParser implements Parser<SoneTextParserContext> {
52 private static final Logger logger = getLogger(SoneTextParser.class.getName());
54 /** Pattern to detect whitespace. */
55 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]");
58 * Enumeration for all recognized link types.
60 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
62 private enum LinkType {
68 HTTP("http://", false),
69 HTTPS("https://", false),
70 SONE("sone://", false),
71 POST("post://", false),
72 ALBUM("album://", 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 private final SoneProvider soneProvider;
98 private final PostProvider postProvider;
99 private final AlbumProvider albumProvider;
101 public SoneTextParser(SoneProvider soneProvider, PostProvider postProvider, AlbumProvider albumProvider) {
102 this.soneProvider = soneProvider;
103 this.postProvider = postProvider;
104 this.albumProvider = albumProvider;
115 public Iterable<Part> parse(SoneTextParserContext context, Reader source) throws IOException {
116 PartContainer parts = new PartContainer();
117 BufferedReader bufferedReader = (source instanceof BufferedReader) ? (BufferedReader) source : new BufferedReader(source);
120 boolean lastLineEmpty = true;
122 while ((line = bufferedReader.readLine()) != null) {
123 if (line.trim().length() == 0) {
127 parts.add(new PlainTextPart("\n"));
129 lastLineEmpty = emptyLines == 2;
134 * lineComplete tracks whether the block you are parsing is the
135 * first block of the line. this is important because sometimes
136 * you have to add an additional line break.
138 boolean lineComplete = true;
139 while (line.length() > 0) {
140 Optional<NextLink> nextLink = NextLink.findNextLink(line);
141 if (!nextLink.isPresent()) {
142 if (lineComplete && !lastLineEmpty) {
143 parts.add(new PlainTextPart("\n" + line));
145 parts.add(new PlainTextPart(line));
149 LinkType linkType = nextLink.get().getLinkType();
150 int next = nextLink.get().getPosition();
152 /* cut off “freenet:” from before keys. */
153 if (linkType.isFreenetLink() && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
155 line = line.substring(0, next) + line.substring(next + 8);
158 /* if there is text before the next item, write it out. */
159 if (lineComplete && !lastLineEmpty) {
160 parts.add(new PlainTextPart("\n"));
163 parts.add(new PlainTextPart(line.substring(0, next)));
164 line = line.substring(next);
166 lineComplete = false;
168 Matcher matcher = whitespacePattern.matcher(line);
169 int nextSpace = matcher.find(0) ? matcher.start() : line.length();
170 String link = line.substring(0, nextSpace);
172 logger.log(Level.FINER, String.format("Found link: %s", link));
174 /* if there is no text after the scheme, it’s not a link! */
175 if (link.equals(linkType.getScheme())) {
176 parts.add(new PlainTextPart(linkType.getScheme()));
177 line = line.substring(linkType.getScheme().length());
181 if (linkType == LinkType.SONE) {
182 if (line.length() >= (7 + 43)) {
183 String soneId = line.substring(7, 50);
184 Optional<Sone> sone = soneProvider.getSone(soneId);
185 if (!sone.isPresent()) {
187 * don’t use create=true above, we don’t want
190 sone = Optional.<Sone>of(new IdOnlySone(soneId));
192 parts.add(new SonePart(sone.get()));
193 line = line.substring(50);
195 parts.add(new PlainTextPart(line));
200 if (linkType == LinkType.POST) {
201 Optional<Post> post = postProvider.getPost(link.substring(7));
202 if (post.isPresent()) {
203 parts.add(new PostPart(post.get(), link.substring(7).equals(post.get().getInternalId())));
205 parts.add(new PlainTextPart(link));
207 line = line.substring(link.length());
210 if (linkType == LinkType.ALBUM) {
211 Optional<Album> album = albumProvider.getAlbum(link.substring(linkType.getScheme().length()));
212 if (album.isPresent()) {
213 parts.add(new AlbumPart(album.get()));
215 parts.add(new PlainTextPart(link));
217 line = line.substring(link.length());
221 if (linkType.isFreenetLink()) {
223 if (name.indexOf('?') > -1) {
224 name = name.substring(0, name.indexOf('?'));
226 if (name.endsWith("/")) {
227 name = name.substring(0, name.length() - 1);
230 uri = new FreenetURI(name);
231 name = uri.lastMetaString();
233 name = uri.getDocName();
236 name = link.substring(0, Math.min(9, link.length()));
238 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());
239 parts.add(new FreenetLinkPart(link, name, fromPostingSone));
240 } catch (MalformedURLException mue1) {
241 /* not a valid link, insert as plain text. */
242 parts.add(new PlainTextPart(link));
243 } catch (NullPointerException npe1) {
244 /* FreenetURI sometimes throws these, too. */
245 parts.add(new PlainTextPart(link));
246 } catch (ArrayIndexOutOfBoundsException aioobe1) {
247 /* oh, and these, too. */
248 parts.add(new PlainTextPart(link));
250 } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
251 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
252 int firstSlash = name.indexOf('/');
253 int lastSlash = name.lastIndexOf('/');
254 if ((lastSlash - firstSlash) > 3) {
255 name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
257 if (name.endsWith("/")) {
258 name = name.substring(0, name.length() - 1);
260 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
261 name = name.substring(4);
263 if (name.indexOf('?') > -1) {
264 name = name.substring(0, name.indexOf('?'));
266 parts.add(new LinkPart(link, name));
268 line = line.substring(nextSpace);
270 lastLineEmpty = false;
273 if (bufferedReader != source) {
274 Closer.close(bufferedReader);
277 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
278 Part part = parts.getPart(partIndex);
279 if (!(part instanceof PlainTextPart) || !"\n".equals(part.getText())) {
282 parts.removePart(partIndex);
287 private static class NextLink {
289 private final int position;
290 private final LinkType linkType;
292 private NextLink(int position, LinkType linkType) {
293 this.position = position;
294 this.linkType = linkType;
297 public int getPosition() {
301 public LinkType getLinkType() {
305 public static Optional<NextLink> findNextLink(String line) {
306 int earliestLinkPosition = Integer.MAX_VALUE;
307 LinkType linkType = null;
308 for (LinkType possibleLinkType : LinkType.values()) {
309 int nextLinkPosition = line.indexOf(possibleLinkType.getScheme());
310 if (nextLinkPosition > -1) {
311 if (nextLinkPosition < earliestLinkPosition) {
312 earliestLinkPosition = nextLinkPosition;
313 linkType = possibleLinkType;
317 return earliestLinkPosition < Integer.MAX_VALUE ?
318 Optional.of(new NextLink(earliestLinkPosition, linkType)) : Optional.<NextLink>absent();