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