427570d38a6767a59b3dc7f1172d3a004f3d2368
[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.List;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
30
31 import net.pterodactylus.sone.core.Core;
32 import net.pterodactylus.sone.data.Post;
33 import net.pterodactylus.sone.data.Sone;
34 import net.pterodactylus.sone.freenet.L10nFilter;
35 import net.pterodactylus.sone.main.SonePlugin;
36 import net.pterodactylus.sone.template.PostAccessor;
37 import net.pterodactylus.sone.template.RequestChangeFilter;
38 import net.pterodactylus.sone.template.SoneAccessor;
39 import net.pterodactylus.sone.template.SubstringFilter;
40 import net.pterodactylus.sone.web.ajax.GetSoneStatusPage;
41 import net.pterodactylus.sone.web.ajax.GetTranslationPage;
42 import net.pterodactylus.sone.web.page.PageToadlet;
43 import net.pterodactylus.sone.web.page.PageToadletFactory;
44 import net.pterodactylus.sone.web.page.StaticPage;
45 import net.pterodactylus.util.logging.Logging;
46 import net.pterodactylus.util.service.AbstractService;
47 import net.pterodactylus.util.template.DateFilter;
48 import net.pterodactylus.util.template.DefaultTemplateFactory;
49 import net.pterodactylus.util.template.ReflectionAccessor;
50 import net.pterodactylus.util.template.Template;
51 import net.pterodactylus.util.template.TemplateException;
52 import net.pterodactylus.util.template.TemplateFactory;
53 import net.pterodactylus.util.template.TemplateProvider;
54 import net.pterodactylus.util.template.XmlFilter;
55 import freenet.clients.http.SessionManager;
56 import freenet.clients.http.ToadletContainer;
57 import freenet.l10n.BaseL10n;
58
59 /**
60  * Bundles functionality that a web interface of a Freenet plugin needs, e.g.
61  * references to l10n helpers.
62  *
63  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
64  */
65 public class WebInterface extends AbstractService {
66
67         /** The logger. */
68         private static final Logger logger = Logging.getLogger(WebInterface.class);
69
70         /** The Sone plugin. */
71         private final SonePlugin sonePlugin;
72
73         /** The registered toadlets. */
74         private final List<PageToadlet> pageToadlets = new ArrayList<PageToadlet>();
75
76         /**
77          * Creates a new web interface.
78          *
79          * @param sonePlugin
80          *            The Sone plugin
81          */
82         public WebInterface(SonePlugin sonePlugin) {
83                 super("Sone Web Interface", false);
84                 this.sonePlugin = sonePlugin;
85         }
86
87         //
88         // ACCESSORS
89         //
90
91         /**
92          * Returns the Sone core used by the Sone plugin.
93          *
94          * @return The Sone core
95          */
96         public Core core() {
97                 return sonePlugin.core();
98         }
99
100         /**
101          * Returns the l10n helper of the node.
102          *
103          * @return The node’s l10n helper
104          */
105         public BaseL10n l10n() {
106                 return sonePlugin.l10n().getBase();
107         }
108
109         /**
110          * Returns the session manager of the node.
111          *
112          * @return The node’s session manager
113          */
114         public SessionManager sessionManager() {
115                 try {
116                         return sonePlugin.pluginRespirator().getSessionManager(new URI("/"));
117                 } catch (URISyntaxException use1) {
118                         logger.log(Level.SEVERE, "Could not get Session Manager!", use1);
119                         return null;
120                 }
121         }
122
123         //
124         // SERVICE METHODS
125         //
126
127         /**
128          * {@inheritDoc}
129          */
130         @Override
131         protected void serviceStart() {
132                 registerToadlets();
133         }
134
135         /**
136          * {@inheritDoc}
137          */
138         @Override
139         protected void serviceStop() {
140                 unregisterToadlets();
141         }
142
143         //
144         // PRIVATE METHODS
145         //
146
147         /**
148          * Register all toadlets.
149          */
150         private void registerToadlets() {
151                 DefaultTemplateFactory templateFactory = new DefaultTemplateFactory();
152                 templateFactory.addAccessor(Object.class, new ReflectionAccessor());
153                 templateFactory.addAccessor(Sone.class, new SoneAccessor(core()));
154                 templateFactory.addAccessor(Post.class, new PostAccessor(core()));
155                 templateFactory.addFilter("date", new DateFilter());
156                 templateFactory.addFilter("l10n", new L10nFilter(l10n()));
157                 templateFactory.addFilter("substring", new SubstringFilter());
158                 templateFactory.addFilter("xml", new XmlFilter());
159                 templateFactory.addFilter("change", new RequestChangeFilter());
160                 templateFactory.setTemplateProvider(new ClassPathTemplateProvider(templateFactory));
161                 templateFactory.addTemplateObject("formPassword", sonePlugin.pluginRespirator().getToadletContainer().getFormPassword());
162
163                 Template loginTemplate = templateFactory.createTemplate(createReader("/templates/login.html"));
164                 Template indexTemplate = templateFactory.createTemplate(createReader("/templates/index.html"));
165                 Template addSoneTemplate = templateFactory.createTemplate(createReader("/templates/addSone.html"));
166                 Template loadSoneTemplate = templateFactory.createTemplate(createReader("/templates/loadSone.html"));
167                 Template knownSonesTemplate = templateFactory.createTemplate(createReader("/templates/knownSones.html"));
168                 Template createSoneTemplate = templateFactory.createTemplate(createReader("/templates/createSone.html"));
169                 Template createPostTemplate = templateFactory.createTemplate(createReader("/templates/createPost.html"));
170                 Template createReplyTemplate = templateFactory.createTemplate(createReader("/templates/createReply.html"));
171                 Template editProfileTemplate = templateFactory.createTemplate(createReader("/templates/editProfile.html"));
172                 Template backupProfileTemplate = templateFactory.createTemplate(createReader("/templates/backup.xml"));
173                 Template viewSoneTemplate = templateFactory.createTemplate(createReader("/templates/viewSone.html"));
174                 Template blockSoneTemplate = templateFactory.createTemplate(createReader("/templates/blockSone.html"));
175                 Template unblockSoneTemplate = templateFactory.createTemplate(createReader("/templates/unblockSone.html"));
176                 Template viewPostTemplate = templateFactory.createTemplate(createReader("/templates/viewPost.html"));
177                 Template deletePostTemplate = templateFactory.createTemplate(createReader("/templates/deletePost.html"));
178                 Template deleteReplyTemplate = templateFactory.createTemplate(createReader("/templates/deleteReply.html"));
179                 Template followSoneTemplate = templateFactory.createTemplate(createReader("/templates/followSone.html"));
180                 Template unfollowSoneTemplate = templateFactory.createTemplate(createReader("/templates/unfollowSone.html"));
181                 Template deleteSoneTemplate = templateFactory.createTemplate(createReader("/templates/deleteSone.html"));
182                 Template noPermissionTemplate = templateFactory.createTemplate(createReader("/templates/noPermission.html"));
183                 Template logoutTemplate = templateFactory.createTemplate(createReader("/templates/logout.html"));
184
185                 PageToadletFactory pageToadletFactory = new PageToadletFactory(sonePlugin.pluginRespirator().getHLSimpleClient(), "/Sone/");
186                 pageToadlets.add(pageToadletFactory.createPageToadlet(new IndexPage(indexTemplate, this), "Index"));
187                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateSonePage(createSoneTemplate, this), "CreateSone"));
188                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LoadSonePage(loadSoneTemplate, this)));
189                 pageToadlets.add(pageToadletFactory.createPageToadlet(new AddSonePage(addSoneTemplate, this)));
190                 pageToadlets.add(pageToadletFactory.createPageToadlet(new KnownSonesPage(knownSonesTemplate, this), "KnownSones"));
191                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfilePage(editProfileTemplate, this), "EditProfile"));
192                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BackupProfilePage(backupProfileTemplate, this)));
193                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreatePostPage(createPostTemplate, this)));
194                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyPage(createReplyTemplate, this)));
195                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewSonePage(viewSoneTemplate, this)));
196                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BlockSonePage(blockSoneTemplate, this)));
197                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnblockSonePage(unblockSoneTemplate, this)));
198                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewPostPage(viewPostTemplate, this)));
199                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostPage(deletePostTemplate, this)));
200                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyPage(deleteReplyTemplate, this)));
201                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSonePage(followSoneTemplate, this)));
202                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSonePage(unfollowSoneTemplate, this)));
203                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteSonePage(deleteSoneTemplate, this), "DeleteSone"));
204                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LoginPage(loginTemplate, this), "Login"));
205                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LogoutPage(logoutTemplate, this), "Logout"));
206                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("noPermission.html", noPermissionTemplate, "Page.NoPermission.Title", this)));
207                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("css/", "/static/css/", "text/css")));
208                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("javascript/", "/static/javascript/", "text/javascript")));
209                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("images/", "/static/images/", "image/png")));
210                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetTranslationPage(this)));
211                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetSoneStatusPage(core())));
212
213                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
214                 toadletContainer.getPageMaker().addNavigationCategory("/Sone/index.html", "Navigation.Menu.Name", "Navigation.Menu.Tooltip", sonePlugin);
215                 for (PageToadlet toadlet : pageToadlets) {
216                         String menuName = toadlet.getMenuName();
217                         if (menuName != null) {
218                                 toadletContainer.register(toadlet, "Navigation.Menu.Name", toadlet.path(), true, "Navigation.Menu.Item." + menuName + ".Name", "Navigation.Menu.Item." + menuName + ".Tooltip", false, toadlet);
219                         } else {
220                                 toadletContainer.register(toadlet, null, toadlet.path(), true, false);
221                         }
222                 }
223         }
224
225         /**
226          * Unregisters all toadlets.
227          */
228         private void unregisterToadlets() {
229                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
230                 for (PageToadlet pageToadlet : pageToadlets) {
231                         toadletContainer.unregister(pageToadlet);
232                 }
233                 toadletContainer.getPageMaker().removeNavigationCategory("Navigation.Menu.Name");
234         }
235
236         /**
237          * Creates a {@link Reader} from the {@link InputStream} for the resource
238          * with the given name.
239          *
240          * @param resourceName
241          *            The name of the resource
242          * @return A {@link Reader} for the resource
243          */
244         private Reader createReader(String resourceName) {
245                 try {
246                         return new InputStreamReader(getClass().getResourceAsStream(resourceName), "UTF-8");
247                 } catch (UnsupportedEncodingException uee1) {
248                         return null;
249                 }
250         }
251
252         /**
253          * Template provider implementation that uses
254          * {@link WebInterface#createReader(String)} to load templates for
255          * inclusion.
256          *
257          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
258          */
259         private class ClassPathTemplateProvider implements TemplateProvider {
260
261                 /** The template factory. */
262                 private final TemplateFactory templateFactory;
263
264                 /**
265                  * Creates a new template provider that locates templates on the
266                  * classpath.
267                  *
268                  * @param templateFactory
269                  *            The template factory to create the templates
270                  */
271                 public ClassPathTemplateProvider(TemplateFactory templateFactory) {
272                         this.templateFactory = templateFactory;
273                 }
274
275                 /**
276                  * {@inheritDoc}
277                  */
278                 @Override
279                 @SuppressWarnings("synthetic-access")
280                 public Template getTemplate(String templateName) {
281                         Reader templateReader = createReader("/templates/" + templateName);
282                         if (templateReader == null) {
283                                 return null;
284                         }
285                         Template template = templateFactory.createTemplate(templateReader);
286                         try {
287                                 template.parse();
288                         } catch (TemplateException te1) {
289                                 logger.log(Level.WARNING, "Could not parse template “" + templateName + "” for inclusion!", te1);
290                         }
291                         return template;
292                 }
293
294         }
295 }