Add ellipsis when cutting off a text.
[Sone.git] / src / main / java / net / pterodactylus / sone / template / ParserFilter.java
1 /*
2  * Sone - ParserFilter.java - Copyright © 2011 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.template;
19
20 import java.io.IOException;
21 import java.io.StringReader;
22 import java.io.StringWriter;
23 import java.io.Writer;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Map;
27
28 import net.pterodactylus.sone.core.Core;
29 import net.pterodactylus.sone.data.Sone;
30 import net.pterodactylus.sone.text.FreenetLinkPart;
31 import net.pterodactylus.sone.text.LinkPart;
32 import net.pterodactylus.sone.text.Part;
33 import net.pterodactylus.sone.text.PlainTextPart;
34 import net.pterodactylus.sone.text.PostPart;
35 import net.pterodactylus.sone.text.SonePart;
36 import net.pterodactylus.sone.text.SoneTextParser;
37 import net.pterodactylus.sone.text.SoneTextParserContext;
38 import net.pterodactylus.sone.web.page.Page.Request;
39 import net.pterodactylus.util.template.Filter;
40 import net.pterodactylus.util.template.Template;
41 import net.pterodactylus.util.template.TemplateContext;
42 import net.pterodactylus.util.template.TemplateContextFactory;
43 import net.pterodactylus.util.template.TemplateParser;
44
45 /**
46  * Filter that filters a given text through a {@link SoneTextParser}.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 public class ParserFilter implements Filter {
51
52         /** The core. */
53         private final Core core;
54
55         /** The link parser. */
56         private final SoneTextParser soneTextParser;
57
58         /** The template context factory. */
59         private final TemplateContextFactory templateContextFactory;
60
61         /** The template for {@link PlainTextPart}s. */
62         private final Template plainTextTemplate = TemplateParser.parse(new StringReader("<%text|html>"));
63
64         /** The template for {@link FreenetLinkPart}s. */
65         private final Template linkTemplate = TemplateParser.parse(new StringReader("<a class=\"<%cssClass|html>\" href=\"<%link|html>\" title=\"<%title|html>\"><%text|html></a>"));
66
67         /**
68          * Creates a new filter that runs its input through a {@link SoneTextParser}
69          * .
70          *
71          * @param core
72          *            The core
73          * @param templateContextFactory
74          *            The context factory for rendering the parts
75          * @param soneTextParser
76          *            The Sone text parser
77          */
78         public ParserFilter(Core core, TemplateContextFactory templateContextFactory, SoneTextParser soneTextParser) {
79                 this.core = core;
80                 this.templateContextFactory = templateContextFactory;
81                 this.soneTextParser = soneTextParser;
82         }
83
84         /**
85          * {@inheritDoc}
86          */
87         @Override
88         public Object format(TemplateContext templateContext, Object data, Map<String, String> parameters) {
89                 String text = String.valueOf(data);
90                 int length = -1;
91                 try {
92                         length = Integer.parseInt(parameters.get("length"));
93                 } catch (NumberFormatException nfe1) {
94                         /* ignore. */
95                 }
96                 String soneKey = parameters.get("sone");
97                 if (soneKey == null) {
98                         soneKey = "sone";
99                 }
100                 Sone sone = (Sone) templateContext.get(soneKey);
101                 if (sone == null) {
102                         sone = core.getSone(soneKey, false);
103                 }
104                 Request request = (Request) templateContext.get("request");
105                 SoneTextParserContext context = new SoneTextParserContext(request, sone);
106                 StringWriter parsedTextWriter = new StringWriter();
107                 try {
108                         Iterable<Part> parts = soneTextParser.parse(context, new StringReader(text));
109                         if (length > -1) {
110                                 List<Part> shortenedParts = new ArrayList<Part>();
111                                 for (Part part : parts) {
112                                         if (part instanceof PlainTextPart) {
113                                                 String longText = ((PlainTextPart) part).getText();
114                                                 if (length >= longText.length()) {
115                                                         shortenedParts.add(part);
116                                                 } else {
117                                                         shortenedParts.add(new PlainTextPart(longText.substring(0, length) + "…"));
118                                                 }
119                                                 length -= longText.length();
120                                         } else if (part instanceof LinkPart) {
121                                                 shortenedParts.add(part);
122                                                 length -= ((LinkPart) part).getText().length();
123                                         } else {
124                                                 shortenedParts.add(part);
125                                         }
126                                         if (length <= 0) {
127                                                 break;
128                                         }
129                                 }
130                                 parts = shortenedParts;
131                         }
132                         render(parsedTextWriter, parts);
133                 } catch (IOException ioe1) {
134                         /* no exceptions in a StringReader or StringWriter, ignore. */
135                 }
136                 return parsedTextWriter.toString();
137         }
138
139         //
140         // PRIVATE METHODS
141         //
142
143         /**
144          * Renders the given parts.
145          *
146          * @param writer
147          *            The writer to render the parts to
148          * @param parts
149          *            The parts to render
150          */
151         private void render(Writer writer, Iterable<Part> parts) {
152                 for (Part part : parts) {
153                         render(writer, part);
154                 }
155         }
156
157         /**
158          * Renders the given part.
159          *
160          * @param writer
161          *            The writer to render the part to
162          * @param part
163          *            The part to render
164          */
165         @SuppressWarnings("unchecked")
166         private void render(Writer writer, Part part) {
167                 if (part instanceof PlainTextPart) {
168                         render(writer, (PlainTextPart) part);
169                 } else if (part instanceof FreenetLinkPart) {
170                         render(writer, (FreenetLinkPart) part);
171                 } else if (part instanceof LinkPart) {
172                         render(writer, (LinkPart) part);
173                 } else if (part instanceof SonePart) {
174                         render(writer, (SonePart) part);
175                 } else if (part instanceof PostPart) {
176                         render(writer, (PostPart) part);
177                 } else if (part instanceof Iterable<?>) {
178                         render(writer, (Iterable<Part>) part);
179                 }
180         }
181
182         /**
183          * Renders the given plain-text part.
184          *
185          * @param writer
186          *            The writer to render the part to
187          * @param plainTextPart
188          *            The part to render
189          */
190         private void render(Writer writer, PlainTextPart plainTextPart) {
191                 TemplateContext templateContext = templateContextFactory.createTemplateContext();
192                 templateContext.set("text", plainTextPart.getText());
193                 plainTextTemplate.render(templateContext, writer);
194         }
195
196         /**
197          * Renders the given freenet link part.
198          *
199          * @param writer
200          *            The writer to render the part to
201          * @param freenetLinkPart
202          *            The part to render
203          */
204         private void render(Writer writer, FreenetLinkPart freenetLinkPart) {
205                 renderLink(writer, "/" + freenetLinkPart.getLink(), freenetLinkPart.getText(), freenetLinkPart.getTitle(), freenetLinkPart.isTrusted() ? "freenet-trusted" : "freenet");
206         }
207
208         /**
209          * Renders the given link part.
210          *
211          * @param writer
212          *            The writer to render the part to
213          * @param linkPart
214          *            The part to render
215          */
216         private void render(Writer writer, LinkPart linkPart) {
217                 renderLink(writer, "/?_CHECKED_HTTP_=" + linkPart.getLink(), linkPart.getText(), linkPart.getTitle(), "internet");
218         }
219
220         /**
221          * Renders the given Sone part.
222          *
223          * @param writer
224          *            The writer to render the part to
225          * @param sonePart
226          *            The part to render
227          */
228         private void render(Writer writer, SonePart sonePart) {
229                 renderLink(writer, "viewSone.html?sone=" + sonePart.getSone().getId(), SoneAccessor.getNiceName(sonePart.getSone()), SoneAccessor.getNiceName(sonePart.getSone()), "in-sone");
230         }
231
232         /**
233          * Renders the given post part.
234          *
235          * @param writer
236          *            The writer to render the part to
237          * @param postPart
238          *            The part to render
239          */
240         private void render(Writer writer, PostPart postPart) {
241                 renderLink(writer, "viewPost.html?post=" + postPart.getPost().getId(), getExcerpt(postPart.getPost().getText(), 20), SoneAccessor.getNiceName(postPart.getPost().getSone()), "in-sone");
242         }
243
244         /**
245          * Renders the given link.
246          *
247          * @param writer
248          *            The writer to render the link to
249          * @param link
250          *            The link to render
251          * @param text
252          *            The text of the link
253          * @param title
254          *            The title of the link
255          * @param cssClass
256          *            The CSS class of the link
257          */
258         private void renderLink(Writer writer, String link, String text, String title, String cssClass) {
259                 TemplateContext templateContext = templateContextFactory.createTemplateContext();
260                 templateContext.set("cssClass", cssClass);
261                 templateContext.set("link", link);
262                 templateContext.set("text", text);
263                 templateContext.set("title", title);
264                 linkTemplate.render(templateContext, writer);
265         }
266
267         //
268         // STATIC METHODS
269         //
270
271         /**
272          * Returns up to {@code length} characters from the given text, appending
273          * “…” if the text is longer.
274          *
275          * @param text
276          *            The text to get an excerpt from
277          * @param length
278          *            The maximum length of the excerpt (without the ellipsis)
279          * @return The excerpt of the text
280          */
281         private static String getExcerpt(String text, int length) {
282                 if (text.length() > length) {
283                         return text.substring(0, length) + "…";
284                 }
285                 return text;
286         }
287
288 }