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