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