Use new session manager syntax.
[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.util.ArrayList;
25 import java.util.Collection;
26 import java.util.List;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import net.pterodactylus.sone.core.Core;
31 import net.pterodactylus.sone.core.CoreListener;
32 import net.pterodactylus.sone.data.Post;
33 import net.pterodactylus.sone.data.Reply;
34 import net.pterodactylus.sone.data.Sone;
35 import net.pterodactylus.sone.freenet.L10nFilter;
36 import net.pterodactylus.sone.freenet.wot.Identity;
37 import net.pterodactylus.sone.main.SonePlugin;
38 import net.pterodactylus.sone.notify.ListNotification;
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.GetStatusAjaxPage;
57 import net.pterodactylus.sone.web.ajax.GetTranslationPage;
58 import net.pterodactylus.sone.web.ajax.LikeAjaxPage;
59 import net.pterodactylus.sone.web.ajax.LockSoneAjaxPage;
60 import net.pterodactylus.sone.web.ajax.UnfollowSoneAjaxPage;
61 import net.pterodactylus.sone.web.ajax.UnlikeAjaxPage;
62 import net.pterodactylus.sone.web.ajax.UnlockSoneAjaxPage;
63 import net.pterodactylus.sone.web.page.PageToadlet;
64 import net.pterodactylus.sone.web.page.PageToadletFactory;
65 import net.pterodactylus.sone.web.page.StaticPage;
66 import net.pterodactylus.util.logging.Logging;
67 import net.pterodactylus.util.notify.NotificationManager;
68 import net.pterodactylus.util.notify.TemplateNotification;
69 import net.pterodactylus.util.template.DateFilter;
70 import net.pterodactylus.util.template.DefaultTemplateFactory;
71 import net.pterodactylus.util.template.MatchFilter;
72 import net.pterodactylus.util.template.PaginationPlugin;
73 import net.pterodactylus.util.template.ReflectionAccessor;
74 import net.pterodactylus.util.template.Template;
75 import net.pterodactylus.util.template.TemplateException;
76 import net.pterodactylus.util.template.TemplateFactory;
77 import net.pterodactylus.util.template.TemplateProvider;
78 import net.pterodactylus.util.template.XmlFilter;
79 import net.pterodactylus.util.thread.Ticker;
80 import freenet.clients.http.SessionManager;
81 import freenet.clients.http.ToadletContainer;
82 import freenet.l10n.BaseL10n;
83
84 /**
85  * Bundles functionality that a web interface of a Freenet plugin needs, e.g.
86  * references to l10n helpers.
87  *
88  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
89  */
90 public class WebInterface implements CoreListener {
91
92         /** The logger. */
93         private static final Logger logger = Logging.getLogger(WebInterface.class);
94
95         /** The notification manager. */
96         private final NotificationManager notificationManager = new NotificationManager();
97
98         /** The Sone plugin. */
99         private final SonePlugin sonePlugin;
100
101         /** The registered toadlets. */
102         private final List<PageToadlet> pageToadlets = new ArrayList<PageToadlet>();
103
104         /** The form password. */
105         private final String formPassword;
106
107         /** The template factory. */
108         private DefaultTemplateFactory templateFactory;
109
110         /** The “new Sone” notification. */
111         private final ListNotification<Sone> newSoneNotification;
112
113         /** The “new post” notification. */
114         private final ListNotification<Post> newPostNotification;
115
116         /** The “new reply” notification. */
117         private final ListNotification<Reply> newReplyNotification;
118
119         /** The “rescuing Sone” notification. */
120         private final ListNotification<Sone> rescuingSonesNotification;
121
122         /** The “Sone rescued” notification. */
123         private final ListNotification<Sone> sonesRescuedNotification;
124
125         /**
126          * Creates a new web interface.
127          *
128          * @param sonePlugin
129          *            The Sone plugin
130          */
131         public WebInterface(SonePlugin sonePlugin) {
132                 this.sonePlugin = sonePlugin;
133                 formPassword = sonePlugin.pluginRespirator().getToadletContainer().getFormPassword();
134
135                 templateFactory = new DefaultTemplateFactory();
136                 templateFactory.addAccessor(Object.class, new ReflectionAccessor());
137                 templateFactory.addAccessor(Collection.class, new CollectionAccessor());
138                 templateFactory.addAccessor(Sone.class, new SoneAccessor(getCore()));
139                 templateFactory.addAccessor(Post.class, new PostAccessor(getCore()));
140                 templateFactory.addAccessor(Reply.class, new ReplyAccessor(getCore()));
141                 templateFactory.addAccessor(Identity.class, new IdentityAccessor(getCore()));
142                 templateFactory.addAccessor(NotificationManager.class, new NotificationManagerAccessor());
143                 templateFactory.addFilter("date", new DateFilter());
144                 templateFactory.addFilter("l10n", new L10nFilter(getL10n()));
145                 templateFactory.addFilter("substring", new SubstringFilter());
146                 templateFactory.addFilter("xml", new XmlFilter());
147                 templateFactory.addFilter("change", new RequestChangeFilter());
148                 templateFactory.addFilter("match", new MatchFilter());
149                 templateFactory.addFilter("css", new CssClassNameFilter());
150                 templateFactory.addPlugin("getpage", new GetPagePlugin());
151                 templateFactory.addPlugin("paginate", new PaginationPlugin());
152                 templateFactory.setTemplateProvider(new ClassPathTemplateProvider(templateFactory));
153                 templateFactory.addTemplateObject("formPassword", formPassword);
154
155                 /* create notifications. */
156                 Template newSoneNotificationTemplate = templateFactory.createTemplate(createReader("/templates/notify/newSoneNotification.html"));
157                 newSoneNotification = new ListNotification<Sone>("new-sone-notification", "sones", newSoneNotificationTemplate);
158
159                 Template newPostNotificationTemplate = templateFactory.createTemplate(createReader("/templates/notify/newPostNotification.html"));
160                 newPostNotification = new ListNotification<Post>("new-post-notification", "posts", newPostNotificationTemplate);
161
162                 Template newReplyNotificationTemplate = templateFactory.createTemplate(createReader("/templates/notify/newReplyNotification.html"));
163                 newReplyNotification = new ListNotification<Reply>("new-replies-notification", "replies", newReplyNotificationTemplate);
164
165                 Template rescuingSonesTemplate = templateFactory.createTemplate(createReader("/templates/notify/rescuingSonesNotification.html"));
166                 rescuingSonesNotification = new ListNotification<Sone>("sones-being-rescued-notification", "sones", rescuingSonesTemplate);
167
168                 Template sonesRescuedTemplate = templateFactory.createTemplate(createReader("/templates/notify/sonesRescuedNotification.html"));
169                 sonesRescuedNotification = new ListNotification<Sone>("sones-rescued-notification", "sones", sonesRescuedTemplate);
170         }
171
172         //
173         // ACCESSORS
174         //
175
176         /**
177          * Returns the Sone core used by the Sone plugin.
178          *
179          * @return The Sone core
180          */
181         public Core getCore() {
182                 return sonePlugin.core();
183         }
184
185         /**
186          * Returns the notification manager.
187          *
188          * @return The notification manager
189          */
190         public NotificationManager getNotifications() {
191                 return notificationManager;
192         }
193
194         /**
195          * Returns the l10n helper of the node.
196          *
197          * @return The node’s l10n helper
198          */
199         public BaseL10n getL10n() {
200                 return sonePlugin.l10n().getBase();
201         }
202
203         /**
204          * Returns the session manager of the node.
205          *
206          * @return The node’s session manager
207          */
208         public SessionManager getSessionManager() {
209                 return sonePlugin.pluginRespirator().getSessionManager("Sone");
210         }
211
212         /**
213          * Returns the node’s form password.
214          *
215          * @return The form password
216          */
217         public String getFormPassword() {
218                 return formPassword;
219         }
220
221         //
222         // ACTIONS
223         //
224
225         /**
226          * Starts the web interface and registers all toadlets.
227          */
228         public void start() {
229                 registerToadlets();
230
231                 /* notification templates. */
232                 Template startupNotificationTemplate = templateFactory.createTemplate(createReader("/templates/notify/startupNotification.html"));
233
234                 final TemplateNotification startupNotification = new TemplateNotification("startup-notification", startupNotificationTemplate);
235                 notificationManager.addNotification(startupNotification);
236
237                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (120 * 1000), new Runnable() {
238
239                         @Override
240                         public void run() {
241                                 startupNotification.dismiss();
242                         }
243                 }, "Sone Startup Notification Remover");
244
245                 Template wotMissingNotificationTemplate = templateFactory.createTemplate(createReader("/templates/notify/wotMissingNotification.html"));
246                 final TemplateNotification wotMissingNotification = new TemplateNotification("wot-missing-notification", wotMissingNotificationTemplate);
247                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (15 * 1000), new Runnable() {
248
249                         @Override
250                         @SuppressWarnings("synthetic-access")
251                         public void run() {
252                                 if (getCore().getIdentityManager().isConnected()) {
253                                         wotMissingNotification.dismiss();
254                                 } else {
255                                         notificationManager.addNotification(wotMissingNotification);
256                                 }
257                                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (15 * 1000), this, "Sone WoT Connector Checker");
258                         }
259
260                 }, "Sone WoT Connector Checker");
261         }
262
263         /**
264          * Stops the web interface and unregisters all toadlets.
265          */
266         public void stop() {
267                 unregisterToadlets();
268                 Ticker.getInstance().stop();
269         }
270
271         //
272         // PRIVATE METHODS
273         //
274
275         /**
276          * Register all toadlets.
277          */
278         private void registerToadlets() {
279                 Template loginTemplate = templateFactory.createTemplate(createReader("/templates/login.html"));
280                 Template indexTemplate = templateFactory.createTemplate(createReader("/templates/index.html"));
281                 Template knownSonesTemplate = templateFactory.createTemplate(createReader("/templates/knownSones.html"));
282                 Template createSoneTemplate = templateFactory.createTemplate(createReader("/templates/createSone.html"));
283                 Template createPostTemplate = templateFactory.createTemplate(createReader("/templates/createPost.html"));
284                 Template createReplyTemplate = templateFactory.createTemplate(createReader("/templates/createReply.html"));
285                 Template editProfileTemplate = templateFactory.createTemplate(createReader("/templates/editProfile.html"));
286                 Template viewSoneTemplate = templateFactory.createTemplate(createReader("/templates/viewSone.html"));
287                 Template viewPostTemplate = templateFactory.createTemplate(createReader("/templates/viewPost.html"));
288                 Template likePostTemplate = templateFactory.createTemplate(createReader("/templates/like.html"));
289                 Template unlikePostTemplate = templateFactory.createTemplate(createReader("/templates/unlike.html"));
290                 Template deletePostTemplate = templateFactory.createTemplate(createReader("/templates/deletePost.html"));
291                 Template deleteReplyTemplate = templateFactory.createTemplate(createReader("/templates/deleteReply.html"));
292                 Template lockSoneTemplate = templateFactory.createTemplate(createReader("/templates/lockSone.html"));
293                 Template unlockSoneTemplate = templateFactory.createTemplate(createReader("/templates/unlockSone.html"));
294                 Template followSoneTemplate = templateFactory.createTemplate(createReader("/templates/followSone.html"));
295                 Template unfollowSoneTemplate = templateFactory.createTemplate(createReader("/templates/unfollowSone.html"));
296                 Template deleteSoneTemplate = templateFactory.createTemplate(createReader("/templates/deleteSone.html"));
297                 Template noPermissionTemplate = templateFactory.createTemplate(createReader("/templates/noPermission.html"));
298                 Template dismissNotificationTemplate = templateFactory.createTemplate(createReader("/templates/dismissNotification.html"));
299                 Template logoutTemplate = templateFactory.createTemplate(createReader("/templates/logout.html"));
300                 Template optionsTemplate = templateFactory.createTemplate(createReader("/templates/options.html"));
301                 Template aboutTemplate = templateFactory.createTemplate(createReader("/templates/about.html"));
302                 Template replyTemplate = templateFactory.createTemplate(createReader("/templates/include/viewReply.html"));
303
304                 PageToadletFactory pageToadletFactory = new PageToadletFactory(sonePlugin.pluginRespirator().getHLSimpleClient(), "/Sone/");
305                 pageToadlets.add(pageToadletFactory.createPageToadlet(new IndexPage(indexTemplate, this), "Index"));
306                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateSonePage(createSoneTemplate, this), "CreateSone"));
307                 pageToadlets.add(pageToadletFactory.createPageToadlet(new KnownSonesPage(knownSonesTemplate, this), "KnownSones"));
308                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfilePage(editProfileTemplate, this), "EditProfile"));
309                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreatePostPage(createPostTemplate, this)));
310                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyPage(createReplyTemplate, this)));
311                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewSonePage(viewSoneTemplate, this)));
312                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewPostPage(viewPostTemplate, this)));
313                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikePage(likePostTemplate, this)));
314                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikePage(unlikePostTemplate, this)));
315                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostPage(deletePostTemplate, this)));
316                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyPage(deleteReplyTemplate, this)));
317                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LockSonePage(lockSoneTemplate, this)));
318                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlockSonePage(unlockSoneTemplate, this)));
319                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSonePage(followSoneTemplate, this)));
320                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSonePage(unfollowSoneTemplate, this)));
321                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteSonePage(deleteSoneTemplate, this), "DeleteSone"));
322                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LoginPage(loginTemplate, this), "Login"));
323                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LogoutPage(logoutTemplate, this), "Logout"));
324                 pageToadlets.add(pageToadletFactory.createPageToadlet(new OptionsPage(optionsTemplate, this), "Options"));
325                 pageToadlets.add(pageToadletFactory.createPageToadlet(new AboutPage(aboutTemplate, this, SonePlugin.VERSION), "About"));
326                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("noPermission.html", noPermissionTemplate, "Page.NoPermission.Title", this)));
327                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DismissNotificationPage(dismissNotificationTemplate, this)));
328                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("css/", "/static/css/", "text/css")));
329                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("javascript/", "/static/javascript/", "text/javascript")));
330                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("images/", "/static/images/", "image/png")));
331                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetTranslationPage(this)));
332                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetStatusAjaxPage(this)));
333                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DismissNotificationAjaxPage(this)));
334                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyAjaxPage(this)));
335                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetReplyAjaxPage(this, replyTemplate)));
336                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostAjaxPage(this)));
337                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyAjaxPage(this)));
338                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LockSoneAjaxPage(this)));
339                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlockSoneAjaxPage(this)));
340                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSoneAjaxPage(this)));
341                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSoneAjaxPage(this)));
342                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikeAjaxPage(this)));
343                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikeAjaxPage(this)));
344                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetLikesAjaxPage(this)));
345
346                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
347                 toadletContainer.getPageMaker().addNavigationCategory("/Sone/index.html", "Navigation.Menu.Name", "Navigation.Menu.Tooltip", sonePlugin);
348                 for (PageToadlet toadlet : pageToadlets) {
349                         String menuName = toadlet.getMenuName();
350                         if (menuName != null) {
351                                 toadletContainer.register(toadlet, "Navigation.Menu.Name", toadlet.path(), true, "Navigation.Menu.Item." + menuName + ".Name", "Navigation.Menu.Item." + menuName + ".Tooltip", false, toadlet);
352                         } else {
353                                 toadletContainer.register(toadlet, null, toadlet.path(), true, false);
354                         }
355                 }
356         }
357
358         /**
359          * Unregisters all toadlets.
360          */
361         private void unregisterToadlets() {
362                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
363                 for (PageToadlet pageToadlet : pageToadlets) {
364                         toadletContainer.unregister(pageToadlet);
365                 }
366                 toadletContainer.getPageMaker().removeNavigationCategory("Navigation.Menu.Name");
367         }
368
369         /**
370          * Creates a {@link Reader} from the {@link InputStream} for the resource
371          * with the given name.
372          *
373          * @param resourceName
374          *            The name of the resource
375          * @return A {@link Reader} for the resource
376          */
377         private Reader createReader(String resourceName) {
378                 try {
379                         return new InputStreamReader(getClass().getResourceAsStream(resourceName), "UTF-8");
380                 } catch (UnsupportedEncodingException uee1) {
381                         return null;
382                 }
383         }
384
385         //
386         // CORELISTENER METHODS
387         //
388
389         /**
390          * {@inheritDoc}
391          */
392         @Override
393         public void rescuingSone(Sone sone) {
394                 rescuingSonesNotification.add(sone);
395                 notificationManager.addNotification(rescuingSonesNotification);
396         }
397
398         /**
399          * {@inheritDoc}
400          */
401         @Override
402         public void rescuedSone(Sone sone) {
403                 rescuingSonesNotification.remove(sone);
404                 sonesRescuedNotification.add(sone);
405                 notificationManager.addNotification(sonesRescuedNotification);
406         }
407
408         /**
409          * {@inheritDoc}
410          */
411         @Override
412         public void newSoneFound(Sone sone) {
413                 newSoneNotification.add(sone);
414                 notificationManager.addNotification(newSoneNotification);
415         }
416
417         /**
418          * {@inheritDoc}
419          */
420         @Override
421         public void newPostFound(Post post) {
422                 newPostNotification.add(post);
423                 notificationManager.addNotification(newPostNotification);
424         }
425
426         /**
427          * {@inheritDoc}
428          */
429         @Override
430         public void newReplyFound(Reply reply) {
431                 if (reply.getPost().getSone() == null) {
432                         return;
433                 }
434                 newReplyNotification.add(reply);
435                 notificationManager.addNotification(newReplyNotification);
436         }
437
438         /**
439          * {@inheritDoc}
440          */
441         @Override
442         public void markSoneKnown(Sone sone) {
443                 newSoneNotification.remove(sone);
444         }
445
446         /**
447          * {@inheritDoc}
448          */
449         @Override
450         public void markPostKnown(Post post) {
451                 newPostNotification.remove(post);
452         }
453
454         /**
455          * {@inheritDoc}
456          */
457         @Override
458         public void markReplyKnown(Reply reply) {
459                 newReplyNotification.remove(reply);
460         }
461
462         /**
463          * Template provider implementation that uses
464          * {@link WebInterface#createReader(String)} to load templates for
465          * inclusion.
466          *
467          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
468          */
469         private class ClassPathTemplateProvider implements TemplateProvider {
470
471                 /** The template factory. */
472                 @SuppressWarnings("hiding")
473                 private final TemplateFactory templateFactory;
474
475                 /**
476                  * Creates a new template provider that locates templates on the
477                  * classpath.
478                  *
479                  * @param templateFactory
480                  *            The template factory to create the templates
481                  */
482                 public ClassPathTemplateProvider(TemplateFactory templateFactory) {
483                         this.templateFactory = templateFactory;
484                 }
485
486                 /**
487                  * {@inheritDoc}
488                  */
489                 @Override
490                 @SuppressWarnings("synthetic-access")
491                 public Template getTemplate(String templateName) {
492                         Reader templateReader = createReader("/templates/" + templateName);
493                         if (templateReader == null) {
494                                 return null;
495                         }
496                         Template template = templateFactory.createTemplate(templateReader);
497                         try {
498                                 template.parse();
499                         } catch (TemplateException te1) {
500                                 logger.log(Level.WARNING, "Could not parse template “" + templateName + "” for inclusion!", te1);
501                         }
502                         return template;
503                 }
504
505         }
506
507 }