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