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