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