Parse album:// links
[Sone.git] / src / main / java / net / pterodactylus / sone / text / SoneTextParser.java
1 /*
2  * Sone - SoneTextParser.java - Copyright © 2010–2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.text;
19
20 import static java.util.logging.Logger.getLogger;
21
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;
30
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;
39
40 import com.google.common.base.Optional;
41
42 import freenet.keys.FreenetURI;
43
44 /**
45  * {@link Parser} implementation that can recognize Freenet URIs.
46  *
47  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
48  */
49 public class SoneTextParser implements Parser<SoneTextParserContext> {
50
51         /** The logger. */
52         private static final Logger logger = getLogger(SoneTextParser.class.getName());
53
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]");
56
57         /**
58          * Enumeration for all recognized link types.
59          *
60          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
61          */
62         private enum LinkType {
63
64                 KSK("KSK@", true),
65                 CHK("CHK@", true),
66                 SSK("SSK@", true),
67                 USK("USK@", true),
68                 HTTP("http://", false),
69                 HTTPS("https://", false),
70                 SONE("sone://", false),
71                 POST("post://", false),
72                 ALBUM("album://", false);
73
74                 private final String scheme;
75                 private final boolean freenetLink;
76
77                 LinkType(String scheme, boolean freenetLink) {
78                         this.scheme = scheme;
79                         this.freenetLink = freenetLink;
80                 }
81
82                 /**
83                  * Returns the scheme of this link type.
84                  *
85                  * @return The scheme of this link type
86                  */
87                 public String getScheme() {
88                         return scheme;
89                 }
90
91                 public boolean isFreenetLink() {
92                         return freenetLink;
93                 }
94
95         }
96
97         private final SoneProvider soneProvider;
98         private final PostProvider postProvider;
99         private final AlbumProvider albumProvider;
100
101         public SoneTextParser(SoneProvider soneProvider, PostProvider postProvider, AlbumProvider albumProvider) {
102                 this.soneProvider = soneProvider;
103                 this.postProvider = postProvider;
104                 this.albumProvider = albumProvider;
105         }
106
107         //
108         // PART METHODS
109         //
110
111         /**
112          * {@inheritDoc}
113          */
114         @Override
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);
118                 try {
119                         String line;
120                         boolean lastLineEmpty = true;
121                         int emptyLines = 0;
122                         while ((line = bufferedReader.readLine()) != null) {
123                                 if (line.trim().length() == 0) {
124                                         if (lastLineEmpty) {
125                                                 continue;
126                                         }
127                                         parts.add(new PlainTextPart("\n"));
128                                         ++emptyLines;
129                                         lastLineEmpty = emptyLines == 2;
130                                         continue;
131                                 }
132                                 emptyLines = 0;
133                                 /*
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.
137                                  */
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));
144                                                 } else {
145                                                         parts.add(new PlainTextPart(line));
146                                                 }
147                                                 break;
148                                         }
149                                         LinkType linkType = nextLink.get().getLinkType();
150                                         int next = nextLink.get().getPosition();
151
152                                         /* cut off “freenet:” from before keys. */
153                                         if (linkType.isFreenetLink() && (next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
154                                                 next -= 8;
155                                                 line = line.substring(0, next) + line.substring(next + 8);
156                                         }
157
158                                         /* if there is text before the next item, write it out. */
159                                         if (lineComplete && !lastLineEmpty) {
160                                                 parts.add(new PlainTextPart("\n"));
161                                         }
162                                         if (next > 0) {
163                                                 parts.add(new PlainTextPart(line.substring(0, next)));
164                                                 line = line.substring(next);
165                                         }
166                                         lineComplete = false;
167
168                                         Matcher matcher = whitespacePattern.matcher(line);
169                                         int nextSpace = matcher.find(0) ? matcher.start() : line.length();
170                                         String link = line.substring(0, nextSpace);
171                                         String name = link;
172                                         logger.log(Level.FINER, String.format("Found link: %s", link));
173
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());
178                                                 continue;
179                                         }
180
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()) {
186                                                                 /*
187                                                                  * don’t use create=true above, we don’t want
188                                                                  * the empty shell.
189                                                                  */
190                                                                 sone = Optional.<Sone>of(new IdOnlySone(soneId));
191                                                         }
192                                                         parts.add(new SonePart(sone.get()));
193                                                         line = line.substring(50);
194                                                 } else {
195                                                         parts.add(new PlainTextPart(line));
196                                                         line = "";
197                                                 }
198                                                 continue;
199                                         }
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())));
204                                                 } else {
205                                                         parts.add(new PlainTextPart(link));
206                                                 }
207                                                 line = line.substring(link.length());
208                                                 continue;
209                                         }
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()));
214                                                 } else {
215                                                         parts.add(new PlainTextPart(link));
216                                                 }
217                                                 line = line.substring(link.length());
218                                                 continue;
219                                         }
220
221                                         if (linkType.isFreenetLink()) {
222                                                 FreenetURI uri;
223                                                 if (name.indexOf('?') > -1) {
224                                                         name = name.substring(0, name.indexOf('?'));
225                                                 }
226                                                 if (name.endsWith("/")) {
227                                                         name = name.substring(0, name.length() - 1);
228                                                 }
229                                                 try {
230                                                         uri = new FreenetURI(name);
231                                                         name = uri.lastMetaString();
232                                                         if (name == null) {
233                                                                 name = uri.getDocName();
234                                                         }
235                                                         if (name == null) {
236                                                                 name = link.substring(0, Math.min(9, link.length()));
237                                                         }
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));
249                                                 }
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);
256                                                 }
257                                                 if (name.endsWith("/")) {
258                                                         name = name.substring(0, name.length() - 1);
259                                                 }
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);
262                                                 }
263                                                 if (name.indexOf('?') > -1) {
264                                                         name = name.substring(0, name.indexOf('?'));
265                                                 }
266                                                 parts.add(new LinkPart(link, name));
267                                         }
268                                         line = line.substring(nextSpace);
269                                 }
270                                 lastLineEmpty = false;
271                         }
272                 } finally {
273                         if (bufferedReader != source) {
274                                 Closer.close(bufferedReader);
275                         }
276                 }
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())) {
280                                 break;
281                         }
282                         parts.removePart(partIndex);
283                 }
284                 return parts;
285         }
286
287         private static class NextLink {
288
289                 private final int position;
290                 private final LinkType linkType;
291
292                 private NextLink(int position, LinkType linkType) {
293                         this.position = position;
294                         this.linkType = linkType;
295                 }
296
297                 public int getPosition() {
298                         return position;
299                 }
300
301                 public LinkType getLinkType() {
302                         return linkType;
303                 }
304
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;
314                                         }
315                                 }
316                         }
317                         return earliestLinkPosition < Integer.MAX_VALUE ?
318                                         Optional.of(new NextLink(earliestLinkPosition, linkType)) : Optional.<NextLink>absent();
319                 }
320
321         }
322
323 }