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 java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.Reader;
23 import java.net.MalformedURLException;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
29 import net.pterodactylus.sone.data.Post;
30 import net.pterodactylus.sone.data.Sone;
31 import net.pterodactylus.sone.database.PostProvider;
32 import net.pterodactylus.sone.database.SoneProvider;
33 import net.pterodactylus.util.io.Closer;
34 import net.pterodactylus.util.logging.Logging;
36 import com.google.common.base.Optional;
38 import freenet.keys.FreenetURI;
41 * {@link Parser} implementation that can recognize Freenet URIs.
43 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
45 public class SoneTextParser implements Parser<SoneTextParserContext> {
48 private static final Logger logger = Logging.getLogger(SoneTextParser.class);
50 /** Pattern to detect whitespace. */
51 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 * Enumeration for all recognized link types.
56 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
58 private enum LinkType {
66 /** Link is an SSK. */
78 /** Link is a Sone. */
81 /** Link is a post. */
84 /** The scheme identifying this link type. */
85 private final String scheme;
88 * Creates a new link type identified by the given scheme.
91 * The scheme of the link type
93 private LinkType(String scheme) {
98 * Returns the scheme of this link type.
100 * @return The scheme of this link type
102 public String getScheme() {
108 /** The Sone provider. */
109 private final SoneProvider soneProvider;
111 /** The post provider. */
112 private final PostProvider postProvider;
115 * Creates a new freenet link parser.
117 * @param soneProvider
119 * @param postProvider
122 public SoneTextParser(SoneProvider soneProvider, PostProvider postProvider) {
123 this.soneProvider = soneProvider;
124 this.postProvider = postProvider;
135 public Iterable<Part> parse(SoneTextParserContext context, Reader source) throws IOException {
136 PartContainer parts = new PartContainer();
137 BufferedReader bufferedReader = (source instanceof BufferedReader) ? (BufferedReader) source : new BufferedReader(source);
140 boolean lastLineEmpty = true;
142 while ((line = bufferedReader.readLine()) != null) {
143 if (line.trim().length() == 0) {
147 parts.add(new PlainTextPart("\n"));
149 lastLineEmpty = emptyLines == 2;
154 * lineComplete tracks whether the block you are parsing is the
155 * first block of the line. this is important because sometimes
156 * you have to add an additional line break.
158 boolean lineComplete = true;
159 while (line.length() > 0) {
160 int nextKsk = line.indexOf("KSK@");
161 int nextChk = line.indexOf("CHK@");
162 int nextSsk = line.indexOf("SSK@");
163 int nextUsk = line.indexOf("USK@");
164 int nextHttp = line.indexOf("http://");
165 int nextHttps = line.indexOf("https://");
166 int nextSone = line.indexOf("sone://");
167 int nextPost = line.indexOf("post://");
168 if ((nextKsk == -1) && (nextChk == -1) && (nextSsk == -1) && (nextUsk == -1) && (nextHttp == -1) && (nextHttps == -1) && (nextSone == -1) && (nextPost == -1)) {
169 if (lineComplete && !lastLineEmpty) {
170 parts.add(new PlainTextPart("\n" + line));
172 parts.add(new PlainTextPart(line));
176 int next = Integer.MAX_VALUE;
177 LinkType linkType = null;
178 if ((nextKsk > -1) && (nextKsk < next)) {
180 linkType = LinkType.KSK;
182 if ((nextChk > -1) && (nextChk < next)) {
184 linkType = LinkType.CHK;
186 if ((nextSsk > -1) && (nextSsk < next)) {
188 linkType = LinkType.SSK;
190 if ((nextUsk > -1) && (nextUsk < next)) {
192 linkType = LinkType.USK;
194 if ((nextHttp > -1) && (nextHttp < next)) {
196 linkType = LinkType.HTTP;
198 if ((nextHttps > -1) && (nextHttps < next)) {
200 linkType = LinkType.HTTPS;
202 if ((nextSone > -1) && (nextSone < next)) {
204 linkType = LinkType.SONE;
206 if ((nextPost > -1) && (nextPost < next)) {
208 linkType = LinkType.POST;
211 /* cut off “freenet:” from before keys. */
212 if (((linkType == LinkType.KSK) || (linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
214 line = line.substring(0, next) + line.substring(next + 8);
217 /* if there is text before the next item, write it out. */
218 if (lineComplete && !lastLineEmpty) {
219 parts.add(new PlainTextPart("\n"));
222 parts.add(new PlainTextPart(line.substring(0, next)));
223 line = line.substring(next);
226 lineComplete = false;
228 Matcher matcher = whitespacePattern.matcher(line);
229 int nextSpace = matcher.find(0) ? matcher.start() : line.length();
230 String link = line.substring(0, nextSpace);
232 logger.log(Level.FINER, String.format("Found link: %s", link));
233 logger.log(Level.FINEST, String.format("CHK: %d, SSK: %d, USK: %d", nextChk, nextSsk, nextUsk));
235 /* if there is no text after the scheme, it’s not a link! */
236 if (link.equals(linkType.getScheme())) {
237 parts.add(new PlainTextPart(linkType.getScheme()));
238 line = line.substring(linkType.getScheme().length());
242 if (linkType == LinkType.SONE) {
243 if (line.length() >= (7 + 43)) {
244 String soneId = line.substring(7, 50);
245 Optional<Sone> sone = soneProvider.getSone(soneId);
246 if (!sone.isPresent()) {
248 * don’t use create=true above, we don’t want
251 sone = Optional.fromNullable(new Sone(soneId, false));
253 parts.add(new SonePart(sone.get()));
254 line = line.substring(50);
256 parts.add(new PlainTextPart(line));
261 if (linkType == LinkType.POST) {
262 if (line.length() >= (7 + 36)) {
263 String postId = line.substring(7, 43);
264 Optional<Post> post = postProvider.getPost(postId);
265 if (post.isPresent()) {
266 parts.add(new PostPart(post.get()));
268 parts.add(new PlainTextPart(line.substring(0, 43)));
270 line = line.substring(43);
272 parts.add(new PlainTextPart(line));
278 if ((linkType == LinkType.KSK) || (linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) {
280 if (name.indexOf('?') > -1) {
281 name = name.substring(0, name.indexOf('?'));
283 if (name.endsWith("/")) {
284 name = name.substring(0, name.length() - 1);
287 uri = new FreenetURI(name);
288 name = uri.lastMetaString();
290 name = uri.getDocName();
293 name = link.substring(0, Math.min(9, link.length()));
295 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());
296 parts.add(new FreenetLinkPart(link, name, fromPostingSone));
297 } catch (MalformedURLException mue1) {
298 /* not a valid link, insert as plain text. */
299 parts.add(new PlainTextPart(link));
300 } catch (NullPointerException npe1) {
301 /* FreenetURI sometimes throws these, too. */
302 parts.add(new PlainTextPart(link));
303 } catch (ArrayIndexOutOfBoundsException aioobe1) {
304 /* oh, and these, too. */
305 parts.add(new PlainTextPart(link));
307 } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) {
308 name = link.substring(linkType == LinkType.HTTP ? 7 : 8);
309 int firstSlash = name.indexOf('/');
310 int lastSlash = name.lastIndexOf('/');
311 if ((lastSlash - firstSlash) > 3) {
312 name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash);
314 if (name.endsWith("/")) {
315 name = name.substring(0, name.length() - 1);
317 if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) {
318 name = name.substring(4);
320 if (name.indexOf('?') > -1) {
321 name = name.substring(0, name.indexOf('?'));
323 parts.add(new LinkPart(link, name));
325 line = line.substring(nextSpace);
327 lastLineEmpty = false;
330 if (bufferedReader != source) {
331 Closer.close(bufferedReader);
334 for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) {
335 Part part = parts.getPart(partIndex);
336 if (!(part instanceof PlainTextPart) || !"\n".equals(((PlainTextPart) part).getText())) {
339 parts.removePart(partIndex);