Add image insert notifications.
[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.StringReader;
24 import java.io.UnsupportedEncodingException;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.UUID;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
36
37 import net.pterodactylus.sone.core.Core;
38 import net.pterodactylus.sone.core.CoreListener;
39 import net.pterodactylus.sone.data.Album;
40 import net.pterodactylus.sone.data.Image;
41 import net.pterodactylus.sone.data.Post;
42 import net.pterodactylus.sone.data.Reply;
43 import net.pterodactylus.sone.data.Sone;
44 import net.pterodactylus.sone.freenet.L10nFilter;
45 import net.pterodactylus.sone.freenet.wot.Identity;
46 import net.pterodactylus.sone.freenet.wot.Trust;
47 import net.pterodactylus.sone.main.SonePlugin;
48 import net.pterodactylus.sone.notify.ListNotification;
49 import net.pterodactylus.sone.template.AlbumAccessor;
50 import net.pterodactylus.sone.template.CollectionAccessor;
51 import net.pterodactylus.sone.template.CssClassNameFilter;
52 import net.pterodactylus.sone.template.GetPagePlugin;
53 import net.pterodactylus.sone.template.IdentityAccessor;
54 import net.pterodactylus.sone.template.ImageLinkFilter;
55 import net.pterodactylus.sone.template.JavascriptFilter;
56 import net.pterodactylus.sone.template.NotificationManagerAccessor;
57 import net.pterodactylus.sone.template.ParserFilter;
58 import net.pterodactylus.sone.template.PostAccessor;
59 import net.pterodactylus.sone.template.ReplyAccessor;
60 import net.pterodactylus.sone.template.RequestChangeFilter;
61 import net.pterodactylus.sone.template.SoneAccessor;
62 import net.pterodactylus.sone.template.SubstringFilter;
63 import net.pterodactylus.sone.template.TrustAccessor;
64 import net.pterodactylus.sone.template.UnknownDateFilter;
65 import net.pterodactylus.sone.web.ajax.BookmarkAjaxPage;
66 import net.pterodactylus.sone.web.ajax.CreatePostAjaxPage;
67 import net.pterodactylus.sone.web.ajax.CreateReplyAjaxPage;
68 import net.pterodactylus.sone.web.ajax.DeletePostAjaxPage;
69 import net.pterodactylus.sone.web.ajax.DeleteProfileFieldAjaxPage;
70 import net.pterodactylus.sone.web.ajax.DeleteReplyAjaxPage;
71 import net.pterodactylus.sone.web.ajax.DismissNotificationAjaxPage;
72 import net.pterodactylus.sone.web.ajax.DistrustAjaxPage;
73 import net.pterodactylus.sone.web.ajax.EditProfileFieldAjaxPage;
74 import net.pterodactylus.sone.web.ajax.FollowSoneAjaxPage;
75 import net.pterodactylus.sone.web.ajax.GetLikesAjaxPage;
76 import net.pterodactylus.sone.web.ajax.GetPostAjaxPage;
77 import net.pterodactylus.sone.web.ajax.GetReplyAjaxPage;
78 import net.pterodactylus.sone.web.ajax.GetStatusAjaxPage;
79 import net.pterodactylus.sone.web.ajax.GetTranslationPage;
80 import net.pterodactylus.sone.web.ajax.LikeAjaxPage;
81 import net.pterodactylus.sone.web.ajax.LockSoneAjaxPage;
82 import net.pterodactylus.sone.web.ajax.MarkAsKnownAjaxPage;
83 import net.pterodactylus.sone.web.ajax.MoveProfileFieldAjaxPage;
84 import net.pterodactylus.sone.web.ajax.TrustAjaxPage;
85 import net.pterodactylus.sone.web.ajax.UnbookmarkAjaxPage;
86 import net.pterodactylus.sone.web.ajax.UnfollowSoneAjaxPage;
87 import net.pterodactylus.sone.web.ajax.UnlikeAjaxPage;
88 import net.pterodactylus.sone.web.ajax.UnlockSoneAjaxPage;
89 import net.pterodactylus.sone.web.ajax.UntrustAjaxPage;
90 import net.pterodactylus.sone.web.page.PageToadlet;
91 import net.pterodactylus.sone.web.page.PageToadletFactory;
92 import net.pterodactylus.sone.web.page.StaticPage;
93 import net.pterodactylus.util.cache.Cache;
94 import net.pterodactylus.util.cache.CacheException;
95 import net.pterodactylus.util.cache.CacheItem;
96 import net.pterodactylus.util.cache.DefaultCacheItem;
97 import net.pterodactylus.util.cache.MemoryCache;
98 import net.pterodactylus.util.cache.ValueRetriever;
99 import net.pterodactylus.util.logging.Logging;
100 import net.pterodactylus.util.notify.Notification;
101 import net.pterodactylus.util.notify.NotificationManager;
102 import net.pterodactylus.util.notify.TemplateNotification;
103 import net.pterodactylus.util.template.CollectionSortFilter;
104 import net.pterodactylus.util.template.DateFilter;
105 import net.pterodactylus.util.template.FormatFilter;
106 import net.pterodactylus.util.template.HtmlFilter;
107 import net.pterodactylus.util.template.MatchFilter;
108 import net.pterodactylus.util.template.PaginationPlugin;
109 import net.pterodactylus.util.template.Provider;
110 import net.pterodactylus.util.template.ReflectionAccessor;
111 import net.pterodactylus.util.template.ReplaceFilter;
112 import net.pterodactylus.util.template.StoreFilter;
113 import net.pterodactylus.util.template.Template;
114 import net.pterodactylus.util.template.TemplateContext;
115 import net.pterodactylus.util.template.TemplateContextFactory;
116 import net.pterodactylus.util.template.TemplateException;
117 import net.pterodactylus.util.template.TemplateParser;
118 import net.pterodactylus.util.template.XmlFilter;
119 import net.pterodactylus.util.thread.Ticker;
120 import net.pterodactylus.util.version.Version;
121 import freenet.clients.http.SessionManager;
122 import freenet.clients.http.SessionManager.Session;
123 import freenet.clients.http.ToadletContainer;
124 import freenet.clients.http.ToadletContext;
125 import freenet.l10n.BaseL10n;
126
127 /**
128  * Bundles functionality that a web interface of a Freenet plugin needs, e.g.
129  * references to l10n helpers.
130  *
131  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
132  */
133 public class WebInterface implements CoreListener {
134
135         /** The logger. */
136         private static final Logger logger = Logging.getLogger(WebInterface.class);
137
138         /** The notification manager. */
139         private final NotificationManager notificationManager = new NotificationManager();
140
141         /** The Sone plugin. */
142         private final SonePlugin sonePlugin;
143
144         /** The registered toadlets. */
145         private final List<PageToadlet> pageToadlets = new ArrayList<PageToadlet>();
146
147         /** The form password. */
148         private final String formPassword;
149
150         /** The template context factory. */
151         private final TemplateContextFactory templateContextFactory;
152
153         /** The “new Sone” notification. */
154         private final ListNotification<Sone> newSoneNotification;
155
156         /** The “new post” notification. */
157         private final ListNotification<Post> newPostNotification;
158
159         /** The “new reply” notification. */
160         private final ListNotification<Reply> newReplyNotification;
161
162         /** The “rescuing Sone” notification. */
163         private final ListNotification<Sone> rescuingSonesNotification;
164
165         /** The “Sone rescued” notification. */
166         private final ListNotification<Sone> sonesRescuedNotification;
167
168         /** Sone locked notification ticker objects. */
169         private final Map<Sone, Object> lockedSonesTickerObjects = Collections.synchronizedMap(new HashMap<Sone, Object>());
170
171         /** The “Sone locked” notification. */
172         private final ListNotification<Sone> lockedSonesNotification;
173
174         /** The “new version” notification. */
175         private final TemplateNotification newVersionNotification;
176
177         /** The “inserting images” notification. */
178         private final ListNotification<Image> insertingImagesNotification;
179
180         /** The “inserted images” notification. */
181         private final ListNotification<Image> insertedImagesNotification;
182
183         /** The “image insert failed” notification. */
184         private final ListNotification<Image> imageInsertFailedNotification;
185
186         /**
187          * Creates a new web interface.
188          *
189          * @param sonePlugin
190          *            The Sone plugin
191          */
192         @SuppressWarnings("synthetic-access")
193         public WebInterface(SonePlugin sonePlugin) {
194                 this.sonePlugin = sonePlugin;
195                 formPassword = sonePlugin.pluginRespirator().getToadletContainer().getFormPassword();
196
197                 templateContextFactory = new TemplateContextFactory();
198                 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
199                 templateContextFactory.addAccessor(Collection.class, new CollectionAccessor());
200                 templateContextFactory.addAccessor(Sone.class, new SoneAccessor(getCore()));
201                 templateContextFactory.addAccessor(Post.class, new PostAccessor(getCore()));
202                 templateContextFactory.addAccessor(Reply.class, new ReplyAccessor(getCore()));
203                 templateContextFactory.addAccessor(Album.class, new AlbumAccessor());
204                 templateContextFactory.addAccessor(Identity.class, new IdentityAccessor(getCore()));
205                 templateContextFactory.addAccessor(NotificationManager.class, new NotificationManagerAccessor());
206                 templateContextFactory.addAccessor(Trust.class, new TrustAccessor());
207                 templateContextFactory.addFilter("date", new DateFilter());
208                 templateContextFactory.addFilter("html", new HtmlFilter());
209                 templateContextFactory.addFilter("replace", new ReplaceFilter());
210                 templateContextFactory.addFilter("store", new StoreFilter());
211                 templateContextFactory.addFilter("l10n", new L10nFilter(getL10n()));
212                 templateContextFactory.addFilter("substring", new SubstringFilter());
213                 templateContextFactory.addFilter("xml", new XmlFilter());
214                 templateContextFactory.addFilter("change", new RequestChangeFilter());
215                 templateContextFactory.addFilter("match", new MatchFilter());
216                 templateContextFactory.addFilter("css", new CssClassNameFilter());
217                 templateContextFactory.addFilter("js", new JavascriptFilter());
218                 templateContextFactory.addFilter("parse", new ParserFilter(getCore(), templateContextFactory));
219                 templateContextFactory.addFilter("unknown", new UnknownDateFilter(getL10n(), "View.Sone.Text.UnknownDate"));
220                 templateContextFactory.addFilter("format", new FormatFilter());
221                 templateContextFactory.addFilter("sort", new CollectionSortFilter());
222                 templateContextFactory.addFilter("image-link", new ImageLinkFilter(templateContextFactory));
223                 templateContextFactory.addProvider(Provider.TEMPLATE_CONTEXT_PROVIDER);
224                 templateContextFactory.addProvider(new ClassPathTemplateProvider());
225                 templateContextFactory.addTemplateObject("formPassword", formPassword);
226
227                 /* create notifications. */
228                 Template newSoneNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newSoneNotification.html"));
229                 newSoneNotification = new ListNotification<Sone>("new-sone-notification", "sones", newSoneNotificationTemplate);
230
231                 Template newPostNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newPostNotification.html"));
232                 newPostNotification = new ListNotification<Post>("new-post-notification", "posts", newPostNotificationTemplate);
233
234                 Template newReplyNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newReplyNotification.html"));
235                 newReplyNotification = new ListNotification<Reply>("new-replies-notification", "replies", newReplyNotificationTemplate);
236
237                 Template rescuingSonesTemplate = TemplateParser.parse(createReader("/templates/notify/rescuingSonesNotification.html"));
238                 rescuingSonesNotification = new ListNotification<Sone>("sones-being-rescued-notification", "sones", rescuingSonesTemplate);
239
240                 Template sonesRescuedTemplate = TemplateParser.parse(createReader("/templates/notify/sonesRescuedNotification.html"));
241                 sonesRescuedNotification = new ListNotification<Sone>("sones-rescued-notification", "sones", sonesRescuedTemplate);
242
243                 Template lockedSonesTemplate = TemplateParser.parse(createReader("/templates/notify/lockedSonesNotification.html"));
244                 lockedSonesNotification = new ListNotification<Sone>("sones-locked-notification", "sones", lockedSonesTemplate);
245
246                 Template newVersionTemplate = TemplateParser.parse(createReader("/templates/notify/newVersionNotification.html"));
247                 newVersionNotification = new TemplateNotification("new-version-notification", newVersionTemplate);
248
249                 Template insertingImagesTemplate = TemplateParser.parse(createReader("/templates/notify/inserting-images-notification.html"));
250                 insertingImagesNotification = new ListNotification<Image>("inserting-images-notification", "images", insertingImagesTemplate);
251
252                 Template insertedImagesTemplate = TemplateParser.parse(createReader("/templates/notify/inserted-images-notification.html"));
253                 insertedImagesNotification = new ListNotification<Image>("inserted-images-notification", "images", insertedImagesTemplate);
254
255                 Template imageInsertFailedTemplate = TemplateParser.parse(createReader("/templates/notify/image-insert-failed-notification.html"));
256                 imageInsertFailedNotification = new ListNotification<Image>("image-insert-failed-notification", "images", imageInsertFailedTemplate);
257         }
258
259         //
260         // ACCESSORS
261         //
262
263         /**
264          * Returns the Sone core used by the Sone plugin.
265          *
266          * @return The Sone core
267          */
268         public Core getCore() {
269                 return sonePlugin.core();
270         }
271
272         /**
273          * Returns the template context factory of the web interface.
274          *
275          * @return The template context factory
276          */
277         public TemplateContextFactory getTemplateContextFactory() {
278                 return templateContextFactory;
279         }
280
281         /**
282          * Returns the current session, creating a new session if there is no
283          * current session.
284          *
285          * @param toadletContenxt
286          *            The toadlet context
287          * @return The current session, or {@code null} if there is no current
288          *         session
289          */
290         public Session getCurrentSession(ToadletContext toadletContenxt) {
291                 return getCurrentSession(toadletContenxt, true);
292         }
293
294         /**
295          * Returns the current session, creating a new session if there is no
296          * current session and {@code create} is {@code true}.
297          *
298          * @param toadletContenxt
299          *            The toadlet context
300          * @param create
301          *            {@code true} to create a new session if there is no current
302          *            session, {@code false} otherwise
303          * @return The current session, or {@code null} if there is no current
304          *         session
305          */
306         public Session getCurrentSession(ToadletContext toadletContenxt, boolean create) {
307                 Session session = getSessionManager().useSession(toadletContenxt);
308                 if (create && (session == null)) {
309                         session = getSessionManager().createSession(UUID.randomUUID().toString(), toadletContenxt);
310                 }
311                 return session;
312         }
313
314         /**
315          * Returns the currently logged in Sone.
316          *
317          * @param toadletContext
318          *            The toadlet context
319          * @return The currently logged in Sone, or {@code null} if no Sone is
320          *         currently logged in
321          */
322         public Sone getCurrentSone(ToadletContext toadletContext) {
323                 return getCurrentSone(toadletContext, true);
324         }
325
326         /**
327          * Returns the currently logged in Sone.
328          *
329          * @param toadletContext
330          *            The toadlet context
331          * @param create
332          *            {@code true} to create a new session if no session exists,
333          *            {@code false} to not create a new session
334          * @return The currently logged in Sone, or {@code null} if no Sone is
335          *         currently logged in
336          */
337         public Sone getCurrentSone(ToadletContext toadletContext, boolean create) {
338                 Set<Sone> localSones = getCore().getLocalSones();
339                 if (localSones.size() == 1) {
340                         return localSones.iterator().next();
341                 }
342                 return getCurrentSone(getCurrentSession(toadletContext, create));
343         }
344
345         /**
346          * Returns the currently logged in Sone.
347          *
348          * @param session
349          *            The session
350          * @return The currently logged in Sone, or {@code null} if no Sone is
351          *         currently logged in
352          */
353         public Sone getCurrentSone(Session session) {
354                 if (session == null) {
355                         return null;
356                 }
357                 String soneId = (String) session.getAttribute("Sone.CurrentSone");
358                 if (soneId == null) {
359                         return null;
360                 }
361                 return getCore().getLocalSone(soneId, false);
362         }
363
364         /**
365          * Sets the currently logged in Sone.
366          *
367          * @param toadletContext
368          *            The toadlet context
369          * @param sone
370          *            The Sone to set as currently logged in
371          */
372         public void setCurrentSone(ToadletContext toadletContext, Sone sone) {
373                 Session session = getCurrentSession(toadletContext);
374                 if (sone == null) {
375                         session.removeAttribute("Sone.CurrentSone");
376                 } else {
377                         session.setAttribute("Sone.CurrentSone", sone.getId());
378                 }
379         }
380
381         /**
382          * Returns the notification manager.
383          *
384          * @return The notification manager
385          */
386         public NotificationManager getNotifications() {
387                 return notificationManager;
388         }
389
390         /**
391          * Returns the l10n helper of the node.
392          *
393          * @return The node’s l10n helper
394          */
395         public BaseL10n getL10n() {
396                 return sonePlugin.l10n().getBase();
397         }
398
399         /**
400          * Returns the session manager of the node.
401          *
402          * @return The node’s session manager
403          */
404         public SessionManager getSessionManager() {
405                 return sonePlugin.pluginRespirator().getSessionManager("Sone");
406         }
407
408         /**
409          * Returns the node’s form password.
410          *
411          * @return The form password
412          */
413         public String getFormPassword() {
414                 return formPassword;
415         }
416
417         /**
418          * Returns the posts that have been announced as new in the
419          * {@link #newPostNotification}.
420          *
421          * @return The new posts
422          */
423         public Set<Post> getNewPosts() {
424                 return new HashSet<Post>(newPostNotification.getElements());
425         }
426
427         /**
428          * Returns the replies that have been announced as new in the
429          * {@link #newReplyNotification}.
430          *
431          * @return The new replies
432          */
433         public Set<Reply> getNewReplies() {
434                 return new HashSet<Reply>(newReplyNotification.getElements());
435         }
436
437         /**
438          * Sets whether the current start of the plugin is the first start. It is
439          * considered a first start if the configuration file does not exist.
440          *
441          * @param firstStart
442          *            {@code true} if no configuration file existed when Sone was
443          *            loaded, {@code false} otherwise
444          */
445         public void setFirstStart(boolean firstStart) {
446                 if (firstStart) {
447                         Template firstStartNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/firstStartNotification.html"));
448                         Notification firstStartNotification = new TemplateNotification("first-start-notification", firstStartNotificationTemplate);
449                         notificationManager.addNotification(firstStartNotification);
450                 }
451         }
452
453         /**
454          * Sets whether Sone was started with a fresh configuration file.
455          *
456          * @param newConfig
457          *            {@code true} if Sone was started with a fresh configuration,
458          *            {@code false} if the existing configuration could be read
459          */
460         public void setNewConfig(boolean newConfig) {
461                 if (newConfig && !hasFirstStartNotification()) {
462                         Template configNotReadNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/configNotReadNotification.html"));
463                         Notification configNotReadNotification = new TemplateNotification("config-not-read-notification", configNotReadNotificationTemplate);
464                         notificationManager.addNotification(configNotReadNotification);
465                 }
466         }
467
468         //
469         // PRIVATE ACCESSORS
470         //
471
472         /**
473          * Returns whether the first start notification is currently displayed.
474          *
475          * @return {@code true} if the first-start notification is currently
476          *         displayed, {@code false} otherwise
477          */
478         private boolean hasFirstStartNotification() {
479                 return notificationManager.getNotification("first-start-notification") != null;
480         }
481
482         //
483         // ACTIONS
484         //
485
486         /**
487          * Starts the web interface and registers all toadlets.
488          */
489         public void start() {
490                 registerToadlets();
491
492                 /* notification templates. */
493                 Template startupNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/startupNotification.html"));
494
495                 final TemplateNotification startupNotification = new TemplateNotification("startup-notification", startupNotificationTemplate);
496                 notificationManager.addNotification(startupNotification);
497
498                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (120 * 1000), new Runnable() {
499
500                         @Override
501                         public void run() {
502                                 startupNotification.dismiss();
503                         }
504                 }, "Sone Startup Notification Remover");
505
506                 Template wotMissingNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/wotMissingNotification.html"));
507                 final TemplateNotification wotMissingNotification = new TemplateNotification("wot-missing-notification", wotMissingNotificationTemplate);
508                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (15 * 1000), new Runnable() {
509
510                         @Override
511                         @SuppressWarnings("synthetic-access")
512                         public void run() {
513                                 if (getCore().getIdentityManager().isConnected()) {
514                                         wotMissingNotification.dismiss();
515                                 } else {
516                                         notificationManager.addNotification(wotMissingNotification);
517                                 }
518                                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (15 * 1000), this, "Sone WoT Connector Checker");
519                         }
520
521                 }, "Sone WoT Connector Checker");
522         }
523
524         /**
525          * Stops the web interface and unregisters all toadlets.
526          */
527         public void stop() {
528                 unregisterToadlets();
529                 Ticker.getInstance().stop();
530         }
531
532         //
533         // PRIVATE METHODS
534         //
535
536         /**
537          * Register all toadlets.
538          */
539         private void registerToadlets() {
540                 Template emptyTemplate = TemplateParser.parse(new StringReader(""));
541                 Template loginTemplate = TemplateParser.parse(createReader("/templates/login.html"));
542                 Template indexTemplate = TemplateParser.parse(createReader("/templates/index.html"));
543                 Template knownSonesTemplate = TemplateParser.parse(createReader("/templates/knownSones.html"));
544                 Template createSoneTemplate = TemplateParser.parse(createReader("/templates/createSone.html"));
545                 Template createPostTemplate = TemplateParser.parse(createReader("/templates/createPost.html"));
546                 Template createReplyTemplate = TemplateParser.parse(createReader("/templates/createReply.html"));
547                 Template bookmarksTemplate = TemplateParser.parse(createReader("/templates/bookmarks.html"));
548                 Template editProfileTemplate = TemplateParser.parse(createReader("/templates/editProfile.html"));
549                 Template editProfileFieldTemplate = TemplateParser.parse(createReader("/templates/editProfileField.html"));
550                 Template deleteProfileFieldTemplate = TemplateParser.parse(createReader("/templates/deleteProfileField.html"));
551                 Template viewSoneTemplate = TemplateParser.parse(createReader("/templates/viewSone.html"));
552                 Template viewPostTemplate = TemplateParser.parse(createReader("/templates/viewPost.html"));
553                 Template deletePostTemplate = TemplateParser.parse(createReader("/templates/deletePost.html"));
554                 Template deleteReplyTemplate = TemplateParser.parse(createReader("/templates/deleteReply.html"));
555                 Template deleteSoneTemplate = TemplateParser.parse(createReader("/templates/deleteSone.html"));
556                 Template imageBrowserTemplate = TemplateParser.parse(createReader("/templates/imageBrowser.html"));
557                 Template createAlbumTemplate = TemplateParser.parse(createReader("/templates/createAlbum.html"));
558                 Template noPermissionTemplate = TemplateParser.parse(createReader("/templates/noPermission.html"));
559                 Template optionsTemplate = TemplateParser.parse(createReader("/templates/options.html"));
560                 Template aboutTemplate = TemplateParser.parse(createReader("/templates/about.html"));
561                 Template invalidTemplate = TemplateParser.parse(createReader("/templates/invalid.html"));
562                 Template postTemplate = TemplateParser.parse(createReader("/templates/include/viewPost.html"));
563                 Template replyTemplate = TemplateParser.parse(createReader("/templates/include/viewReply.html"));
564
565                 PageToadletFactory pageToadletFactory = new PageToadletFactory(sonePlugin.pluginRespirator().getHLSimpleClient(), "/Sone/");
566                 pageToadlets.add(pageToadletFactory.createPageToadlet(new IndexPage(indexTemplate, this), "Index"));
567                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateSonePage(createSoneTemplate, this), "CreateSone"));
568                 pageToadlets.add(pageToadletFactory.createPageToadlet(new KnownSonesPage(knownSonesTemplate, this), "KnownSones"));
569                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfilePage(editProfileTemplate, this), "EditProfile"));
570                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfileFieldPage(editProfileFieldTemplate, this)));
571                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteProfileFieldPage(deleteProfileFieldTemplate, this)));
572                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreatePostPage(createPostTemplate, this)));
573                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyPage(createReplyTemplate, this)));
574                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewSonePage(viewSoneTemplate, this)));
575                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewPostPage(viewPostTemplate, this)));
576                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikePage(emptyTemplate, this)));
577                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikePage(emptyTemplate, this)));
578                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostPage(deletePostTemplate, this)));
579                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyPage(deleteReplyTemplate, this)));
580                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LockSonePage(emptyTemplate, this)));
581                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlockSonePage(emptyTemplate, this)));
582                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSonePage(emptyTemplate, this)));
583                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSonePage(emptyTemplate, this)));
584                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ImageBrowserPage(imageBrowserTemplate, this), "ImageBrowser"));
585                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateAlbumPage(createAlbumTemplate, this)));
586                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UploadImagePage(invalidTemplate, this)));
587                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TrustPage(emptyTemplate, this)));
588                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DistrustPage(emptyTemplate, this)));
589                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UntrustPage(emptyTemplate, this)));
590                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MarkAsKnownPage(emptyTemplate, this)));
591                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarkPage(emptyTemplate, this)));
592                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnbookmarkPage(emptyTemplate, this)));
593                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarksPage(bookmarksTemplate, this), "Bookmarks"));
594                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteSonePage(deleteSoneTemplate, this), "DeleteSone"));
595                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LoginPage(loginTemplate, this), "Login"));
596                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LogoutPage(emptyTemplate, this), "Logout"));
597                 pageToadlets.add(pageToadletFactory.createPageToadlet(new OptionsPage(optionsTemplate, this), "Options"));
598                 pageToadlets.add(pageToadletFactory.createPageToadlet(new AboutPage(aboutTemplate, this, SonePlugin.VERSION), "About"));
599                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("noPermission.html", noPermissionTemplate, "Page.NoPermission.Title", this)));
600                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DismissNotificationPage(emptyTemplate, this)));
601                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("invalid.html", invalidTemplate, "Page.Invalid.Title", this)));
602                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("css/", "/static/css/", "text/css")));
603                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("javascript/", "/static/javascript/", "text/javascript")));
604                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("images/", "/static/images/", "image/png")));
605                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TemplatePage("OpenSearch.xml", "application/opensearchdescription+xml", templateContextFactory, openSearchTemplate)));
606                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetImagePage(this)));
607                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetTranslationPage(this)));
608                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetStatusAjaxPage(this)));
609                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DismissNotificationAjaxPage(this)));
610                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreatePostAjaxPage(this)));
611                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyAjaxPage(this)));
612                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetReplyAjaxPage(this, replyTemplate)));
613                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetPostAjaxPage(this, postTemplate)));
614                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MarkAsKnownAjaxPage(this)));
615                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostAjaxPage(this)));
616                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyAjaxPage(this)));
617                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LockSoneAjaxPage(this)));
618                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlockSoneAjaxPage(this)));
619                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSoneAjaxPage(this)));
620                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSoneAjaxPage(this)));
621                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TrustAjaxPage(this)));
622                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DistrustAjaxPage(this)));
623                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UntrustAjaxPage(this)));
624                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikeAjaxPage(this)));
625                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikeAjaxPage(this)));
626                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetLikesAjaxPage(this)));
627                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarkAjaxPage(this)));
628                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnbookmarkAjaxPage(this)));
629                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfileFieldAjaxPage(this)));
630                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteProfileFieldAjaxPage(this)));
631                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MoveProfileFieldAjaxPage(this)));
632
633                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
634                 toadletContainer.getPageMaker().addNavigationCategory("/Sone/index.html", "Navigation.Menu.Name", "Navigation.Menu.Tooltip", sonePlugin);
635                 for (PageToadlet toadlet : pageToadlets) {
636                         String menuName = toadlet.getMenuName();
637                         if (menuName != null) {
638                                 toadletContainer.register(toadlet, "Navigation.Menu.Name", toadlet.path(), true, "Navigation.Menu.Item." + menuName + ".Name", "Navigation.Menu.Item." + menuName + ".Tooltip", false, toadlet);
639                         } else {
640                                 toadletContainer.register(toadlet, null, toadlet.path(), true, false);
641                         }
642                 }
643         }
644
645         /**
646          * Unregisters all toadlets.
647          */
648         private void unregisterToadlets() {
649                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
650                 for (PageToadlet pageToadlet : pageToadlets) {
651                         toadletContainer.unregister(pageToadlet);
652                 }
653                 toadletContainer.getPageMaker().removeNavigationCategory("Navigation.Menu.Name");
654         }
655
656         /**
657          * Creates a {@link Reader} from the {@link InputStream} for the resource
658          * with the given name.
659          *
660          * @param resourceName
661          *            The name of the resource
662          * @return A {@link Reader} for the resource
663          */
664         private Reader createReader(String resourceName) {
665                 try {
666                         return new InputStreamReader(getClass().getResourceAsStream(resourceName), "UTF-8");
667                 } catch (UnsupportedEncodingException uee1) {
668                         System.out.println("  fail.");
669                         return null;
670                 }
671         }
672
673         //
674         // CORELISTENER METHODS
675         //
676
677         /**
678          * {@inheritDoc}
679          */
680         @Override
681         public void rescuingSone(Sone sone) {
682                 rescuingSonesNotification.add(sone);
683                 notificationManager.addNotification(rescuingSonesNotification);
684         }
685
686         /**
687          * {@inheritDoc}
688          */
689         @Override
690         public void rescuedSone(Sone sone) {
691                 rescuingSonesNotification.remove(sone);
692                 sonesRescuedNotification.add(sone);
693                 notificationManager.addNotification(sonesRescuedNotification);
694         }
695
696         /**
697          * {@inheritDoc}
698          */
699         @Override
700         public void newSoneFound(Sone sone) {
701                 newSoneNotification.add(sone);
702                 if (!hasFirstStartNotification()) {
703                         notificationManager.addNotification(newSoneNotification);
704                 }
705         }
706
707         /**
708          * {@inheritDoc}
709          */
710         @Override
711         public void newPostFound(Post post) {
712                 newPostNotification.add(post);
713                 if (!hasFirstStartNotification()) {
714                         notificationManager.addNotification(newPostNotification);
715                 } else {
716                         getCore().markPostKnown(post);
717                 }
718         }
719
720         /**
721          * {@inheritDoc}
722          */
723         @Override
724         public void newReplyFound(Reply reply) {
725                 if (reply.getPost().getSone() == null) {
726                         return;
727                 }
728                 newReplyNotification.add(reply);
729                 if (!hasFirstStartNotification()) {
730                         notificationManager.addNotification(newReplyNotification);
731                 } else {
732                         getCore().markReplyKnown(reply);
733                 }
734         }
735
736         /**
737          * {@inheritDoc}
738          */
739         @Override
740         public void markSoneKnown(Sone sone) {
741                 newSoneNotification.remove(sone);
742         }
743
744         /**
745          * {@inheritDoc}
746          */
747         @Override
748         public void markPostKnown(Post post) {
749                 newPostNotification.remove(post);
750         }
751
752         /**
753          * {@inheritDoc}
754          */
755         @Override
756         public void markReplyKnown(Reply reply) {
757                 newReplyNotification.remove(reply);
758         }
759
760         /**
761          * {@inheritDoc}
762          */
763         @Override
764         public void postRemoved(Post post) {
765                 newPostNotification.remove(post);
766         }
767
768         /**
769          * {@inheritDoc}
770          */
771         @Override
772         public void replyRemoved(Reply reply) {
773                 newReplyNotification.remove(reply);
774         }
775
776         /**
777          * {@inheritDoc}
778          */
779         @Override
780         public void soneLocked(final Sone sone) {
781                 Object tickerObject = Ticker.getInstance().registerEvent(System.currentTimeMillis() + (5 * 60) * 1000, new Runnable() {
782
783                         @Override
784                         @SuppressWarnings("synthetic-access")
785                         public void run() {
786                                 lockedSonesNotification.add(sone);
787                                 lockedSonesTickerObjects.remove(sone);
788                                 notificationManager.addNotification(lockedSonesNotification);
789                         }
790                 }, "Sone Locked Notification");
791                 lockedSonesTickerObjects.put(sone, tickerObject);
792         }
793
794         /**
795          * {@inheritDoc}
796          */
797         @Override
798         public void soneUnlocked(Sone sone) {
799                 lockedSonesNotification.remove(sone);
800                 Ticker.getInstance().deregisterEvent(lockedSonesTickerObjects.remove(sone));
801         }
802
803         /**
804          * {@inheritDoc}
805          */
806         @Override
807         public void updateFound(Version version, long releaseTime, long latestEdition) {
808                 newVersionNotification.getTemplateContext().set("latestVersion", version);
809                 newVersionNotification.getTemplateContext().set("latestEdition", latestEdition);
810                 newVersionNotification.getTemplateContext().set("releaseTime", releaseTime);
811                 notificationManager.addNotification(newVersionNotification);
812         }
813
814         /**
815          * {@inheritDoc}
816          */
817         @Override
818         public void imageInsertStarted(Image image) {
819                 insertingImagesNotification.add(image);
820                 notificationManager.addNotification(insertingImagesNotification);
821         }
822
823         /**
824          * {@inheritDoc}
825          */
826         @Override
827         public void imageInsertAborted(Image image) {
828                 insertingImagesNotification.remove(image);
829         }
830
831         /**
832          * {@inheritDoc}
833          */
834         @Override
835         public void imageInsertFinished(Image image) {
836                 insertingImagesNotification.remove(image);
837                 insertedImagesNotification.add(image);
838                 notificationManager.addNotification(insertedImagesNotification);
839         }
840
841         /**
842          * {@inheritDoc}
843          */
844         @Override
845         public void imageInsertFailed(Image image, Throwable cause) {
846                 insertingImagesNotification.remove(image);
847                 imageInsertFailedNotification.add(image);
848                 notificationManager.addNotification(imageInsertFailedNotification);
849         }
850
851         /**
852          * Template provider implementation that uses
853          * {@link WebInterface#createReader(String)} to load templates for
854          * inclusion.
855          *
856          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
857          */
858         private class ClassPathTemplateProvider implements Provider {
859
860                 /** Cache for templates. */
861                 private final Cache<String, Template> templateCache = new MemoryCache<String, Template>(new ValueRetriever<String, Template>() {
862
863                         @Override
864                         @SuppressWarnings("synthetic-access")
865                         public CacheItem<Template> retrieve(String key) throws CacheException {
866                                 Template template = findTemplate(key);
867                                 if (template != null) {
868                                         return new DefaultCacheItem<Template>(template);
869                                 }
870                                 return null;
871                         }
872                 });
873
874                 /**
875                  * {@inheritDoc}
876                  */
877                 @Override
878                 @SuppressWarnings("synthetic-access")
879                 public Template getTemplate(TemplateContext templateContext, String templateName) {
880                         try {
881                                 return templateCache.get(templateName);
882                         } catch (CacheException ce1) {
883                                 logger.log(Level.WARNING, "Could not get template for " + templateName + "!", ce1);
884                                 return null;
885                         }
886                 }
887
888                 /**
889                  * Locates a template in the class path.
890                  *
891                  * @param templateName
892                  *            The name of the template to load
893                  * @return The loaded template, or {@code null} if no template could be
894                  *         found
895                  */
896                 @SuppressWarnings("synthetic-access")
897                 private Template findTemplate(String templateName) {
898                         Reader templateReader = createReader("/templates/" + templateName);
899                         if (templateReader == null) {
900                                 return null;
901                         }
902                         Template template = null;
903                         try {
904                                 template = TemplateParser.parse(templateReader);
905                         } catch (TemplateException te1) {
906                                 logger.log(Level.WARNING, "Could not parse template “" + templateName + "” for inclusion!", te1);
907                         }
908                         return template;
909                 }
910
911         }
912
913 }