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