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