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