Only store IDs of Sones in replies.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010–2013 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.core;
19
20 import static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
22
23 import java.net.MalformedURLException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.Set;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.ScheduledExecutorService;
36 import java.util.concurrent.TimeUnit;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
39
40 import net.pterodactylus.sone.core.Options.DefaultOption;
41 import net.pterodactylus.sone.core.Options.Option;
42 import net.pterodactylus.sone.core.Options.OptionWatcher;
43 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
44 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
47 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
48 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
49 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
50 import net.pterodactylus.sone.core.event.PostRemovedEvent;
51 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneLockedEvent;
53 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
55 import net.pterodactylus.sone.data.Album;
56 import net.pterodactylus.sone.data.Client;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.Post;
59 import net.pterodactylus.sone.data.PostBuilder;
60 import net.pterodactylus.sone.data.PostBuilderFactory;
61 import net.pterodactylus.sone.data.PostReply;
62 import net.pterodactylus.sone.data.PostReplyBuilder;
63 import net.pterodactylus.sone.data.PostReplyBuilderFactory;
64 import net.pterodactylus.sone.data.Profile;
65 import net.pterodactylus.sone.data.Profile.Field;
66 import net.pterodactylus.sone.data.Reply;
67 import net.pterodactylus.sone.data.Sone;
68 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
69 import net.pterodactylus.sone.data.Sone.SoneStatus;
70 import net.pterodactylus.sone.data.TemporaryImage;
71 import net.pterodactylus.sone.fcp.FcpInterface;
72 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
73 import net.pterodactylus.sone.freenet.wot.Identity;
74 import net.pterodactylus.sone.freenet.wot.IdentityManager;
75 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
76 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
77 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
78 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
79 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
81 import net.pterodactylus.sone.main.SonePlugin;
82 import net.pterodactylus.sone.utils.IntegerRangePredicate;
83 import net.pterodactylus.util.config.Configuration;
84 import net.pterodactylus.util.config.ConfigurationException;
85 import net.pterodactylus.util.logging.Logging;
86 import net.pterodactylus.util.number.Numbers;
87 import net.pterodactylus.util.service.AbstractService;
88 import net.pterodactylus.util.thread.NamedThreadFactory;
89
90 import com.google.common.base.Predicate;
91 import com.google.common.base.Predicates;
92 import com.google.common.collect.Collections2;
93 import com.google.common.eventbus.EventBus;
94 import com.google.common.eventbus.Subscribe;
95 import com.google.inject.Inject;
96
97 import freenet.keys.FreenetURI;
98
99 /**
100  * The Sone core.
101  *
102  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
103  */
104 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
105
106         /** The logger. */
107         private static final Logger logger = Logging.getLogger(Core.class);
108
109         /** The start time. */
110         private final long startupTime = System.currentTimeMillis();
111
112         /** The options. */
113         private final Options options = new Options();
114
115         /** The preferences. */
116         private final Preferences preferences = new Preferences(options);
117
118         /** The event bus. */
119         private final EventBus eventBus;
120
121         /** The configuration. */
122         private Configuration configuration;
123
124         /** Whether we’re currently saving the configuration. */
125         private boolean storingConfiguration = false;
126
127         /** The identity manager. */
128         private final IdentityManager identityManager;
129
130         /** Interface to freenet. */
131         private final FreenetInterface freenetInterface;
132
133         /** The Sone downloader. */
134         private final SoneDownloader soneDownloader;
135
136         /** The image inserter. */
137         private final ImageInserter imageInserter;
138
139         /** Sone downloader thread-pool. */
140         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
141
142         /** The update checker. */
143         private final UpdateChecker updateChecker;
144
145         /** The trust updater. */
146         private final WebOfTrustUpdater webOfTrustUpdater;
147
148         /** The FCP interface. */
149         private volatile FcpInterface fcpInterface;
150
151         /** The times Sones were followed. */
152         private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
153
154         /** Locked local Sones. */
155         /* synchronize on itself. */
156         private final Set<Sone> lockedSones = new HashSet<Sone>();
157
158         /** Sone inserters. */
159         /* synchronize access on this on sones. */
160         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
161
162         /** Sone rescuers. */
163         /* synchronize access on this on sones. */
164         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
165
166         /** All Sones. */
167         /* synchronize access on this on itself. */
168         private final Map<String, Sone> sones = new HashMap<String, Sone>();
169
170         /** All known Sones. */
171         private final Set<String> knownSones = new HashSet<String>();
172
173         /** The post builder. */
174         private final PostBuilderFactory postBuilderFactory;
175
176         /** All posts. */
177         private final Map<String, Post> posts = new HashMap<String, Post>();
178
179         /** All known posts. */
180         private final Set<String> knownPosts = new HashSet<String>();
181
182         /** The post reply builder factory. */
183         private final PostReplyBuilderFactory postReplyBuilderFactory;
184
185         /** All replies. */
186         private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
187
188         /** All known replies. */
189         private final Set<String> knownReplies = new HashSet<String>();
190
191         /** All bookmarked posts. */
192         /* synchronize access on itself. */
193         private final Set<String> bookmarkedPosts = new HashSet<String>();
194
195         /** Trusted identities, sorted by own identities. */
196         private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
197
198         /** All known albums. */
199         private final Map<String, Album> albums = new HashMap<String, Album>();
200
201         /** All known images. */
202         private final Map<String, Image> images = new HashMap<String, Image>();
203
204         /** All temporary images. */
205         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
206
207         /** Ticker for threads that mark own elements as known. */
208         private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
209
210         /** The time the configuration was last touched. */
211         private volatile long lastConfigurationUpdate;
212
213         /**
214          * Creates a new core.
215          *
216          * @param configuration
217          *            The configuration of the core
218          * @param freenetInterface
219          *            The freenet interface
220          * @param identityManager
221          *            The identity manager
222          * @param webOfTrustUpdater
223          *            The WebOfTrust updater
224          * @param eventBus
225          *            The event bus
226          * @param postBuilderFactory
227          *            The post builder
228          * @param postReplyBuilderFactory
229          *            The post reply builder factory
230          */
231         @Inject
232         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, PostBuilderFactory postBuilderFactory, PostReplyBuilderFactory postReplyBuilderFactory) {
233                 super("Sone Core");
234                 this.configuration = configuration;
235                 this.freenetInterface = freenetInterface;
236                 this.identityManager = identityManager;
237                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
238                 this.imageInserter = new ImageInserter(freenetInterface);
239                 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
240                 this.webOfTrustUpdater = webOfTrustUpdater;
241                 this.eventBus = eventBus;
242                 this.postBuilderFactory = postBuilderFactory;
243                 this.postReplyBuilderFactory = postReplyBuilderFactory;
244         }
245
246         //
247         // ACCESSORS
248         //
249
250         /**
251          * Returns the time Sone was started.
252          *
253          * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
254          */
255         public long getStartupTime() {
256                 return startupTime;
257         }
258
259         /**
260          * Sets the configuration to use. This will automatically save the current
261          * configuration to the given configuration.
262          *
263          * @param configuration
264          *            The new configuration to use
265          */
266         public void setConfiguration(Configuration configuration) {
267                 this.configuration = configuration;
268                 touchConfiguration();
269         }
270
271         /**
272          * Returns the options used by the core.
273          *
274          * @return The options of the core
275          */
276         public Preferences getPreferences() {
277                 return preferences;
278         }
279
280         /**
281          * Returns the identity manager used by the core.
282          *
283          * @return The identity manager
284          */
285         public IdentityManager getIdentityManager() {
286                 return identityManager;
287         }
288
289         /**
290          * Returns the update checker.
291          *
292          * @return The update checker
293          */
294         public UpdateChecker getUpdateChecker() {
295                 return updateChecker;
296         }
297
298         /**
299          * Sets the FCP interface to use.
300          *
301          * @param fcpInterface
302          *            The FCP interface to use
303          */
304         public void setFcpInterface(FcpInterface fcpInterface) {
305                 this.fcpInterface = fcpInterface;
306         }
307
308         /**
309          * Returns the Sone rescuer for the given local Sone.
310          *
311          * @param sone
312          *            The local Sone to get the rescuer for
313          * @return The Sone rescuer for the given Sone
314          */
315         public SoneRescuer getSoneRescuer(Sone sone) {
316                 checkNotNull(sone, "sone must not be null");
317                 checkArgument(sone.isLocal(), "sone must be local");
318                 synchronized (sones) {
319                         SoneRescuer soneRescuer = soneRescuers.get(sone);
320                         if (soneRescuer == null) {
321                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
322                                 soneRescuers.put(sone, soneRescuer);
323                                 soneRescuer.start();
324                         }
325                         return soneRescuer;
326                 }
327         }
328
329         /**
330          * Returns whether the given Sone is currently locked.
331          *
332          * @param sone
333          *            The sone to check
334          * @return {@code true} if the Sone is locked, {@code false} if it is not
335          */
336         public boolean isLocked(Sone sone) {
337                 synchronized (lockedSones) {
338                         return lockedSones.contains(sone);
339                 }
340         }
341
342         /**
343          * Returns all Sones, remote and local.
344          *
345          * @return All Sones
346          */
347         public Set<Sone> getSones() {
348                 return new HashSet<Sone>(sones.values());
349         }
350
351         /**
352          * Returns the Sone with the given ID, regardless whether it’s local or
353          * remote.
354          *
355          * @param id
356          *            The ID of the Sone to get
357          * @return The Sone with the given ID, or {@code null} if there is no such
358          *         Sone
359          */
360         public Sone getSone(String id) {
361                 return getSone(id, true);
362         }
363
364         /**
365          * Returns the Sone with the given ID, regardless whether it’s local or
366          * remote.
367          *
368          * @param id
369          *            The ID of the Sone to get
370          * @param create
371          *            {@code true} to create a new Sone if none exists,
372          *            {@code false} to return {@code null} if a Sone with the given
373          *            ID does not exist
374          * @return The Sone with the given ID, or {@code null} if there is no such
375          *         Sone
376          */
377         @Override
378         public Sone getSone(String id, boolean create) {
379                 synchronized (sones) {
380                         if (!sones.containsKey(id) && create) {
381                                 Sone sone = new Sone(id, false);
382                                 sones.put(id, sone);
383                         }
384                         return sones.get(id);
385                 }
386         }
387
388         /**
389          * Checks whether the core knows a Sone with the given ID.
390          *
391          * @param id
392          *            The ID of the Sone
393          * @return {@code true} if there is a Sone with the given ID, {@code false}
394          *         otherwise
395          */
396         public boolean hasSone(String id) {
397                 synchronized (sones) {
398                         return sones.containsKey(id);
399                 }
400         }
401
402         /**
403          * Returns all local Sones.
404          *
405          * @return All local Sones
406          */
407         public Collection<Sone> getLocalSones() {
408                 synchronized (sones) {
409                         return Collections2.filter(sones.values(), new Predicate<Sone>() {
410
411                                 @Override
412                                 public boolean apply(Sone sone) {
413                                         return sone.isLocal();
414                                 }
415                         });
416                 }
417         }
418
419         /**
420          * Returns the local Sone with the given ID, optionally creating a new Sone.
421          *
422          * @param id
423          *            The ID of the Sone
424          * @param create
425          *            {@code true} to create a new Sone if none exists,
426          *            {@code false} to return null if none exists
427          * @return The Sone with the given ID, or {@code null}
428          */
429         public Sone getLocalSone(String id, boolean create) {
430                 synchronized (sones) {
431                         Sone sone = sones.get(id);
432                         if ((sone == null) && create) {
433                                 sone = new Sone(id, true);
434                                 sones.put(id, sone);
435                         }
436                         if ((sone != null) && !sone.isLocal()) {
437                                 sone = new Sone(id, true);
438                                 sones.put(id, sone);
439                         }
440                         return sone;
441                 }
442         }
443
444         /**
445          * Returns all remote Sones.
446          *
447          * @return All remote Sones
448          */
449         public Collection<Sone> getRemoteSones() {
450                 synchronized (sones) {
451                         return Collections2.filter(sones.values(), new Predicate<Sone>() {
452
453                                 @Override
454                                 public boolean apply(Sone sone) {
455                                         return !sone.isLocal();
456                                 }
457                         });
458                 }
459         }
460
461         /**
462          * Returns the remote Sone with the given ID.
463          *
464          * @param id
465          *            The ID of the remote Sone to get
466          * @param create
467          *            {@code true} to always create a Sone, {@code false} to return
468          *            {@code null} if no Sone with the given ID exists
469          * @return The Sone with the given ID
470          */
471         public Sone getRemoteSone(String id, boolean create) {
472                 synchronized (sones) {
473                         Sone sone = sones.get(id);
474                         if ((sone == null) && create && (id != null) && (id.length() == 43)) {
475                                 sone = new Sone(id, false);
476                                 sones.put(id, sone);
477                         }
478                         return sone;
479                 }
480         }
481
482         /**
483          * Returns whether the given Sone has been modified.
484          *
485          * @param sone
486          *            The Sone to check for modifications
487          * @return {@code true} if a modification has been detected in the Sone,
488          *         {@code false} otherwise
489          */
490         public boolean isModifiedSone(Sone sone) {
491                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
492         }
493
494         /**
495          * Returns the time when the given was first followed by any local Sone.
496          *
497          * @param sone
498          *            The Sone to get the time for
499          * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
500          *         been followed, or {@link Long#MAX_VALUE}
501          */
502         public long getSoneFollowingTime(Sone sone) {
503                 synchronized (soneFollowingTimes) {
504                         if (soneFollowingTimes.containsKey(sone)) {
505                                 return soneFollowingTimes.get(sone);
506                         }
507                         return Long.MAX_VALUE;
508                 }
509         }
510
511         /**
512          * Returns whether the target Sone is trusted by the origin Sone.
513          *
514          * @param origin
515          *            The origin Sone
516          * @param target
517          *            The target Sone
518          * @return {@code true} if the target Sone is trusted by the origin Sone
519          */
520         public boolean isSoneTrusted(Sone origin, Sone target) {
521                 checkNotNull(origin, "origin must not be null");
522                 checkNotNull(target, "target must not be null");
523                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
524                 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
525         }
526
527         /**
528          * Returns a post builder.
529          *
530          * @return A new post builder
531          */
532         public PostBuilder postBuilder() {
533                 return postBuilderFactory.newPostBuilder();
534         }
535
536         /**
537          * {@inheritDoc}
538          */
539         @Override
540         public Post getPost(String postId) {
541                 synchronized (posts) {
542                         return posts.get(postId);
543                 }
544         }
545
546         /**
547          * Returns all posts that have the given Sone as recipient.
548          *
549          * @see Post#getRecipient()
550          * @param recipient
551          *            The recipient of the posts
552          * @return All posts that have the given Sone as recipient
553          */
554         public Set<Post> getDirectedPosts(Sone recipient) {
555                 checkNotNull(recipient, "recipient must not be null");
556                 Set<Post> directedPosts = new HashSet<Post>();
557                 synchronized (posts) {
558                         for (Post post : posts.values()) {
559                                 if (recipient.equals(post.getRecipient())) {
560                                         directedPosts.add(post);
561                                 }
562                         }
563                 }
564                 return directedPosts;
565         }
566
567         /**
568          * Returns a post reply builder.
569          *
570          * @return A new post reply builder
571          */
572         public PostReplyBuilder postReplyBuilder() {
573                 return postReplyBuilderFactory.newPostReplyBuilder();
574         }
575
576         /**
577          * {@inheritDoc}
578          */
579         @Override
580         public PostReply getPostReply(String replyId) {
581                 synchronized (replies) {
582                         return replies.get(replyId);
583                 }
584         }
585
586         /**
587          * {@inheritDoc}
588          */
589         @Override
590         public List<PostReply> getReplies(Post post) {
591                 Set<Sone> sones = getSones();
592                 List<PostReply> replies = new ArrayList<PostReply>();
593                 for (Sone sone : sones) {
594                         for (PostReply reply : sone.getReplies()) {
595                                 if (reply.getPost().equals(post)) {
596                                         replies.add(reply);
597                                 }
598                         }
599                 }
600                 Collections.sort(replies, Reply.TIME_COMPARATOR);
601                 return replies;
602         }
603
604         /**
605          * Returns all Sones that have liked the given post.
606          *
607          * @param post
608          *            The post to get the liking Sones for
609          * @return The Sones that like the given post
610          */
611         public Set<Sone> getLikes(Post post) {
612                 Set<Sone> sones = new HashSet<Sone>();
613                 for (Sone sone : getSones()) {
614                         if (sone.getLikedPostIds().contains(post.getId())) {
615                                 sones.add(sone);
616                         }
617                 }
618                 return sones;
619         }
620
621         /**
622          * Returns all Sones that have liked the given reply.
623          *
624          * @param reply
625          *            The reply to get the liking Sones for
626          * @return The Sones that like the given reply
627          */
628         public Set<Sone> getLikes(PostReply reply) {
629                 Set<Sone> sones = new HashSet<Sone>();
630                 for (Sone sone : getSones()) {
631                         if (sone.getLikedReplyIds().contains(reply.getId())) {
632                                 sones.add(sone);
633                         }
634                 }
635                 return sones;
636         }
637
638         /**
639          * Returns whether the given post is bookmarked.
640          *
641          * @param post
642          *            The post to check
643          * @return {@code true} if the given post is bookmarked, {@code false}
644          *         otherwise
645          */
646         public boolean isBookmarked(Post post) {
647                 return isPostBookmarked(post.getId());
648         }
649
650         /**
651          * Returns whether the post with the given ID is bookmarked.
652          *
653          * @param id
654          *            The ID of the post to check
655          * @return {@code true} if the post with the given ID is bookmarked,
656          *         {@code false} otherwise
657          */
658         public boolean isPostBookmarked(String id) {
659                 synchronized (bookmarkedPosts) {
660                         return bookmarkedPosts.contains(id);
661                 }
662         }
663
664         /**
665          * Returns all currently known bookmarked posts.
666          *
667          * @return All bookmarked posts
668          */
669         public Set<Post> getBookmarkedPosts() {
670                 Set<Post> posts = new HashSet<Post>();
671                 synchronized (bookmarkedPosts) {
672                         for (String bookmarkedPostId : bookmarkedPosts) {
673                                 Post post = getPost(bookmarkedPostId);
674                                 if (post != null) {
675                                         posts.add(post);
676                                 }
677                         }
678                 }
679                 return posts;
680         }
681
682         /**
683          * Returns the album with the given ID, creating a new album if no album
684          * with the given ID can be found.
685          *
686          * @param albumId
687          *            The ID of the album
688          * @return The album with the given ID
689          */
690         public Album getAlbum(String albumId) {
691                 return getAlbum(albumId, true);
692         }
693
694         /**
695          * Returns the album with the given ID, optionally creating a new album if
696          * an album with the given ID can not be found.
697          *
698          * @param albumId
699          *            The ID of the album
700          * @param create
701          *            {@code true} to create a new album if none exists for the
702          *            given ID
703          * @return The album with the given ID, or {@code null} if no album with the
704          *         given ID exists and {@code create} is {@code false}
705          */
706         public Album getAlbum(String albumId, boolean create) {
707                 synchronized (albums) {
708                         Album album = albums.get(albumId);
709                         if (create && (album == null)) {
710                                 album = new Album(albumId);
711                                 albums.put(albumId, album);
712                         }
713                         return album;
714                 }
715         }
716
717         /**
718          * Returns the image with the given ID, creating it if necessary.
719          *
720          * @param imageId
721          *            The ID of the image
722          * @return The image with the given ID
723          */
724         public Image getImage(String imageId) {
725                 return getImage(imageId, true);
726         }
727
728         /**
729          * Returns the image with the given ID, optionally creating it if it does
730          * not exist.
731          *
732          * @param imageId
733          *            The ID of the image
734          * @param create
735          *            {@code true} to create an image if none exists with the given
736          *            ID
737          * @return The image with the given ID, or {@code null} if none exists and
738          *         none was created
739          */
740         public Image getImage(String imageId, boolean create) {
741                 synchronized (images) {
742                         Image image = images.get(imageId);
743                         if (create && (image == null)) {
744                                 image = new Image(imageId);
745                                 images.put(imageId, image);
746                         }
747                         return image;
748                 }
749         }
750
751         /**
752          * Returns the temporary image with the given ID.
753          *
754          * @param imageId
755          *            The ID of the temporary image
756          * @return The temporary image, or {@code null} if there is no temporary
757          *         image with the given ID
758          */
759         public TemporaryImage getTemporaryImage(String imageId) {
760                 synchronized (temporaryImages) {
761                         return temporaryImages.get(imageId);
762                 }
763         }
764
765         //
766         // ACTIONS
767         //
768
769         /**
770          * Locks the given Sone. A locked Sone will not be inserted by
771          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
772          * again.
773          *
774          * @param sone
775          *            The sone to lock
776          */
777         public void lockSone(Sone sone) {
778                 synchronized (lockedSones) {
779                         if (lockedSones.add(sone)) {
780                                 eventBus.post(new SoneLockedEvent(sone));
781                         }
782                 }
783         }
784
785         /**
786          * Unlocks the given Sone.
787          *
788          * @see #lockSone(Sone)
789          * @param sone
790          *            The sone to unlock
791          */
792         public void unlockSone(Sone sone) {
793                 synchronized (lockedSones) {
794                         if (lockedSones.remove(sone)) {
795                                 eventBus.post(new SoneUnlockedEvent(sone));
796                         }
797                 }
798         }
799
800         /**
801          * Adds a local Sone from the given own identity.
802          *
803          * @param ownIdentity
804          *            The own identity to create a Sone from
805          * @return The added (or already existing) Sone
806          */
807         public Sone addLocalSone(OwnIdentity ownIdentity) {
808                 if (ownIdentity == null) {
809                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
810                         return null;
811                 }
812                 synchronized (sones) {
813                         final Sone sone;
814                         try {
815                                 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
816                         } catch (MalformedURLException mue1) {
817                                 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
818                                 return null;
819                         }
820                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
821                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
822                         sone.setKnown(true);
823                         /* TODO - load posts ’n stuff */
824                         sones.put(ownIdentity.getId(), sone);
825                         final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
826                         soneInserters.put(sone, soneInserter);
827                         sone.setStatus(SoneStatus.idle);
828                         loadSone(sone);
829                         soneInserter.start();
830                         return sone;
831                 }
832         }
833
834         /**
835          * Creates a new Sone for the given own identity.
836          *
837          * @param ownIdentity
838          *            The own identity to create a Sone for
839          * @return The created Sone
840          */
841         public Sone createSone(OwnIdentity ownIdentity) {
842                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
843                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
844                         return null;
845                 }
846                 Sone sone = addLocalSone(ownIdentity);
847                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
848                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
849                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
850                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
851                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
852                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
853
854                 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
855                 touchConfiguration();
856                 return sone;
857         }
858
859         /**
860          * Adds the Sone of the given identity.
861          *
862          * @param identity
863          *            The identity whose Sone to add
864          * @return The added or already existing Sone
865          */
866         public Sone addRemoteSone(Identity identity) {
867                 if (identity == null) {
868                         logger.log(Level.WARNING, "Given Identity is null!");
869                         return null;
870                 }
871                 synchronized (sones) {
872                         final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
873                         boolean newSone = sone.getRequestUri() == null;
874                         sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
875                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
876                         if (newSone) {
877                                 synchronized (knownSones) {
878                                         newSone = !knownSones.contains(sone.getId());
879                                 }
880                                 sone.setKnown(!newSone);
881                                 if (newSone) {
882                                         eventBus.post(new NewSoneFoundEvent(sone));
883                                         for (Sone localSone : getLocalSones()) {
884                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
885                                                         followSone(localSone, sone);
886                                                 }
887                                         }
888                                 }
889                         }
890                         soneDownloader.addSone(sone);
891                         soneDownloaders.execute(new Runnable() {
892
893                                 @Override
894                                 @SuppressWarnings("synthetic-access")
895                                 public void run() {
896                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
897                                 }
898
899                         });
900                         return sone;
901                 }
902         }
903
904         /**
905          * Lets the given local Sone follow the Sone with the given ID.
906          *
907          * @param sone
908          *            The local Sone that should follow another Sone
909          * @param soneId
910          *            The ID of the Sone to follow
911          */
912         public void followSone(Sone sone, String soneId) {
913                 checkNotNull(sone, "sone must not be null");
914                 checkNotNull(soneId, "soneId must not be null");
915                 Sone followedSone = getSone(soneId, true);
916                 if (followedSone == null) {
917                         logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
918                         return;
919                 }
920                 followSone(sone, getSone(soneId));
921         }
922
923         /**
924          * Lets the given local Sone follow the other given Sone. If the given Sone
925          * was not followed by any local Sone before, this will mark all elements of
926          * the followed Sone as read that have been created before the current
927          * moment.
928          *
929          * @param sone
930          *            The local Sone that should follow the other Sone
931          * @param followedSone
932          *            The Sone that should be followed
933          */
934         public void followSone(Sone sone, Sone followedSone) {
935                 checkNotNull(sone, "sone must not be null");
936                 checkNotNull(followedSone, "followedSone must not be null");
937                 sone.addFriend(followedSone.getId());
938                 synchronized (soneFollowingTimes) {
939                         if (!soneFollowingTimes.containsKey(followedSone)) {
940                                 long now = System.currentTimeMillis();
941                                 soneFollowingTimes.put(followedSone, now);
942                                 for (Post post : followedSone.getPosts()) {
943                                         if (post.getTime() < now) {
944                                                 markPostKnown(post);
945                                         }
946                                 }
947                                 for (PostReply reply : followedSone.getReplies()) {
948                                         if (reply.getTime() < now) {
949                                                 markReplyKnown(reply);
950                                         }
951                                 }
952                         }
953                 }
954                 touchConfiguration();
955         }
956
957         /**
958          * Lets the given local Sone unfollow the Sone with the given ID.
959          *
960          * @param sone
961          *            The local Sone that should unfollow another Sone
962          * @param soneId
963          *            The ID of the Sone being unfollowed
964          */
965         public void unfollowSone(Sone sone, String soneId) {
966                 checkNotNull(sone, "sone must not be null");
967                 checkNotNull(soneId, "soneId must not be null");
968                 unfollowSone(sone, getSone(soneId, false));
969         }
970
971         /**
972          * Lets the given local Sone unfollow the other given Sone. If the given
973          * local Sone is the last local Sone that followed the given Sone, its
974          * following time will be removed.
975          *
976          * @param sone
977          *            The local Sone that should unfollow another Sone
978          * @param unfollowedSone
979          *            The Sone being unfollowed
980          */
981         public void unfollowSone(Sone sone, Sone unfollowedSone) {
982                 checkNotNull(sone, "sone must not be null");
983                 checkNotNull(unfollowedSone, "unfollowedSone must not be null");
984                 sone.removeFriend(unfollowedSone.getId());
985                 boolean unfollowedSoneStillFollowed = false;
986                 for (Sone localSone : getLocalSones()) {
987                         unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
988                 }
989                 if (!unfollowedSoneStillFollowed) {
990                         synchronized (soneFollowingTimes) {
991                                 soneFollowingTimes.remove(unfollowedSone);
992                         }
993                 }
994                 touchConfiguration();
995         }
996
997         /**
998          * Sets the trust value of the given origin Sone for the target Sone.
999          *
1000          * @param origin
1001          *            The origin Sone
1002          * @param target
1003          *            The target Sone
1004          * @param trustValue
1005          *            The trust value (from {@code -100} to {@code 100})
1006          */
1007         public void setTrust(Sone origin, Sone target, int trustValue) {
1008                 checkNotNull(origin, "origin must not be null");
1009                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1010                 checkNotNull(target, "target must not be null");
1011                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
1012                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1013         }
1014
1015         /**
1016          * Removes any trust assignment for the given target Sone.
1017          *
1018          * @param origin
1019          *            The trust origin
1020          * @param target
1021          *            The trust target
1022          */
1023         public void removeTrust(Sone origin, Sone target) {
1024                 checkNotNull(origin, "origin must not be null");
1025                 checkNotNull(target, "target must not be null");
1026                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1027                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1028         }
1029
1030         /**
1031          * Assigns the configured positive trust value for the given target.
1032          *
1033          * @param origin
1034          *            The trust origin
1035          * @param target
1036          *            The trust target
1037          */
1038         public void trustSone(Sone origin, Sone target) {
1039                 setTrust(origin, target, preferences.getPositiveTrust());
1040         }
1041
1042         /**
1043          * Assigns the configured negative trust value for the given target.
1044          *
1045          * @param origin
1046          *            The trust origin
1047          * @param target
1048          *            The trust target
1049          */
1050         public void distrustSone(Sone origin, Sone target) {
1051                 setTrust(origin, target, preferences.getNegativeTrust());
1052         }
1053
1054         /**
1055          * Removes the trust assignment for the given target.
1056          *
1057          * @param origin
1058          *            The trust origin
1059          * @param target
1060          *            The trust target
1061          */
1062         public void untrustSone(Sone origin, Sone target) {
1063                 removeTrust(origin, target);
1064         }
1065
1066         /**
1067          * Updates the stored Sone with the given Sone.
1068          *
1069          * @param sone
1070          *            The updated Sone
1071          */
1072         public void updateSone(Sone sone) {
1073                 updateSone(sone, false);
1074         }
1075
1076         /**
1077          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1078          * {@code true}, an older Sone than the current Sone can be given to restore
1079          * an old state.
1080          *
1081          * @param sone
1082          *            The Sone to update
1083          * @param soneRescueMode
1084          *            {@code true} if the stored Sone should be updated regardless
1085          *            of the age of the given Sone
1086          */
1087         public void updateSone(Sone sone, boolean soneRescueMode) {
1088                 if (hasSone(sone.getId())) {
1089                         Sone storedSone = getSone(sone.getId());
1090                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1091                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1092                                 return;
1093                         }
1094                         synchronized (posts) {
1095                                 if (!soneRescueMode) {
1096                                         for (Post post : storedSone.getPosts()) {
1097                                                 posts.remove(post.getId());
1098                                                 if (!sone.getPosts().contains(post)) {
1099                                                         eventBus.post(new PostRemovedEvent(post));
1100                                                 }
1101                                         }
1102                                 }
1103                                 List<Post> storedPosts = storedSone.getPosts();
1104                                 synchronized (knownPosts) {
1105                                         for (Post post : sone.getPosts()) {
1106                                                 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1107                                                 postBuilder.copyPost(post).from(storedSone.getId());
1108                                                 Post newPost = postBuilder.build().setKnown(knownPosts.contains(post.getId()));
1109                                                 if (!storedPosts.contains(newPost)) {
1110                                                         if (newPost.getTime() < getSoneFollowingTime(sone)) {
1111                                                                 knownPosts.add(newPost.getId());
1112                                                                 newPost.setKnown(true);
1113                                                         } else if (!knownPosts.contains(newPost.getId())) {
1114                                                                 eventBus.post(new NewPostFoundEvent(newPost));
1115                                                         }
1116                                                 }
1117                                                 posts.put(newPost.getId(), newPost);
1118                                         }
1119                                 }
1120                         }
1121                         synchronized (replies) {
1122                                 if (!soneRescueMode) {
1123                                         for (PostReply reply : storedSone.getReplies()) {
1124                                                 replies.remove(reply.getId());
1125                                                 if (!sone.getReplies().contains(reply)) {
1126                                                         eventBus.post(new PostReplyRemovedEvent(reply));
1127                                                 }
1128                                         }
1129                                 }
1130                                 Set<PostReply> storedReplies = storedSone.getReplies();
1131                                 synchronized (knownReplies) {
1132                                         for (PostReply reply : sone.getReplies()) {
1133                                                 reply.setKnown(knownReplies.contains(reply.getId()));
1134                                                 if (!storedReplies.contains(reply)) {
1135                                                         if (reply.getTime() < getSoneFollowingTime(sone)) {
1136                                                                 knownReplies.add(reply.getId());
1137                                                                 reply.setKnown(true);
1138                                                         } else if (!knownReplies.contains(reply.getId())) {
1139                                                                 eventBus.post(new NewPostReplyFoundEvent(reply));
1140                                                         }
1141                                                 }
1142                                                 replies.put(reply.getId(), reply);
1143                                         }
1144                                 }
1145                         }
1146                         synchronized (albums) {
1147                                 synchronized (images) {
1148                                         for (Album album : storedSone.getAlbums()) {
1149                                                 albums.remove(album.getId());
1150                                                 for (Image image : album.getImages()) {
1151                                                         images.remove(image.getId());
1152                                                 }
1153                                         }
1154                                         for (Album album : sone.getAlbums()) {
1155                                                 albums.put(album.getId(), album);
1156                                                 for (Image image : album.getImages()) {
1157                                                         images.put(image.getId(), image);
1158                                                 }
1159                                         }
1160                                 }
1161                         }
1162                         synchronized (storedSone) {
1163                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1164                                         storedSone.setTime(sone.getTime());
1165                                 }
1166                                 storedSone.setClient(sone.getClient());
1167                                 storedSone.setProfile(sone.getProfile());
1168                                 if (soneRescueMode) {
1169                                         for (Post post : sone.getPosts()) {
1170                                                 storedSone.addPost(post);
1171                                         }
1172                                         for (PostReply reply : sone.getReplies()) {
1173                                                 storedSone.addReply(reply);
1174                                         }
1175                                         for (String likedPostId : sone.getLikedPostIds()) {
1176                                                 storedSone.addLikedPostId(likedPostId);
1177                                         }
1178                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1179                                                 storedSone.addLikedReplyId(likedReplyId);
1180                                         }
1181                                         for (Album album : sone.getAlbums()) {
1182                                                 storedSone.addAlbum(album);
1183                                         }
1184                                 } else {
1185                                         storedSone.setPosts(sone.getPosts());
1186                                         storedSone.setReplies(sone.getReplies());
1187                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1188                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1189                                         storedSone.setAlbums(sone.getAlbums());
1190                                 }
1191                                 storedSone.setLatestEdition(sone.getLatestEdition());
1192                         }
1193                 }
1194         }
1195
1196         /**
1197          * Deletes the given Sone. This will remove the Sone from the
1198          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1199          * remove the context from its identity.
1200          *
1201          * @param sone
1202          *            The Sone to delete
1203          */
1204         public void deleteSone(Sone sone) {
1205                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1206                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1207                         return;
1208                 }
1209                 synchronized (sones) {
1210                         if (!getLocalSones().contains(sone)) {
1211                                 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1212                                 return;
1213                         }
1214                         sones.remove(sone.getId());
1215                         SoneInserter soneInserter = soneInserters.remove(sone);
1216                         soneInserter.stop();
1217                 }
1218                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1219                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1220                 try {
1221                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1222                 } catch (ConfigurationException ce1) {
1223                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1224                 }
1225         }
1226
1227         /**
1228          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1229          * known} before, a {@link MarkSoneKnownEvent} is fired.
1230          *
1231          * @param sone
1232          *            The Sone to mark as known
1233          */
1234         public void markSoneKnown(Sone sone) {
1235                 if (!sone.isKnown()) {
1236                         sone.setKnown(true);
1237                         synchronized (knownSones) {
1238                                 knownSones.add(sone.getId());
1239                         }
1240                         eventBus.post(new MarkSoneKnownEvent(sone));
1241                         touchConfiguration();
1242                 }
1243         }
1244
1245         /**
1246          * Loads and updates the given Sone from the configuration. If any error is
1247          * encountered, loading is aborted and the given Sone is not changed.
1248          *
1249          * @param sone
1250          *            The Sone to load and update
1251          */
1252         public void loadSone(Sone sone) {
1253                 if (!sone.isLocal()) {
1254                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1255                         return;
1256                 }
1257
1258                 /* initialize options. */
1259                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1260                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1261                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1262                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1263                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1264                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1265
1266                 /* load Sone. */
1267                 String sonePrefix = "Sone/" + sone.getId();
1268                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1269                 if (soneTime == null) {
1270                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1271                         return;
1272                 }
1273                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1274
1275                 /* load profile. */
1276                 Profile profile = new Profile(sone);
1277                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1278                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1279                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1280                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1281                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1282                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1283
1284                 /* load profile fields. */
1285                 while (true) {
1286                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1287                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1288                         if (fieldName == null) {
1289                                 break;
1290                         }
1291                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1292                         profile.addField(fieldName).setValue(fieldValue);
1293                 }
1294
1295                 /* load posts. */
1296                 Set<Post> posts = new HashSet<Post>();
1297                 while (true) {
1298                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1299                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1300                         if (postId == null) {
1301                                 break;
1302                         }
1303                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1304                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1305                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1306                         if ((postTime == 0) || (postText == null)) {
1307                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1308                                 return;
1309                         }
1310                         PostBuilder postBuilder = postBuilderFactory.newPostBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1311                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1312                                 postBuilder.to(postRecipientId);
1313                         }
1314                         posts.add(postBuilder.build());
1315                 }
1316
1317                 /* load replies. */
1318                 Set<PostReply> replies = new HashSet<PostReply>();
1319                 while (true) {
1320                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1321                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1322                         if (replyId == null) {
1323                                 break;
1324                         }
1325                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1326                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1327                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1328                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1329                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1330                                 return;
1331                         }
1332                         PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1333                         postReplyBuilder.withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1334                         replies.add(postReplyBuilder.build());
1335                 }
1336
1337                 /* load post likes. */
1338                 Set<String> likedPostIds = new HashSet<String>();
1339                 while (true) {
1340                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1341                         if (likedPostId == null) {
1342                                 break;
1343                         }
1344                         likedPostIds.add(likedPostId);
1345                 }
1346
1347                 /* load reply likes. */
1348                 Set<String> likedReplyIds = new HashSet<String>();
1349                 while (true) {
1350                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1351                         if (likedReplyId == null) {
1352                                 break;
1353                         }
1354                         likedReplyIds.add(likedReplyId);
1355                 }
1356
1357                 /* load friends. */
1358                 Set<String> friends = new HashSet<String>();
1359                 while (true) {
1360                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1361                         if (friendId == null) {
1362                                 break;
1363                         }
1364                         friends.add(friendId);
1365                 }
1366
1367                 /* load albums. */
1368                 List<Album> topLevelAlbums = new ArrayList<Album>();
1369                 int albumCounter = 0;
1370                 while (true) {
1371                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1372                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1373                         if (albumId == null) {
1374                                 break;
1375                         }
1376                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1377                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1378                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1379                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1380                         if ((albumTitle == null) || (albumDescription == null)) {
1381                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1382                                 return;
1383                         }
1384                         Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1385                         if (albumParentId != null) {
1386                                 Album parentAlbum = getAlbum(albumParentId, false);
1387                                 if (parentAlbum == null) {
1388                                         logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1389                                         return;
1390                                 }
1391                                 parentAlbum.addAlbum(album);
1392                         } else {
1393                                 if (!topLevelAlbums.contains(album)) {
1394                                         topLevelAlbums.add(album);
1395                                 }
1396                         }
1397                 }
1398
1399                 /* load images. */
1400                 int imageCounter = 0;
1401                 while (true) {
1402                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1403                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1404                         if (imageId == null) {
1405                                 break;
1406                         }
1407                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1408                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1409                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1410                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1411                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1412                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1413                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1414                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1415                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1416                                 return;
1417                         }
1418                         Album album = getAlbum(albumId, false);
1419                         if (album == null) {
1420                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1421                                 return;
1422                         }
1423                         Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1424                         image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1425                         album.addImage(image);
1426                 }
1427
1428                 /* load avatar. */
1429                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1430                 if (avatarId != null) {
1431                         profile.setAvatar(getImage(avatarId, false));
1432                 }
1433
1434                 /* load options. */
1435                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1436                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1437                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1438                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1439                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1440                 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1441
1442                 /* if we’re still here, Sone was loaded successfully. */
1443                 synchronized (sone) {
1444                         sone.setTime(soneTime);
1445                         sone.setProfile(profile);
1446                         sone.setPosts(posts);
1447                         sone.setReplies(replies);
1448                         sone.setLikePostIds(likedPostIds);
1449                         sone.setLikeReplyIds(likedReplyIds);
1450                         for (String friendId : friends) {
1451                                 followSone(sone, friendId);
1452                         }
1453                         sone.setAlbums(topLevelAlbums);
1454                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1455                 }
1456                 synchronized (knownSones) {
1457                         for (String friend : friends) {
1458                                 knownSones.add(friend);
1459                         }
1460                 }
1461                 synchronized (knownPosts) {
1462                         for (Post post : posts) {
1463                                 knownPosts.add(post.getId());
1464                         }
1465                 }
1466                 synchronized (knownReplies) {
1467                         for (PostReply reply : replies) {
1468                                 knownReplies.add(reply.getId());
1469                         }
1470                 }
1471         }
1472
1473         /**
1474          * Creates a new post.
1475          *
1476          * @param sone
1477          *            The Sone that creates the post
1478          * @param text
1479          *            The text of the post
1480          * @return The created post
1481          */
1482         public Post createPost(Sone sone, String text) {
1483                 return createPost(sone, System.currentTimeMillis(), text);
1484         }
1485
1486         /**
1487          * Creates a new post.
1488          *
1489          * @param sone
1490          *            The Sone that creates the post
1491          * @param time
1492          *            The time of the post
1493          * @param text
1494          *            The text of the post
1495          * @return The created post
1496          */
1497         public Post createPost(Sone sone, long time, String text) {
1498                 return createPost(sone, null, time, text);
1499         }
1500
1501         /**
1502          * Creates a new post.
1503          *
1504          * @param sone
1505          *            The Sone that creates the post
1506          * @param recipient
1507          *            The recipient Sone, or {@code null} if this post does not have
1508          *            a recipient
1509          * @param text
1510          *            The text of the post
1511          * @return The created post
1512          */
1513         public Post createPost(Sone sone, Sone recipient, String text) {
1514                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1515         }
1516
1517         /**
1518          * Creates a new post.
1519          *
1520          * @param sone
1521          *            The Sone that creates the post
1522          * @param recipient
1523          *            The recipient Sone, or {@code null} if this post does not have
1524          *            a recipient
1525          * @param time
1526          *            The time of the post
1527          * @param text
1528          *            The text of the post
1529          * @return The created post
1530          */
1531         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1532                 checkNotNull(text, "text must not be null");
1533                 checkArgument(text.trim().length() > 0, "text must not be empty");
1534                 if (!sone.isLocal()) {
1535                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1536                         return null;
1537                 }
1538                 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1539                 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1540                 if (recipient != null) {
1541                         postBuilder.to(recipient.getId());
1542                 }
1543                 final Post post = postBuilder.build();
1544                 synchronized (posts) {
1545                         posts.put(post.getId(), post);
1546                 }
1547                 eventBus.post(new NewPostFoundEvent(post));
1548                 sone.addPost(post);
1549                 touchConfiguration();
1550                 localElementTicker.schedule(new Runnable() {
1551
1552                         /**
1553                          * {@inheritDoc}
1554                          */
1555                         @Override
1556                         public void run() {
1557                                 markPostKnown(post);
1558                         }
1559                 }, 10, TimeUnit.SECONDS);
1560                 return post;
1561         }
1562
1563         /**
1564          * Deletes the given post.
1565          *
1566          * @param post
1567          *            The post to delete
1568          */
1569         public void deletePost(Post post) {
1570                 if (!post.getSone().isLocal()) {
1571                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1572                         return;
1573                 }
1574                 post.getSone().removePost(post);
1575                 synchronized (posts) {
1576                         posts.remove(post.getId());
1577                 }
1578                 eventBus.post(new PostRemovedEvent(post));
1579                 markPostKnown(post);
1580                 touchConfiguration();
1581         }
1582
1583         /**
1584          * Marks the given post as known, if it is currently not a known post
1585          * (according to {@link Post#isKnown()}).
1586          *
1587          * @param post
1588          *            The post to mark as known
1589          */
1590         public void markPostKnown(Post post) {
1591                 post.setKnown(true);
1592                 synchronized (knownPosts) {
1593                         eventBus.post(new MarkPostKnownEvent(post));
1594                         if (knownPosts.add(post.getId())) {
1595                                 touchConfiguration();
1596                         }
1597                 }
1598                 for (PostReply reply : getReplies(post)) {
1599                         markReplyKnown(reply);
1600                 }
1601         }
1602
1603         /**
1604          * Bookmarks the given post.
1605          *
1606          * @param post
1607          *            The post to bookmark
1608          */
1609         public void bookmark(Post post) {
1610                 bookmarkPost(post.getId());
1611         }
1612
1613         /**
1614          * Bookmarks the post with the given ID.
1615          *
1616          * @param id
1617          *            The ID of the post to bookmark
1618          */
1619         public void bookmarkPost(String id) {
1620                 synchronized (bookmarkedPosts) {
1621                         bookmarkedPosts.add(id);
1622                 }
1623         }
1624
1625         /**
1626          * Removes the given post from the bookmarks.
1627          *
1628          * @param post
1629          *            The post to unbookmark
1630          */
1631         public void unbookmark(Post post) {
1632                 unbookmarkPost(post.getId());
1633         }
1634
1635         /**
1636          * Removes the post with the given ID from the bookmarks.
1637          *
1638          * @param id
1639          *            The ID of the post to unbookmark
1640          */
1641         public void unbookmarkPost(String id) {
1642                 synchronized (bookmarkedPosts) {
1643                         bookmarkedPosts.remove(id);
1644                 }
1645         }
1646
1647         /**
1648          * Creates a new reply.
1649          *
1650          * @param sone
1651          *            The Sone that creates the reply
1652          * @param post
1653          *            The post that this reply refers to
1654          * @param text
1655          *            The text of the reply
1656          * @return The created reply
1657          */
1658         public PostReply createReply(Sone sone, Post post, String text) {
1659                 checkNotNull(text, "text must not be null");
1660                 checkArgument(text.trim().length() > 0, "text must not be empty");
1661                 if (!sone.isLocal()) {
1662                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1663                         return null;
1664                 }
1665                 PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1666                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1667                 final PostReply reply = postReplyBuilder.build();
1668                 synchronized (replies) {
1669                         replies.put(reply.getId(), reply);
1670                 }
1671                 synchronized (knownReplies) {
1672                         eventBus.post(new NewPostReplyFoundEvent(reply));
1673                 }
1674                 sone.addReply(reply);
1675                 touchConfiguration();
1676                 localElementTicker.schedule(new Runnable() {
1677
1678                         /**
1679                          * {@inheritDoc}
1680                          */
1681                         @Override
1682                         public void run() {
1683                                 markReplyKnown(reply);
1684                         }
1685                 }, 10, TimeUnit.SECONDS);
1686                 return reply;
1687         }
1688
1689         /**
1690          * Deletes the given reply.
1691          *
1692          * @param reply
1693          *            The reply to delete
1694          */
1695         public void deleteReply(PostReply reply) {
1696                 Sone sone = reply.getSone();
1697                 if (!sone.isLocal()) {
1698                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1699                         return;
1700                 }
1701                 synchronized (replies) {
1702                         replies.remove(reply.getId());
1703                 }
1704                 synchronized (knownReplies) {
1705                         markReplyKnown(reply);
1706                         knownReplies.remove(reply.getId());
1707                 }
1708                 sone.removeReply(reply);
1709                 touchConfiguration();
1710         }
1711
1712         /**
1713          * Marks the given reply as known, if it is currently not a known reply
1714          * (according to {@link Reply#isKnown()}).
1715          *
1716          * @param reply
1717          *            The reply to mark as known
1718          */
1719         public void markReplyKnown(PostReply reply) {
1720                 reply.setKnown(true);
1721                 synchronized (knownReplies) {
1722                         eventBus.post(new MarkPostReplyKnownEvent(reply));
1723                         if (knownReplies.add(reply.getId())) {
1724                                 touchConfiguration();
1725                         }
1726                 }
1727         }
1728
1729         /**
1730          * Creates a new top-level album for the given Sone.
1731          *
1732          * @param sone
1733          *            The Sone to create the album for
1734          * @return The new album
1735          */
1736         public Album createAlbum(Sone sone) {
1737                 return createAlbum(sone, null);
1738         }
1739
1740         /**
1741          * Creates a new album for the given Sone.
1742          *
1743          * @param sone
1744          *            The Sone to create the album for
1745          * @param parent
1746          *            The parent of the album (may be {@code null} to create a
1747          *            top-level album)
1748          * @return The new album
1749          */
1750         public Album createAlbum(Sone sone, Album parent) {
1751                 Album album = new Album();
1752                 synchronized (albums) {
1753                         albums.put(album.getId(), album);
1754                 }
1755                 album.setSone(sone);
1756                 if (parent != null) {
1757                         parent.addAlbum(album);
1758                 } else {
1759                         sone.addAlbum(album);
1760                 }
1761                 return album;
1762         }
1763
1764         /**
1765          * Deletes the given album. The owner of the album has to be a local Sone,
1766          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1767          *
1768          * @param album
1769          *            The album to remove
1770          */
1771         public void deleteAlbum(Album album) {
1772                 checkNotNull(album, "album must not be null");
1773                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1774                 if (!album.isEmpty()) {
1775                         return;
1776                 }
1777                 if (album.getParent() == null) {
1778                         album.getSone().removeAlbum(album);
1779                 } else {
1780                         album.getParent().removeAlbum(album);
1781                 }
1782                 synchronized (albums) {
1783                         albums.remove(album.getId());
1784                 }
1785                 touchConfiguration();
1786         }
1787
1788         /**
1789          * Creates a new image.
1790          *
1791          * @param sone
1792          *            The Sone creating the image
1793          * @param album
1794          *            The album the image will be inserted into
1795          * @param temporaryImage
1796          *            The temporary image to create the image from
1797          * @return The newly created image
1798          */
1799         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1800                 checkNotNull(sone, "sone must not be null");
1801                 checkNotNull(album, "album must not be null");
1802                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1803                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1804                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1805                 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1806                 album.addImage(image);
1807                 synchronized (images) {
1808                         images.put(image.getId(), image);
1809                 }
1810                 imageInserter.insertImage(temporaryImage, image);
1811                 return image;
1812         }
1813
1814         /**
1815          * Deletes the given image. This method will also delete a matching
1816          * temporary image.
1817          *
1818          * @see #deleteTemporaryImage(TemporaryImage)
1819          * @param image
1820          *            The image to delete
1821          */
1822         public void deleteImage(Image image) {
1823                 checkNotNull(image, "image must not be null");
1824                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1825                 deleteTemporaryImage(image.getId());
1826                 image.getAlbum().removeImage(image);
1827                 synchronized (images) {
1828                         images.remove(image.getId());
1829                 }
1830                 touchConfiguration();
1831         }
1832
1833         /**
1834          * Creates a new temporary image.
1835          *
1836          * @param mimeType
1837          *            The MIME type of the temporary image
1838          * @param imageData
1839          *            The encoded data of the image
1840          * @return The temporary image
1841          */
1842         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1843                 TemporaryImage temporaryImage = new TemporaryImage();
1844                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1845                 synchronized (temporaryImages) {
1846                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1847                 }
1848                 return temporaryImage;
1849         }
1850
1851         /**
1852          * Deletes the given temporary image.
1853          *
1854          * @param temporaryImage
1855          *            The temporary image to delete
1856          */
1857         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1858                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1859                 deleteTemporaryImage(temporaryImage.getId());
1860         }
1861
1862         /**
1863          * Deletes the temporary image with the given ID.
1864          *
1865          * @param imageId
1866          *            The ID of the temporary image to delete
1867          */
1868         public void deleteTemporaryImage(String imageId) {
1869                 checkNotNull(imageId, "imageId must not be null");
1870                 synchronized (temporaryImages) {
1871                         temporaryImages.remove(imageId);
1872                 }
1873                 Image image = getImage(imageId, false);
1874                 if (image != null) {
1875                         imageInserter.cancelImageInsert(image);
1876                 }
1877         }
1878
1879         /**
1880          * Notifies the core that the configuration, either of the core or of a
1881          * single local Sone, has changed, and that the configuration should be
1882          * saved.
1883          */
1884         public void touchConfiguration() {
1885                 lastConfigurationUpdate = System.currentTimeMillis();
1886         }
1887
1888         //
1889         // SERVICE METHODS
1890         //
1891
1892         /**
1893          * Starts the core.
1894          */
1895         @Override
1896         public void serviceStart() {
1897                 loadConfiguration();
1898                 updateChecker.start();
1899                 identityManager.start();
1900                 webOfTrustUpdater.init();
1901                 webOfTrustUpdater.start();
1902         }
1903
1904         /**
1905          * {@inheritDoc}
1906          */
1907         @Override
1908         public void serviceRun() {
1909                 long lastSaved = System.currentTimeMillis();
1910                 while (!shouldStop()) {
1911                         sleep(1000);
1912                         long now = System.currentTimeMillis();
1913                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1914                                 for (Sone localSone : getLocalSones()) {
1915                                         saveSone(localSone);
1916                                 }
1917                                 saveConfiguration();
1918                                 lastSaved = now;
1919                         }
1920                 }
1921         }
1922
1923         /**
1924          * Stops the core.
1925          */
1926         @Override
1927         public void serviceStop() {
1928                 localElementTicker.shutdownNow();
1929                 synchronized (sones) {
1930                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1931                                 soneInserter.getValue().stop();
1932                                 saveSone(soneInserter.getKey());
1933                         }
1934                 }
1935                 saveConfiguration();
1936                 webOfTrustUpdater.stop();
1937                 updateChecker.stop();
1938                 soneDownloader.stop();
1939                 identityManager.stop();
1940         }
1941
1942         //
1943         // PRIVATE METHODS
1944         //
1945
1946         /**
1947          * Saves the given Sone. This will persist all local settings for the given
1948          * Sone, such as the friends list and similar, private options.
1949          *
1950          * @param sone
1951          *            The Sone to save
1952          */
1953         private synchronized void saveSone(Sone sone) {
1954                 if (!sone.isLocal()) {
1955                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1956                         return;
1957                 }
1958                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1959                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1960                         return;
1961                 }
1962
1963                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1964                 try {
1965                         /* save Sone into configuration. */
1966                         String sonePrefix = "Sone/" + sone.getId();
1967                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1968                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1969
1970                         /* save profile. */
1971                         Profile profile = sone.getProfile();
1972                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1973                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1974                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1975                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1976                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1977                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1978                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1979
1980                         /* save profile fields. */
1981                         int fieldCounter = 0;
1982                         for (Field profileField : profile.getFields()) {
1983                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1984                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1985                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1986                         }
1987                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1988
1989                         /* save posts. */
1990                         int postCounter = 0;
1991                         for (Post post : sone.getPosts()) {
1992                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1993                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1994                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1995                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1996                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1997                         }
1998                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1999
2000                         /* save replies. */
2001                         int replyCounter = 0;
2002                         for (PostReply reply : sone.getReplies()) {
2003                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2004                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2005                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2006                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2007                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2008                         }
2009                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2010
2011                         /* save post likes. */
2012                         int postLikeCounter = 0;
2013                         for (String postId : sone.getLikedPostIds()) {
2014                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2015                         }
2016                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2017
2018                         /* save reply likes. */
2019                         int replyLikeCounter = 0;
2020                         for (String replyId : sone.getLikedReplyIds()) {
2021                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2022                         }
2023                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2024
2025                         /* save friends. */
2026                         int friendCounter = 0;
2027                         for (String friendId : sone.getFriends()) {
2028                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2029                         }
2030                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2031
2032                         /* save albums. first, collect in a flat structure, top-level first. */
2033                         List<Album> albums = sone.getAllAlbums();
2034
2035                         int albumCounter = 0;
2036                         for (Album album : albums) {
2037                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2038                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2039                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2040                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2041                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2042                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2043                         }
2044                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2045
2046                         /* save images. */
2047                         int imageCounter = 0;
2048                         for (Album album : albums) {
2049                                 for (Image image : album.getImages()) {
2050                                         if (!image.isInserted()) {
2051                                                 continue;
2052                                         }
2053                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2054                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2055                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2056                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2057                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2058                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2059                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2060                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2061                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2062                                 }
2063                         }
2064                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2065
2066                         /* save options. */
2067                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2068                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2069                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2070                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2071                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2072                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2073
2074                         configuration.save();
2075
2076                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2077
2078                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2079                 } catch (ConfigurationException ce1) {
2080                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2081                 }
2082         }
2083
2084         /**
2085          * Saves the current options.
2086          */
2087         private void saveConfiguration() {
2088                 synchronized (configuration) {
2089                         if (storingConfiguration) {
2090                                 logger.log(Level.FINE, "Already storing configuration…");
2091                                 return;
2092                         }
2093                         storingConfiguration = true;
2094                 }
2095
2096                 /* store the options first. */
2097                 try {
2098                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2099                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2100                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2101                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2102                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2103                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2104                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2105                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2106                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2107                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2108                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2109                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2110
2111                         /* save known Sones. */
2112                         int soneCounter = 0;
2113                         synchronized (knownSones) {
2114                                 for (String knownSoneId : knownSones) {
2115                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2116                                 }
2117                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2118                         }
2119
2120                         /* save Sone following times. */
2121                         soneCounter = 0;
2122                         synchronized (soneFollowingTimes) {
2123                                 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2124                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2125                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2126                                         ++soneCounter;
2127                                 }
2128                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2129                         }
2130
2131                         /* save known posts. */
2132                         int postCounter = 0;
2133                         synchronized (knownPosts) {
2134                                 for (String knownPostId : knownPosts) {
2135                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2136                                 }
2137                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2138                         }
2139
2140                         /* save known replies. */
2141                         int replyCounter = 0;
2142                         synchronized (knownReplies) {
2143                                 for (String knownReplyId : knownReplies) {
2144                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2145                                 }
2146                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2147                         }
2148
2149                         /* save bookmarked posts. */
2150                         int bookmarkedPostCounter = 0;
2151                         synchronized (bookmarkedPosts) {
2152                                 for (String bookmarkedPostId : bookmarkedPosts) {
2153                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2154                                 }
2155                         }
2156                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2157
2158                         /* now save it. */
2159                         configuration.save();
2160
2161                 } catch (ConfigurationException ce1) {
2162                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2163                 } finally {
2164                         synchronized (configuration) {
2165                                 storingConfiguration = false;
2166                         }
2167                 }
2168         }
2169
2170         /**
2171          * Loads the configuration.
2172          */
2173         @SuppressWarnings("unchecked")
2174         private void loadConfiguration() {
2175                 /* create options. */
2176                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2177
2178                         @Override
2179                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2180                                 SoneInserter.setInsertionDelay(newValue);
2181                         }
2182
2183                 }));
2184                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2185                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2186                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2187                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2188                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2189                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2190                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2191                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2192                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2193
2194                         @Override
2195                         @SuppressWarnings("synthetic-access")
2196                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2197                                 fcpInterface.setActive(newValue);
2198                         }
2199                 }));
2200                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2201
2202                         @Override
2203                         @SuppressWarnings("synthetic-access")
2204                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2205                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2206                         }
2207
2208                 }));
2209
2210                 loadConfigurationValue("InsertionDelay");
2211                 loadConfigurationValue("PostsPerPage");
2212                 loadConfigurationValue("ImagesPerPage");
2213                 loadConfigurationValue("CharactersPerPost");
2214                 loadConfigurationValue("PostCutOffLength");
2215                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2216                 loadConfigurationValue("PositiveTrust");
2217                 loadConfigurationValue("NegativeTrust");
2218                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2219                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2220                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2221
2222                 /* load known Sones. */
2223                 int soneCounter = 0;
2224                 while (true) {
2225                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2226                         if (knownSoneId == null) {
2227                                 break;
2228                         }
2229                         synchronized (knownSones) {
2230                                 knownSones.add(knownSoneId);
2231                         }
2232                 }
2233
2234                 /* load Sone following times. */
2235                 soneCounter = 0;
2236                 while (true) {
2237                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2238                         if (soneId == null) {
2239                                 break;
2240                         }
2241                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2242                         Sone followedSone = getSone(soneId);
2243                         if (followedSone == null) {
2244                                 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2245                         } else {
2246                                 synchronized (soneFollowingTimes) {
2247                                         soneFollowingTimes.put(getSone(soneId), time);
2248                                 }
2249                         }
2250                         ++soneCounter;
2251                 }
2252
2253                 /* load known posts. */
2254                 int postCounter = 0;
2255                 while (true) {
2256                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2257                         if (knownPostId == null) {
2258                                 break;
2259                         }
2260                         synchronized (knownPosts) {
2261                                 knownPosts.add(knownPostId);
2262                         }
2263                 }
2264
2265                 /* load known replies. */
2266                 int replyCounter = 0;
2267                 while (true) {
2268                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2269                         if (knownReplyId == null) {
2270                                 break;
2271                         }
2272                         synchronized (knownReplies) {
2273                                 knownReplies.add(knownReplyId);
2274                         }
2275                 }
2276
2277                 /* load bookmarked posts. */
2278                 int bookmarkedPostCounter = 0;
2279                 while (true) {
2280                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2281                         if (bookmarkedPostId == null) {
2282                                 break;
2283                         }
2284                         synchronized (bookmarkedPosts) {
2285                                 bookmarkedPosts.add(bookmarkedPostId);
2286                         }
2287                 }
2288
2289         }
2290
2291         /**
2292          * Loads an {@link Integer} configuration value for the option with the
2293          * given name, logging validation failures.
2294          *
2295          * @param optionName
2296          *            The name of the option to load
2297          */
2298         private void loadConfigurationValue(String optionName) {
2299                 try {
2300                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2301                 } catch (IllegalArgumentException iae1) {
2302                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2303                 }
2304         }
2305
2306         /**
2307          * Notifies the core that a new {@link OwnIdentity} was added.
2308          *
2309          * @param ownIdentityAddedEvent
2310          *            The event
2311          */
2312         @Subscribe
2313         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2314                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2315                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2316                 if (ownIdentity.hasContext("Sone")) {
2317                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2318                         addLocalSone(ownIdentity);
2319                 }
2320         }
2321
2322         /**
2323          * Notifies the core that an {@link OwnIdentity} was removed.
2324          *
2325          * @param ownIdentityRemovedEvent
2326          *            The event
2327          */
2328         @Subscribe
2329         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2330                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2331                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2332                 trustedIdentities.remove(ownIdentity);
2333         }
2334
2335         /**
2336          * Notifies the core that a new {@link Identity} was added.
2337          *
2338          * @param identityAddedEvent
2339          *            The event
2340          */
2341         @Subscribe
2342         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2343                 Identity identity = identityAddedEvent.identity();
2344                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2345                 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2346                 addRemoteSone(identity);
2347         }
2348
2349         /**
2350          * Notifies the core that an {@link Identity} was updated.
2351          *
2352          * @param identityUpdatedEvent
2353          *            The event
2354          */
2355         @Subscribe
2356         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2357                 final Identity identity = identityUpdatedEvent.identity();
2358                 soneDownloaders.execute(new Runnable() {
2359
2360                         @Override
2361                         @SuppressWarnings("synthetic-access")
2362                         public void run() {
2363                                 Sone sone = getRemoteSone(identity.getId(), false);
2364                                 sone.setIdentity(identity);
2365                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2366                                 soneDownloader.addSone(sone);
2367                                 soneDownloader.fetchSone(sone);
2368                         }
2369                 });
2370         }
2371
2372         /**
2373          * Notifies the core that an {@link Identity} was removed.
2374          *
2375          * @param identityRemovedEvent
2376          *            The event
2377          */
2378         @Subscribe
2379         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2380                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2381                 Identity identity = identityRemovedEvent.identity();
2382                 trustedIdentities.get(ownIdentity).remove(identity);
2383                 boolean foundIdentity = false;
2384                 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2385                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2386                                 continue;
2387                         }
2388                         if (trustedIdentity.getValue().contains(identity)) {
2389                                 foundIdentity = true;
2390                         }
2391                 }
2392                 if (foundIdentity) {
2393                         /* some local identity still trusts this identity, don’t remove. */
2394                         return;
2395                 }
2396                 Sone sone = getSone(identity.getId(), false);
2397                 if (sone == null) {
2398                         /* TODO - we don’t have the Sone anymore. should this happen? */
2399                         return;
2400                 }
2401                 synchronized (posts) {
2402                         synchronized (knownPosts) {
2403                                 for (Post post : sone.getPosts()) {
2404                                         posts.remove(post.getId());
2405                                         eventBus.post(new PostRemovedEvent(post));
2406                                 }
2407                         }
2408                 }
2409                 synchronized (replies) {
2410                         synchronized (knownReplies) {
2411                                 for (PostReply reply : sone.getReplies()) {
2412                                         replies.remove(reply.getId());
2413                                         eventBus.post(new PostReplyRemovedEvent(reply));
2414                                 }
2415                         }
2416                 }
2417                 synchronized (sones) {
2418                         sones.remove(identity.getId());
2419                 }
2420                 eventBus.post(new SoneRemovedEvent(sone));
2421         }
2422
2423         /**
2424          * Deletes the temporary image.
2425          *
2426          * @param imageInsertFinishedEvent
2427          *            The event
2428          */
2429         @Subscribe
2430         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2431                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2432                 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2433                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2434                 touchConfiguration();
2435         }
2436
2437 }