Convert template factory into field.
[Sone.git] / src / main / java / net / pterodactylus / sone / web / WebInterface.java
1 /*
2  * FreenetSone - WebInterface.java - Copyright © 2010 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.web;
19
20 import java.io.InputStream;
21 import java.io.InputStreamReader;
22 import java.io.Reader;
23 import java.io.UnsupportedEncodingException;
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.List;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
31
32 import net.pterodactylus.sone.core.Core;
33 import net.pterodactylus.sone.data.Post;
34 import net.pterodactylus.sone.data.Reply;
35 import net.pterodactylus.sone.data.Sone;
36 import net.pterodactylus.sone.freenet.L10nFilter;
37 import net.pterodactylus.sone.freenet.wot.Identity;
38 import net.pterodactylus.sone.main.SonePlugin;
39 import net.pterodactylus.sone.template.CollectionAccessor;
40 import net.pterodactylus.sone.template.CssClassNameFilter;
41 import net.pterodactylus.sone.template.GetPagePlugin;
42 import net.pterodactylus.sone.template.IdentityAccessor;
43 import net.pterodactylus.sone.template.PostAccessor;
44 import net.pterodactylus.sone.template.ReplyAccessor;
45 import net.pterodactylus.sone.template.RequestChangeFilter;
46 import net.pterodactylus.sone.template.SoneAccessor;
47 import net.pterodactylus.sone.template.SubstringFilter;
48 import net.pterodactylus.sone.web.ajax.CreateReplyAjaxPage;
49 import net.pterodactylus.sone.web.ajax.DeletePostAjaxPage;
50 import net.pterodactylus.sone.web.ajax.DeleteReplyAjaxPage;
51 import net.pterodactylus.sone.web.ajax.FollowSoneAjaxPage;
52 import net.pterodactylus.sone.web.ajax.GetLikesAjaxPage;
53 import net.pterodactylus.sone.web.ajax.GetReplyAjaxPage;
54 import net.pterodactylus.sone.web.ajax.GetSoneStatusPage;
55 import net.pterodactylus.sone.web.ajax.GetTranslationPage;
56 import net.pterodactylus.sone.web.ajax.LikeAjaxPage;
57 import net.pterodactylus.sone.web.ajax.UnfollowSoneAjaxPage;
58 import net.pterodactylus.sone.web.ajax.UnlikeAjaxPage;
59 import net.pterodactylus.sone.web.page.PageToadlet;
60 import net.pterodactylus.sone.web.page.PageToadletFactory;
61 import net.pterodactylus.sone.web.page.StaticPage;
62 import net.pterodactylus.util.logging.Logging;
63 import net.pterodactylus.util.template.DateFilter;
64 import net.pterodactylus.util.template.DefaultTemplateFactory;
65 import net.pterodactylus.util.template.MatchFilter;
66 import net.pterodactylus.util.template.PaginationPlugin;
67 import net.pterodactylus.util.template.ReflectionAccessor;
68 import net.pterodactylus.util.template.Template;
69 import net.pterodactylus.util.template.TemplateException;
70 import net.pterodactylus.util.template.TemplateFactory;
71 import net.pterodactylus.util.template.TemplateProvider;
72 import net.pterodactylus.util.template.XmlFilter;
73 import freenet.clients.http.SessionManager;
74 import freenet.clients.http.ToadletContainer;
75 import freenet.l10n.BaseL10n;
76
77 /**
78  * Bundles functionality that a web interface of a Freenet plugin needs, e.g.
79  * references to l10n helpers.
80  *
81  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
82  */
83 public class WebInterface {
84
85         /** The logger. */
86         private static final Logger logger = Logging.getLogger(WebInterface.class);
87
88         /** The Sone plugin. */
89         private final SonePlugin sonePlugin;
90
91         /** The registered toadlets. */
92         private final List<PageToadlet> pageToadlets = new ArrayList<PageToadlet>();
93
94         /** The form password. */
95         private final String formPassword;
96
97         /** The template factory. */
98         private DefaultTemplateFactory templateFactory;
99
100         /**
101          * Creates a new web interface.
102          *
103          * @param sonePlugin
104          *            The Sone plugin
105          */
106         public WebInterface(SonePlugin sonePlugin) {
107                 this.sonePlugin = sonePlugin;
108                 formPassword = sonePlugin.pluginRespirator().getToadletContainer().getFormPassword();
109
110                 templateFactory = new DefaultTemplateFactory();
111                 templateFactory.addAccessor(Object.class, new ReflectionAccessor());
112                 templateFactory.addAccessor(Collection.class, new CollectionAccessor());
113                 templateFactory.addAccessor(Sone.class, new SoneAccessor(getCore()));
114                 templateFactory.addAccessor(Post.class, new PostAccessor(getCore()));
115                 templateFactory.addAccessor(Reply.class, new ReplyAccessor(getCore()));
116                 templateFactory.addAccessor(Identity.class, new IdentityAccessor(getCore()));
117                 templateFactory.addFilter("date", new DateFilter());
118                 templateFactory.addFilter("l10n", new L10nFilter(getL10n()));
119                 templateFactory.addFilter("substring", new SubstringFilter());
120                 templateFactory.addFilter("xml", new XmlFilter());
121                 templateFactory.addFilter("change", new RequestChangeFilter());
122                 templateFactory.addFilter("match", new MatchFilter());
123                 templateFactory.addFilter("css", new CssClassNameFilter());
124                 templateFactory.addPlugin("getpage", new GetPagePlugin());
125                 templateFactory.addPlugin("paginate", new PaginationPlugin());
126                 templateFactory.setTemplateProvider(new ClassPathTemplateProvider(templateFactory));
127                 templateFactory.addTemplateObject("formPassword", formPassword);
128         }
129
130         //
131         // ACCESSORS
132         //
133
134         /**
135          * Returns the Sone core used by the Sone plugin.
136          *
137          * @return The Sone core
138          */
139         public Core getCore() {
140                 return sonePlugin.core();
141         }
142
143         /**
144          * Returns the l10n helper of the node.
145          *
146          * @return The node’s l10n helper
147          */
148         public BaseL10n getL10n() {
149                 return sonePlugin.l10n().getBase();
150         }
151
152         /**
153          * Returns the session manager of the node.
154          *
155          * @return The node’s session manager
156          */
157         public SessionManager getSessionManager() {
158                 try {
159                         return sonePlugin.pluginRespirator().getSessionManager(new URI("/"));
160                 } catch (URISyntaxException use1) {
161                         logger.log(Level.SEVERE, "Could not get Session Manager!", use1);
162                         return null;
163                 }
164         }
165
166         /**
167          * Returns the node’s form password.
168          *
169          * @return The form password
170          */
171         public String getFormPassword() {
172                 return formPassword;
173         }
174
175         //
176         // ACTIONS
177         //
178
179         /**
180          * Starts the web interface and registers all toadlets.
181          */
182         public void start() {
183                 registerToadlets();
184         }
185
186         /**
187          * Stops the web interface and unregisters all toadlets.
188          */
189         public void stop() {
190                 unregisterToadlets();
191         }
192
193         //
194         // PRIVATE METHODS
195         //
196
197         /**
198          * Register all toadlets.
199          */
200         private void registerToadlets() {
201                 Template loginTemplate = templateFactory.createTemplate(createReader("/templates/login.html"));
202                 Template indexTemplate = templateFactory.createTemplate(createReader("/templates/index.html"));
203                 Template knownSonesTemplate = templateFactory.createTemplate(createReader("/templates/knownSones.html"));
204                 Template createSoneTemplate = templateFactory.createTemplate(createReader("/templates/createSone.html"));
205                 Template createPostTemplate = templateFactory.createTemplate(createReader("/templates/createPost.html"));
206                 Template createReplyTemplate = templateFactory.createTemplate(createReader("/templates/createReply.html"));
207                 Template editProfileTemplate = templateFactory.createTemplate(createReader("/templates/editProfile.html"));
208                 Template viewSoneTemplate = templateFactory.createTemplate(createReader("/templates/viewSone.html"));
209                 Template viewPostTemplate = templateFactory.createTemplate(createReader("/templates/viewPost.html"));
210                 Template likePostTemplate = templateFactory.createTemplate(createReader("/templates/like.html"));
211                 Template unlikePostTemplate = templateFactory.createTemplate(createReader("/templates/unlike.html"));
212                 Template deletePostTemplate = templateFactory.createTemplate(createReader("/templates/deletePost.html"));
213                 Template deleteReplyTemplate = templateFactory.createTemplate(createReader("/templates/deleteReply.html"));
214                 Template followSoneTemplate = templateFactory.createTemplate(createReader("/templates/followSone.html"));
215                 Template unfollowSoneTemplate = templateFactory.createTemplate(createReader("/templates/unfollowSone.html"));
216                 Template deleteSoneTemplate = templateFactory.createTemplate(createReader("/templates/deleteSone.html"));
217                 Template noPermissionTemplate = templateFactory.createTemplate(createReader("/templates/noPermission.html"));
218                 Template wotPluginMissingTemplate = templateFactory.createTemplate(createReader("/templates/wotPluginMissing.html"));
219                 Template logoutTemplate = templateFactory.createTemplate(createReader("/templates/logout.html"));
220                 Template optionsTemplate = templateFactory.createTemplate(createReader("/templates/options.html"));
221                 Template aboutTemplate = templateFactory.createTemplate(createReader("/templates/about.html"));
222                 Template replyTemplate = templateFactory.createTemplate(createReader("/templates/include/viewReply.html"));
223
224                 PageToadletFactory pageToadletFactory = new PageToadletFactory(sonePlugin.pluginRespirator().getHLSimpleClient(), "/Sone/");
225                 pageToadlets.add(pageToadletFactory.createPageToadlet(new IndexPage(indexTemplate, this), "Index"));
226                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateSonePage(createSoneTemplate, this), "CreateSone"));
227                 pageToadlets.add(pageToadletFactory.createPageToadlet(new KnownSonesPage(knownSonesTemplate, this), "KnownSones"));
228                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfilePage(editProfileTemplate, this), "EditProfile"));
229                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreatePostPage(createPostTemplate, this)));
230                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyPage(createReplyTemplate, this)));
231                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewSonePage(viewSoneTemplate, this)));
232                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewPostPage(viewPostTemplate, this)));
233                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikePage(likePostTemplate, this)));
234                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikePage(unlikePostTemplate, this)));
235                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostPage(deletePostTemplate, this)));
236                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyPage(deleteReplyTemplate, this)));
237                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSonePage(followSoneTemplate, this)));
238                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSonePage(unfollowSoneTemplate, this)));
239                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteSonePage(deleteSoneTemplate, this), "DeleteSone"));
240                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LoginPage(loginTemplate, this), "Login"));
241                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LogoutPage(logoutTemplate, this), "Logout"));
242                 pageToadlets.add(pageToadletFactory.createPageToadlet(new OptionsPage(optionsTemplate, this), "Options"));
243                 pageToadlets.add(pageToadletFactory.createPageToadlet(new AboutPage(aboutTemplate, this, SonePlugin.VERSION), "About"));
244                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("noPermission.html", noPermissionTemplate, "Page.NoPermission.Title", this)));
245                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("wotPluginMissing.html", wotPluginMissingTemplate, "Page.WotPluginMissing.Title", this)));
246                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("css/", "/static/css/", "text/css")));
247                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("javascript/", "/static/javascript/", "text/javascript")));
248                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("images/", "/static/images/", "image/png")));
249                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetTranslationPage(this)));
250                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetSoneStatusPage(this)));
251                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyAjaxPage(this)));
252                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetReplyAjaxPage(this, replyTemplate)));
253                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostAjaxPage(this)));
254                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyAjaxPage(this)));
255                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSoneAjaxPage(this)));
256                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSoneAjaxPage(this)));
257                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikeAjaxPage(this)));
258                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikeAjaxPage(this)));
259                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetLikesAjaxPage(this)));
260
261                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
262                 toadletContainer.getPageMaker().addNavigationCategory("/Sone/index.html", "Navigation.Menu.Name", "Navigation.Menu.Tooltip", sonePlugin);
263                 for (PageToadlet toadlet : pageToadlets) {
264                         String menuName = toadlet.getMenuName();
265                         if (menuName != null) {
266                                 toadletContainer.register(toadlet, "Navigation.Menu.Name", toadlet.path(), true, "Navigation.Menu.Item." + menuName + ".Name", "Navigation.Menu.Item." + menuName + ".Tooltip", false, toadlet);
267                         } else {
268                                 toadletContainer.register(toadlet, null, toadlet.path(), true, false);
269                         }
270                 }
271         }
272
273         /**
274          * Unregisters all toadlets.
275          */
276         private void unregisterToadlets() {
277                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
278                 for (PageToadlet pageToadlet : pageToadlets) {
279                         toadletContainer.unregister(pageToadlet);
280                 }
281                 toadletContainer.getPageMaker().removeNavigationCategory("Navigation.Menu.Name");
282         }
283
284         /**
285          * Creates a {@link Reader} from the {@link InputStream} for the resource
286          * with the given name.
287          *
288          * @param resourceName
289          *            The name of the resource
290          * @return A {@link Reader} for the resource
291          */
292         private Reader createReader(String resourceName) {
293                 try {
294                         return new InputStreamReader(getClass().getResourceAsStream(resourceName), "UTF-8");
295                 } catch (UnsupportedEncodingException uee1) {
296                         return null;
297                 }
298         }
299
300         /**
301          * Template provider implementation that uses
302          * {@link WebInterface#createReader(String)} to load templates for
303          * inclusion.
304          *
305          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
306          */
307         private class ClassPathTemplateProvider implements TemplateProvider {
308
309                 /** The template factory. */
310                 @SuppressWarnings("hiding")
311                 private final TemplateFactory templateFactory;
312
313                 /**
314                  * Creates a new template provider that locates templates on the
315                  * classpath.
316                  *
317                  * @param templateFactory
318                  *            The template factory to create the templates
319                  */
320                 public ClassPathTemplateProvider(TemplateFactory templateFactory) {
321                         this.templateFactory = templateFactory;
322                 }
323
324                 /**
325                  * {@inheritDoc}
326                  */
327                 @Override
328                 @SuppressWarnings("synthetic-access")
329                 public Template getTemplate(String templateName) {
330                         Reader templateReader = createReader("/templates/" + templateName);
331                         if (templateReader == null) {
332                                 return null;
333                         }
334                         Template template = templateFactory.createTemplate(templateReader);
335                         try {
336                                 template.parse();
337                         } catch (TemplateException te1) {
338                                 logger.log(Level.WARNING, "Could not parse template “" + templateName + "” for inclusion!", te1);
339                         }
340                         return template;
341                 }
342
343         }
344
345 }