fd3b1d1a474eb297c757daaee7f03a8cc623b2fb
[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() : false;
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         public Optional<Image> getImage(String imageId) {
647                 return database.getImage(imageId);
648         }
649
650         /**
651          * Returns the temporary image with the given ID.
652          *
653          * @param imageId
654          *            The ID of the temporary image
655          * @return The temporary image, or {@code null} if there is no temporary
656          *         image with the given ID
657          */
658         public TemporaryImage getTemporaryImage(String imageId) {
659                 synchronized (temporaryImages) {
660                         return temporaryImages.get(imageId);
661                 }
662         }
663
664         //
665         // ACTIONS
666         //
667
668         /**
669          * Locks the given Sone. A locked Sone will not be inserted by
670          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
671          * again.
672          *
673          * @param sone
674          *            The sone to lock
675          */
676         public void lockSone(Sone sone) {
677                 synchronized (lockedSones) {
678                         if (lockedSones.add(sone)) {
679                                 eventBus.post(new SoneLockedEvent(sone));
680                         }
681                 }
682         }
683
684         /**
685          * Unlocks the given Sone.
686          *
687          * @see #lockSone(Sone)
688          * @param sone
689          *            The sone to unlock
690          */
691         public void unlockSone(Sone sone) {
692                 synchronized (lockedSones) {
693                         if (lockedSones.remove(sone)) {
694                                 eventBus.post(new SoneUnlockedEvent(sone));
695                         }
696                 }
697         }
698
699         /**
700          * Adds a local Sone from the given own identity.
701          *
702          * @param ownIdentity
703          *            The own identity to create a Sone from
704          * @return The added (or already existing) Sone
705          */
706         public Sone addLocalSone(OwnIdentity ownIdentity) {
707                 if (ownIdentity == null) {
708                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
709                         return null;
710                 }
711                 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
712                 synchronized (sones) {
713                         final Sone sone;
714                         try {
715                                 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
716                         } catch (MalformedURLException mue1) {
717                                 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
718                                 return null;
719                         }
720                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
721                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
722                         sone.setKnown(true);
723                         /* TODO - load posts ’n stuff */
724                         sones.put(ownIdentity.getId(), sone);
725                         final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
726                         soneInserters.put(sone, soneInserter);
727                         sone.setStatus(SoneStatus.idle);
728                         loadSone(sone);
729                         soneInserter.start();
730                         return sone;
731                 }
732         }
733
734         /**
735          * Creates a new Sone for the given own identity.
736          *
737          * @param ownIdentity
738          *            The own identity to create a Sone for
739          * @return The created Sone
740          */
741         public Sone createSone(OwnIdentity ownIdentity) {
742                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
743                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
744                         return null;
745                 }
746                 Sone sone = addLocalSone(ownIdentity);
747                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
748                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
749                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
750                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
751                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
752                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
753
754                 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
755                 touchConfiguration();
756                 return sone;
757         }
758
759         /**
760          * Adds the Sone of the given identity.
761          *
762          * @param identity
763          *            The identity whose Sone to add
764          * @return The added or already existing Sone
765          */
766         public Sone addRemoteSone(Identity identity) {
767                 if (identity == null) {
768                         logger.log(Level.WARNING, "Given Identity is null!");
769                         return null;
770                 }
771                 synchronized (sones) {
772                         final Sone sone = getRemoteSone(identity.getId(), true);
773                         if (sone.isLocal()) {
774                                 return sone;
775                         }
776                         sone.setIdentity(identity);
777                         boolean newSone = sone.getRequestUri() == null;
778                         sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
779                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
780                         if (newSone) {
781                                 synchronized (knownSones) {
782                                         newSone = !knownSones.contains(sone.getId());
783                                 }
784                                 sone.setKnown(!newSone);
785                                 if (newSone) {
786                                         eventBus.post(new NewSoneFoundEvent(sone));
787                                         for (Sone localSone : getLocalSones()) {
788                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
789                                                         followSone(localSone, sone.getId());
790                                                 }
791                                         }
792                                 }
793                         }
794                         soneDownloader.addSone(sone);
795                         soneDownloaders.execute(new Runnable() {
796
797                                 @Override
798                                 @SuppressWarnings("synthetic-access")
799                                 public void run() {
800                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
801                                 }
802
803                         });
804                         return sone;
805                 }
806         }
807
808         /**
809          * Lets the given local Sone follow the Sone with the given ID.
810          *
811          * @param sone
812          *            The local Sone that should follow another Sone
813          * @param soneId
814          *            The ID of the Sone to follow
815          */
816         public void followSone(Sone sone, String soneId) {
817                 checkNotNull(sone, "sone must not be null");
818                 checkNotNull(soneId, "soneId must not be null");
819                 sone.addFriend(soneId);
820                 synchronized (soneFollowingTimes) {
821                         if (!soneFollowingTimes.containsKey(soneId)) {
822                                 long now = System.currentTimeMillis();
823                                 soneFollowingTimes.put(soneId, now);
824                                 Optional<Sone> followedSone = getSone(soneId);
825                                 if (!followedSone.isPresent()) {
826                                         return;
827                                 }
828                                 for (Post post : followedSone.get().getPosts()) {
829                                         if (post.getTime() < now) {
830                                                 markPostKnown(post);
831                                         }
832                                 }
833                                 for (PostReply reply : followedSone.get().getReplies()) {
834                                         if (reply.getTime() < now) {
835                                                 markReplyKnown(reply);
836                                         }
837                                 }
838                         }
839                 }
840                 touchConfiguration();
841         }
842
843         /**
844          * Lets the given local Sone unfollow the Sone with the given ID.
845          *
846          * @param sone
847          *            The local Sone that should unfollow another Sone
848          * @param soneId
849          *            The ID of the Sone being unfollowed
850          */
851         public void unfollowSone(Sone sone, String soneId) {
852                 checkNotNull(sone, "sone must not be null");
853                 checkNotNull(soneId, "soneId must not be null");
854                 sone.removeFriend(soneId);
855                 boolean unfollowedSoneStillFollowed = false;
856                 for (Sone localSone : getLocalSones()) {
857                         unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
858                 }
859                 if (!unfollowedSoneStillFollowed) {
860                         synchronized (soneFollowingTimes) {
861                                 soneFollowingTimes.remove(soneId);
862                         }
863                 }
864                 touchConfiguration();
865         }
866
867         /**
868          * Sets the trust value of the given origin Sone for the target Sone.
869          *
870          * @param origin
871          *            The origin Sone
872          * @param target
873          *            The target Sone
874          * @param trustValue
875          *            The trust value (from {@code -100} to {@code 100})
876          */
877         public void setTrust(Sone origin, Sone target, int trustValue) {
878                 checkNotNull(origin, "origin must not be null");
879                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
880                 checkNotNull(target, "target must not be null");
881                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
882                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
883         }
884
885         /**
886          * Removes any trust assignment for the given target Sone.
887          *
888          * @param origin
889          *            The trust origin
890          * @param target
891          *            The trust target
892          */
893         public void removeTrust(Sone origin, Sone target) {
894                 checkNotNull(origin, "origin must not be null");
895                 checkNotNull(target, "target must not be null");
896                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
897                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
898         }
899
900         /**
901          * Assigns the configured positive trust value for the given target.
902          *
903          * @param origin
904          *            The trust origin
905          * @param target
906          *            The trust target
907          */
908         public void trustSone(Sone origin, Sone target) {
909                 setTrust(origin, target, preferences.getPositiveTrust());
910         }
911
912         /**
913          * Assigns the configured negative trust value for the given target.
914          *
915          * @param origin
916          *            The trust origin
917          * @param target
918          *            The trust target
919          */
920         public void distrustSone(Sone origin, Sone target) {
921                 setTrust(origin, target, preferences.getNegativeTrust());
922         }
923
924         /**
925          * Removes the trust assignment for the given target.
926          *
927          * @param origin
928          *            The trust origin
929          * @param target
930          *            The trust target
931          */
932         public void untrustSone(Sone origin, Sone target) {
933                 removeTrust(origin, target);
934         }
935
936         /**
937          * Updates the stored Sone with the given Sone.
938          *
939          * @param sone
940          *            The updated Sone
941          */
942         public void updateSone(Sone sone) {
943                 updateSone(sone, false);
944         }
945
946         /**
947          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
948          * {@code true}, an older Sone than the current Sone can be given to restore
949          * an old state.
950          *
951          * @param sone
952          *            The Sone to update
953          * @param soneRescueMode
954          *            {@code true} if the stored Sone should be updated regardless
955          *            of the age of the given Sone
956          */
957         public void updateSone(Sone sone, boolean soneRescueMode) {
958                 Optional<Sone> storedSone = getSone(sone.getId());
959                 if (storedSone.isPresent()) {
960                         if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
961                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
962                                 return;
963                         }
964                         /* find removed posts. */
965                         Collection<Post> existingPosts = database.getPosts(sone.getId());
966                         for (Post oldPost : existingPosts) {
967                                 if (!sone.getPosts().contains(oldPost)) {
968                                         eventBus.post(new PostRemovedEvent(oldPost));
969                                 }
970                         }
971                         /* find new posts. */
972                         for (Post newPost : sone.getPosts()) {
973                                 if (existingPosts.contains(newPost)) {
974                                         continue;
975                                 }
976                                 if (newPost.getTime() < getSoneFollowingTime(sone)) {
977                                         newPost.setKnown(true);
978                                 } else if (!newPost.isKnown()) {
979                                         eventBus.post(new NewPostFoundEvent(newPost));
980                                 }
981                         }
982                         /* store posts. */
983                         database.storePosts(sone, sone.getPosts());
984                         if (!soneRescueMode) {
985                                 for (PostReply reply : storedSone.get().getReplies()) {
986                                         if (!sone.getReplies().contains(reply)) {
987                                                 eventBus.post(new PostReplyRemovedEvent(reply));
988                                         }
989                                 }
990                         }
991                         Set<PostReply> storedReplies = storedSone.get().getReplies();
992                         for (PostReply reply : sone.getReplies()) {
993                                 if (storedReplies.contains(reply)) {
994                                         continue;
995                                 }
996                                 if (reply.getTime() < getSoneFollowingTime(sone)) {
997                                         reply.setKnown(true);
998                                 } else if (!reply.isKnown()) {
999                                         eventBus.post(new NewPostReplyFoundEvent(reply));
1000                                 }
1001                         }
1002                         database.storePostReplies(sone, sone.getReplies());
1003                         for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1004                                 database.removeAlbum(album);
1005                                 for (Image image : album.getImages()) {
1006                                         database.removeImage(image);
1007                                 }
1008                         }
1009                         for (Album album : sone.getRootAlbum().getAlbums()) {
1010                                 database.storeAlbum(album);
1011                                 for (Image image : album.getImages()) {
1012                                         database.storeImage(image);
1013                                 }
1014                         }
1015                         synchronized (sones) {
1016                                 sone.setOptions(storedSone.get().getOptions());
1017                                 sone.setKnown(storedSone.get().isKnown());
1018                                 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1019                                 if (sone.isLocal()) {
1020                                         soneInserters.get(storedSone.get()).setSone(sone);
1021                                         touchConfiguration();
1022                                 }
1023                                 sones.put(sone.getId(), sone);
1024                         }
1025                 }
1026         }
1027
1028         /**
1029          * Deletes the given Sone. This will remove the Sone from the
1030          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1031          * remove the context from its identity.
1032          *
1033          * @param sone
1034          *            The Sone to delete
1035          */
1036         public void deleteSone(Sone sone) {
1037                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1038                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1039                         return;
1040                 }
1041                 synchronized (sones) {
1042                         if (!getLocalSones().contains(sone)) {
1043                                 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1044                                 return;
1045                         }
1046                         sones.remove(sone.getId());
1047                         SoneInserter soneInserter = soneInserters.remove(sone);
1048                         soneInserter.stop();
1049                 }
1050                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1051                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1052                 try {
1053                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1054                 } catch (ConfigurationException ce1) {
1055                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1056                 }
1057         }
1058
1059         /**
1060          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1061          * known} before, a {@link MarkSoneKnownEvent} is fired.
1062          *
1063          * @param sone
1064          *            The Sone to mark as known
1065          */
1066         public void markSoneKnown(Sone sone) {
1067                 if (!sone.isKnown()) {
1068                         sone.setKnown(true);
1069                         synchronized (knownSones) {
1070                                 knownSones.add(sone.getId());
1071                         }
1072                         eventBus.post(new MarkSoneKnownEvent(sone));
1073                         touchConfiguration();
1074                 }
1075         }
1076
1077         /**
1078          * Loads and updates the given Sone from the configuration. If any error is
1079          * encountered, loading is aborted and the given Sone is not changed.
1080          *
1081          * @param sone
1082          *            The Sone to load and update
1083          */
1084         public void loadSone(Sone sone) {
1085                 if (!sone.isLocal()) {
1086                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1087                         return;
1088                 }
1089                 logger.info(String.format("Loading local Sone: %s", sone));
1090
1091                 /* initialize options. */
1092                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1093                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1094                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1095                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1096                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1097                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1098
1099                 /* load Sone. */
1100                 String sonePrefix = "Sone/" + sone.getId();
1101                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1102                 if (soneTime == null) {
1103                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1104                         return;
1105                 }
1106                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1107
1108                 /* load profile. */
1109                 Profile profile = new Profile(sone);
1110                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1111                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1112                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1113                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1114                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1115                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1116
1117                 /* load profile fields. */
1118                 while (true) {
1119                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1120                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1121                         if (fieldName == null) {
1122                                 break;
1123                         }
1124                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1125                         profile.addField(fieldName).setValue(fieldValue);
1126                 }
1127
1128                 /* load posts. */
1129                 Set<Post> posts = new HashSet<Post>();
1130                 while (true) {
1131                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1132                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1133                         if (postId == null) {
1134                                 break;
1135                         }
1136                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1137                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1138                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1139                         if ((postTime == 0) || (postText == null)) {
1140                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1141                                 return;
1142                         }
1143                         PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1144                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1145                                 postBuilder.to(postRecipientId);
1146                         }
1147                         posts.add(postBuilder.build());
1148                 }
1149
1150                 /* load replies. */
1151                 Set<PostReply> replies = new HashSet<PostReply>();
1152                 while (true) {
1153                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1154                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1155                         if (replyId == null) {
1156                                 break;
1157                         }
1158                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1159                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1160                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1161                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1162                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1163                                 return;
1164                         }
1165                         PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1166                         replies.add(postReplyBuilder.build());
1167                 }
1168
1169                 /* load post likes. */
1170                 Set<String> likedPostIds = new HashSet<String>();
1171                 while (true) {
1172                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1173                         if (likedPostId == null) {
1174                                 break;
1175                         }
1176                         likedPostIds.add(likedPostId);
1177                 }
1178
1179                 /* load reply likes. */
1180                 Set<String> likedReplyIds = new HashSet<String>();
1181                 while (true) {
1182                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1183                         if (likedReplyId == null) {
1184                                 break;
1185                         }
1186                         likedReplyIds.add(likedReplyId);
1187                 }
1188
1189                 /* load friends. */
1190                 Set<String> friends = new HashSet<String>();
1191                 while (true) {
1192                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1193                         if (friendId == null) {
1194                                 break;
1195                         }
1196                         friends.add(friendId);
1197                 }
1198
1199                 /* load albums. */
1200                 List<Album> topLevelAlbums = new ArrayList<Album>();
1201                 int albumCounter = 0;
1202                 while (true) {
1203                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1204                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1205                         if (albumId == null) {
1206                                 break;
1207                         }
1208                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1209                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1210                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1211                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1212                         if ((albumTitle == null) || (albumDescription == null)) {
1213                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1214                                 return;
1215                         }
1216                         Album album = getAlbum(albumId).setSone(sone).modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1217                         if (albumParentId != null) {
1218                                 Album parentAlbum = getAlbum(albumParentId, false);
1219                                 if (parentAlbum == null) {
1220                                         logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1221                                         return;
1222                                 }
1223                                 parentAlbum.addAlbum(album);
1224                         } else {
1225                                 if (!topLevelAlbums.contains(album)) {
1226                                         topLevelAlbums.add(album);
1227                                 }
1228                         }
1229                 }
1230
1231                 /* load images. */
1232                 int imageCounter = 0;
1233                 while (true) {
1234                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1235                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1236                         if (imageId == null) {
1237                                 break;
1238                         }
1239                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1240                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1241                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1242                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1243                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1244                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1245                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1246                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1247                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1248                                 return;
1249                         }
1250                         Album album = getAlbum(albumId, false);
1251                         if (album == null) {
1252                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1253                                 return;
1254                         }
1255                         album.newImageBuilder().withId(imageId).by(sone).created(creationTime).at(key).sized(width, height).build().modify().setTitle(title).setDescription(description).update();
1256                 }
1257
1258                 /* load avatar. */
1259                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1260                 if (avatarId != null) {
1261                         profile.setAvatar(getImage(avatarId).orNull());
1262                 }
1263
1264                 /* load options. */
1265                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1266                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1267                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1268                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1269                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1270                 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1271
1272                 /* if we’re still here, Sone was loaded successfully. */
1273                 synchronized (sone) {
1274                         sone.setTime(soneTime);
1275                         sone.setProfile(profile);
1276                         sone.setPosts(posts);
1277                         sone.setReplies(replies);
1278                         sone.setLikePostIds(likedPostIds);
1279                         sone.setLikeReplyIds(likedReplyIds);
1280                         for (String friendId : friends) {
1281                                 followSone(sone, friendId);
1282                         }
1283                         for (Album album : sone.getRootAlbum().getAlbums()) {
1284                                 sone.getRootAlbum().removeAlbum(album);
1285                         }
1286                         for (Album album : topLevelAlbums) {
1287                                 sone.getRootAlbum().addAlbum(album);
1288                         }
1289                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1290                 }
1291                 synchronized (knownSones) {
1292                         for (String friend : friends) {
1293                                 knownSones.add(friend);
1294                         }
1295                 }
1296                 database.storePosts(sone, posts);
1297                 for (Post post : posts) {
1298                         post.setKnown(true);
1299                 }
1300                 database.storePostReplies(sone, replies);
1301                 for (PostReply reply : replies) {
1302                         reply.setKnown(true);
1303                 }
1304
1305                 logger.info(String.format("Sone loaded successfully: %s", sone));
1306         }
1307
1308         /**
1309          * Creates a new post.
1310          *
1311          * @param sone
1312          *            The Sone that creates the post
1313          * @param text
1314          *            The text of the post
1315          * @return The created post
1316          */
1317         public Post createPost(Sone sone, String text) {
1318                 return createPost(sone, System.currentTimeMillis(), text);
1319         }
1320
1321         /**
1322          * Creates a new post.
1323          *
1324          * @param sone
1325          *            The Sone that creates the post
1326          * @param time
1327          *            The time of the post
1328          * @param text
1329          *            The text of the post
1330          * @return The created post
1331          */
1332         public Post createPost(Sone sone, long time, String text) {
1333                 return createPost(sone, null, time, text);
1334         }
1335
1336         /**
1337          * Creates a new post.
1338          *
1339          * @param sone
1340          *            The Sone that creates the post
1341          * @param recipient
1342          *            The recipient Sone, or {@code null} if this post does not have
1343          *            a recipient
1344          * @param text
1345          *            The text of the post
1346          * @return The created post
1347          */
1348         public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1349                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1350         }
1351
1352         /**
1353          * Creates a new post.
1354          *
1355          * @param sone
1356          *            The Sone that creates the post
1357          * @param recipient
1358          *            The recipient Sone, or {@code null} if this post does not have
1359          *            a recipient
1360          * @param time
1361          *            The time of the post
1362          * @param text
1363          *            The text of the post
1364          * @return The created post
1365          */
1366         public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1367                 checkNotNull(text, "text must not be null");
1368                 checkArgument(text.trim().length() > 0, "text must not be empty");
1369                 if (!sone.isLocal()) {
1370                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1371                         return null;
1372                 }
1373                 PostBuilder postBuilder = database.newPostBuilder();
1374                 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1375                 if (recipient.isPresent()) {
1376                         postBuilder.to(recipient.get().getId());
1377                 }
1378                 final Post post = postBuilder.build();
1379                 database.storePost(post);
1380                 eventBus.post(new NewPostFoundEvent(post));
1381                 sone.addPost(post);
1382                 touchConfiguration();
1383                 localElementTicker.schedule(new Runnable() {
1384
1385                         /**
1386                          * {@inheritDoc}
1387                          */
1388                         @Override
1389                         public void run() {
1390                                 markPostKnown(post);
1391                         }
1392                 }, 10, TimeUnit.SECONDS);
1393                 return post;
1394         }
1395
1396         /**
1397          * Deletes the given post.
1398          *
1399          * @param post
1400          *            The post to delete
1401          */
1402         public void deletePost(Post post) {
1403                 if (!post.getSone().isLocal()) {
1404                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1405                         return;
1406                 }
1407                 database.removePost(post);
1408                 eventBus.post(new PostRemovedEvent(post));
1409                 markPostKnown(post);
1410                 touchConfiguration();
1411         }
1412
1413         /**
1414          * Marks the given post as known, if it is currently not a known post
1415          * (according to {@link Post#isKnown()}).
1416          *
1417          * @param post
1418          *            The post to mark as known
1419          */
1420         public void markPostKnown(Post post) {
1421                 post.setKnown(true);
1422                 eventBus.post(new MarkPostKnownEvent(post));
1423                 touchConfiguration();
1424                 for (PostReply reply : getReplies(post.getId())) {
1425                         markReplyKnown(reply);
1426                 }
1427         }
1428
1429         /**
1430          * Bookmarks the given post.
1431          *
1432          * @param post
1433          *            The post to bookmark
1434          */
1435         public void bookmark(Post post) {
1436                 bookmarkPost(post.getId());
1437         }
1438
1439         /**
1440          * Bookmarks the post with the given ID.
1441          *
1442          * @param id
1443          *            The ID of the post to bookmark
1444          */
1445         public void bookmarkPost(String id) {
1446                 synchronized (bookmarkedPosts) {
1447                         bookmarkedPosts.add(id);
1448                 }
1449         }
1450
1451         /**
1452          * Removes the given post from the bookmarks.
1453          *
1454          * @param post
1455          *            The post to unbookmark
1456          */
1457         public void unbookmark(Post post) {
1458                 unbookmarkPost(post.getId());
1459         }
1460
1461         /**
1462          * Removes the post with the given ID from the bookmarks.
1463          *
1464          * @param id
1465          *            The ID of the post to unbookmark
1466          */
1467         public void unbookmarkPost(String id) {
1468                 synchronized (bookmarkedPosts) {
1469                         bookmarkedPosts.remove(id);
1470                 }
1471         }
1472
1473         /**
1474          * Creates a new reply.
1475          *
1476          * @param sone
1477          *            The Sone that creates the reply
1478          * @param post
1479          *            The post that this reply refers to
1480          * @param text
1481          *            The text of the reply
1482          * @return The created reply
1483          */
1484         public PostReply createReply(Sone sone, Post post, String text) {
1485                 checkNotNull(text, "text must not be null");
1486                 checkArgument(text.trim().length() > 0, "text must not be empty");
1487                 if (!sone.isLocal()) {
1488                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1489                         return null;
1490                 }
1491                 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1492                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1493                 final PostReply reply = postReplyBuilder.build();
1494                 database.storePostReply(reply);
1495                 eventBus.post(new NewPostReplyFoundEvent(reply));
1496                 sone.addReply(reply);
1497                 touchConfiguration();
1498                 localElementTicker.schedule(new Runnable() {
1499
1500                         /**
1501                          * {@inheritDoc}
1502                          */
1503                         @Override
1504                         public void run() {
1505                                 markReplyKnown(reply);
1506                         }
1507                 }, 10, TimeUnit.SECONDS);
1508                 return reply;
1509         }
1510
1511         /**
1512          * Deletes the given reply.
1513          *
1514          * @param reply
1515          *            The reply to delete
1516          */
1517         public void deleteReply(PostReply reply) {
1518                 Sone sone = reply.getSone();
1519                 if (!sone.isLocal()) {
1520                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1521                         return;
1522                 }
1523                 database.removePostReply(reply);
1524                 markReplyKnown(reply);
1525                 sone.removeReply(reply);
1526                 touchConfiguration();
1527         }
1528
1529         /**
1530          * Marks the given reply as known, if it is currently not a known reply
1531          * (according to {@link Reply#isKnown()}).
1532          *
1533          * @param reply
1534          *            The reply to mark as known
1535          */
1536         public void markReplyKnown(PostReply reply) {
1537                 boolean previouslyKnown = reply.isKnown();
1538                 reply.setKnown(true);
1539                 eventBus.post(new MarkPostReplyKnownEvent(reply));
1540                 if (!previouslyKnown) {
1541                         touchConfiguration();
1542                 }
1543         }
1544
1545         /**
1546          * Creates a new top-level album for the given Sone.
1547          *
1548          * @param sone
1549          *            The Sone to create the album for
1550          * @return The new album
1551          */
1552         public Album createAlbum(Sone sone) {
1553                 return createAlbum(sone, sone.getRootAlbum());
1554         }
1555
1556         /**
1557          * Creates a new album for the given Sone.
1558          *
1559          * @param sone
1560          *            The Sone to create the album for
1561          * @param parent
1562          *            The parent of the album (may be {@code null} to create a
1563          *            top-level album)
1564          * @return The new album
1565          */
1566         public Album createAlbum(Sone sone, Album parent) {
1567                 Album album = database.newAlbumBuilder().randomId().build();
1568                 database.storeAlbum(album);
1569                 album.setSone(sone);
1570                 parent.addAlbum(album);
1571                 return album;
1572         }
1573
1574         /**
1575          * Deletes the given album. The owner of the album has to be a local Sone,
1576          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1577          *
1578          * @param album
1579          *            The album to remove
1580          */
1581         public void deleteAlbum(Album album) {
1582                 checkNotNull(album, "album must not be null");
1583                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1584                 if (!album.isEmpty()) {
1585                         return;
1586                 }
1587                 album.getParent().removeAlbum(album);
1588                 database.removeAlbum(album);
1589                 touchConfiguration();
1590         }
1591
1592         /**
1593          * Creates a new image.
1594          *
1595          * @param sone
1596          *            The Sone creating the image
1597          * @param album
1598          *            The album the image will be inserted into
1599          * @param temporaryImage
1600          *            The temporary image to create the image from
1601          * @return The newly created image
1602          */
1603         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1604                 checkNotNull(sone, "sone must not be null");
1605                 checkNotNull(album, "album must not be null");
1606                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1607                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1608                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1609                 Image image = album.newImageBuilder().withId(temporaryImage.getId()).by(sone).createdNow().sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build();
1610                 database.storeImage(image);
1611                 imageInserter.insertImage(temporaryImage, image);
1612                 return image;
1613         }
1614
1615         /**
1616          * Deletes the given image. This method will also delete a matching
1617          * temporary image.
1618          *
1619          * @see #deleteTemporaryImage(TemporaryImage)
1620          * @param image
1621          *            The image to delete
1622          */
1623         public void deleteImage(Image image) {
1624                 checkNotNull(image, "image must not be null");
1625                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1626                 deleteTemporaryImage(image.getId());
1627                 image.getAlbum().removeImage(image);
1628                 database.removeImage(image);
1629                 touchConfiguration();
1630         }
1631
1632         /**
1633          * Creates a new temporary image.
1634          *
1635          * @param mimeType
1636          *            The MIME type of the temporary image
1637          * @param imageData
1638          *            The encoded data of the image
1639          * @return The temporary image
1640          */
1641         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1642                 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1643                 synchronized (temporaryImages) {
1644                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1645                 }
1646                 return temporaryImage;
1647         }
1648
1649         /**
1650          * Deletes the given temporary image.
1651          *
1652          * @param temporaryImage
1653          *            The temporary image to delete
1654          */
1655         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1656                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1657                 deleteTemporaryImage(temporaryImage.getId());
1658         }
1659
1660         /**
1661          * Deletes the temporary image with the given ID.
1662          *
1663          * @param imageId
1664          *            The ID of the temporary image to delete
1665          */
1666         public void deleteTemporaryImage(String imageId) {
1667                 checkNotNull(imageId, "imageId must not be null");
1668                 synchronized (temporaryImages) {
1669                         temporaryImages.remove(imageId);
1670                 }
1671                 Optional<Image> image = getImage(imageId);
1672                 if (image.isPresent()) {
1673                         imageInserter.cancelImageInsert(image.get());
1674                 }
1675         }
1676
1677         /**
1678          * Notifies the core that the configuration, either of the core or of a
1679          * single local Sone, has changed, and that the configuration should be
1680          * saved.
1681          */
1682         public void touchConfiguration() {
1683                 lastConfigurationUpdate = System.currentTimeMillis();
1684         }
1685
1686         //
1687         // SERVICE METHODS
1688         //
1689
1690         /**
1691          * Starts the core.
1692          */
1693         @Override
1694         public void serviceStart() {
1695                 loadConfiguration();
1696                 updateChecker.start();
1697                 identityManager.start();
1698                 webOfTrustUpdater.init();
1699                 webOfTrustUpdater.start();
1700                 database.start();
1701         }
1702
1703         /**
1704          * {@inheritDoc}
1705          */
1706         @Override
1707         public void serviceRun() {
1708                 long lastSaved = System.currentTimeMillis();
1709                 while (!shouldStop()) {
1710                         sleep(1000);
1711                         long now = System.currentTimeMillis();
1712                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1713                                 for (Sone localSone : getLocalSones()) {
1714                                         saveSone(localSone);
1715                                 }
1716                                 saveConfiguration();
1717                                 lastSaved = now;
1718                         }
1719                 }
1720         }
1721
1722         /**
1723          * Stops the core.
1724          */
1725         @Override
1726         public void serviceStop() {
1727                 localElementTicker.shutdownNow();
1728                 synchronized (sones) {
1729                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1730                                 soneInserter.getValue().stop();
1731                                 saveSone(soneInserter.getKey());
1732                         }
1733                 }
1734                 saveConfiguration();
1735                 database.stop();
1736                 webOfTrustUpdater.stop();
1737                 updateChecker.stop();
1738                 soneDownloader.stop();
1739                 soneDownloaders.shutdown();
1740                 identityManager.stop();
1741         }
1742
1743         //
1744         // PRIVATE METHODS
1745         //
1746
1747         /**
1748          * Saves the given Sone. This will persist all local settings for the given
1749          * Sone, such as the friends list and similar, private options.
1750          *
1751          * @param sone
1752          *            The Sone to save
1753          */
1754         private synchronized void saveSone(Sone sone) {
1755                 if (!sone.isLocal()) {
1756                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1757                         return;
1758                 }
1759                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1760                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1761                         return;
1762                 }
1763
1764                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1765                 try {
1766                         /* save Sone into configuration. */
1767                         String sonePrefix = "Sone/" + sone.getId();
1768                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1769                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1770
1771                         /* save profile. */
1772                         Profile profile = sone.getProfile();
1773                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1774                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1775                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1776                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1777                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1778                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1779                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1780
1781                         /* save profile fields. */
1782                         int fieldCounter = 0;
1783                         for (Field profileField : profile.getFields()) {
1784                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1785                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1786                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1787                         }
1788                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1789
1790                         /* save posts. */
1791                         int postCounter = 0;
1792                         for (Post post : sone.getPosts()) {
1793                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1794                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1795                                 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1796                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1797                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1798                         }
1799                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1800
1801                         /* save replies. */
1802                         int replyCounter = 0;
1803                         for (PostReply reply : sone.getReplies()) {
1804                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1805                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1806                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1807                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1808                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1809                         }
1810                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1811
1812                         /* save post likes. */
1813                         int postLikeCounter = 0;
1814                         for (String postId : sone.getLikedPostIds()) {
1815                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1816                         }
1817                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1818
1819                         /* save reply likes. */
1820                         int replyLikeCounter = 0;
1821                         for (String replyId : sone.getLikedReplyIds()) {
1822                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1823                         }
1824                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1825
1826                         /* save friends. */
1827                         int friendCounter = 0;
1828                         for (String friendId : sone.getFriends()) {
1829                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1830                         }
1831                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1832
1833                         /* save albums. first, collect in a flat structure, top-level first. */
1834                         List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1835
1836                         int albumCounter = 0;
1837                         for (Album album : albums) {
1838                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1839                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1840                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1841                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1842                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1843                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1844                         }
1845                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1846
1847                         /* save images. */
1848                         int imageCounter = 0;
1849                         for (Album album : albums) {
1850                                 for (Image image : album.getImages()) {
1851                                         if (!image.isInserted()) {
1852                                                 continue;
1853                                         }
1854                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1855                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1856                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1857                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1858                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1859                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1860                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1861                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1862                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1863                                 }
1864                         }
1865                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1866
1867                         /* save options. */
1868                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1869                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1870                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1871                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1872                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1873                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1874
1875                         configuration.save();
1876
1877                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1878
1879                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1880                 } catch (ConfigurationException ce1) {
1881                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1882                 }
1883         }
1884
1885         /**
1886          * Saves the current options.
1887          */
1888         private void saveConfiguration() {
1889                 synchronized (configuration) {
1890                         if (storingConfiguration) {
1891                                 logger.log(Level.FINE, "Already storing configuration…");
1892                                 return;
1893                         }
1894                         storingConfiguration = true;
1895                 }
1896
1897                 /* store the options first. */
1898                 try {
1899                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1900                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1901                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1902                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1903                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1904                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1905                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1906                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1907                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1908                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1909                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1910                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1911
1912                         /* save known Sones. */
1913                         int soneCounter = 0;
1914                         synchronized (knownSones) {
1915                                 for (String knownSoneId : knownSones) {
1916                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1917                                 }
1918                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1919                         }
1920
1921                         /* save Sone following times. */
1922                         soneCounter = 0;
1923                         synchronized (soneFollowingTimes) {
1924                                 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1925                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1926                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1927                                         ++soneCounter;
1928                                 }
1929                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1930                         }
1931
1932                         /* save known posts. */
1933                         database.save();
1934
1935                         /* save bookmarked posts. */
1936                         int bookmarkedPostCounter = 0;
1937                         synchronized (bookmarkedPosts) {
1938                                 for (String bookmarkedPostId : bookmarkedPosts) {
1939                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1940                                 }
1941                         }
1942                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1943
1944                         /* now save it. */
1945                         configuration.save();
1946
1947                 } catch (ConfigurationException ce1) {
1948                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1949                 } catch (DatabaseException de1) {
1950                         logger.log(Level.SEVERE, "Could not save database!", de1);
1951                 } finally {
1952                         synchronized (configuration) {
1953                                 storingConfiguration = false;
1954                         }
1955                 }
1956         }
1957
1958         /**
1959          * Loads the configuration.
1960          */
1961         private void loadConfiguration() {
1962                 /* create options. */
1963                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1964
1965                         @Override
1966                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1967                                 SoneInserter.setInsertionDelay(newValue);
1968                         }
1969
1970                 }));
1971                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1972                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1973                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1974                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1975                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1976                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1977                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1978                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1979                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1980
1981                         @Override
1982                         @SuppressWarnings("synthetic-access")
1983                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1984                                 fcpInterface.setActive(newValue);
1985                         }
1986                 }));
1987                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1988
1989                         @Override
1990                         @SuppressWarnings("synthetic-access")
1991                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1992                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1993                         }
1994
1995                 }));
1996
1997                 loadConfigurationValue("InsertionDelay");
1998                 loadConfigurationValue("PostsPerPage");
1999                 loadConfigurationValue("ImagesPerPage");
2000                 loadConfigurationValue("CharactersPerPost");
2001                 loadConfigurationValue("PostCutOffLength");
2002                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2003                 loadConfigurationValue("PositiveTrust");
2004                 loadConfigurationValue("NegativeTrust");
2005                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2006                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2007                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2008
2009                 /* load known Sones. */
2010                 int soneCounter = 0;
2011                 while (true) {
2012                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2013                         if (knownSoneId == null) {
2014                                 break;
2015                         }
2016                         synchronized (knownSones) {
2017                                 knownSones.add(knownSoneId);
2018                         }
2019                 }
2020
2021                 /* load Sone following times. */
2022                 soneCounter = 0;
2023                 while (true) {
2024                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2025                         if (soneId == null) {
2026                                 break;
2027                         }
2028                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2029                         synchronized (soneFollowingTimes) {
2030                                 soneFollowingTimes.put(soneId, time);
2031                         }
2032                         ++soneCounter;
2033                 }
2034
2035                 /* load bookmarked posts. */
2036                 int bookmarkedPostCounter = 0;
2037                 while (true) {
2038                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2039                         if (bookmarkedPostId == null) {
2040                                 break;
2041                         }
2042                         synchronized (bookmarkedPosts) {
2043                                 bookmarkedPosts.add(bookmarkedPostId);
2044                         }
2045                 }
2046
2047         }
2048
2049         /**
2050          * Loads an {@link Integer} configuration value for the option with the
2051          * given name, logging validation failures.
2052          *
2053          * @param optionName
2054          *            The name of the option to load
2055          */
2056         private void loadConfigurationValue(String optionName) {
2057                 try {
2058                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2059                 } catch (IllegalArgumentException iae1) {
2060                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2061                 }
2062         }
2063
2064         /**
2065          * Notifies the core that a new {@link OwnIdentity} was added.
2066          *
2067          * @param ownIdentityAddedEvent
2068          *            The event
2069          */
2070         @Subscribe
2071         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2072                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2073                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2074                 if (ownIdentity.hasContext("Sone")) {
2075                         addLocalSone(ownIdentity);
2076                 }
2077         }
2078
2079         /**
2080          * Notifies the core that an {@link OwnIdentity} was removed.
2081          *
2082          * @param ownIdentityRemovedEvent
2083          *            The event
2084          */
2085         @Subscribe
2086         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2087                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2088                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2089                 trustedIdentities.removeAll(ownIdentity);
2090         }
2091
2092         /**
2093          * Notifies the core that a new {@link Identity} was added.
2094          *
2095          * @param identityAddedEvent
2096          *            The event
2097          */
2098         @Subscribe
2099         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2100                 Identity identity = identityAddedEvent.identity();
2101                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2102                 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2103                 addRemoteSone(identity);
2104         }
2105
2106         /**
2107          * Notifies the core that an {@link Identity} was updated.
2108          *
2109          * @param identityUpdatedEvent
2110          *            The event
2111          */
2112         @Subscribe
2113         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2114                 final Identity identity = identityUpdatedEvent.identity();
2115                 soneDownloaders.execute(new Runnable() {
2116
2117                         @Override
2118                         @SuppressWarnings("synthetic-access")
2119                         public void run() {
2120                                 Sone sone = getRemoteSone(identity.getId(), false);
2121                                 if (sone.isLocal()) {
2122                                         return;
2123                                 }
2124                                 sone.setIdentity(identity);
2125                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2126                                 soneDownloader.addSone(sone);
2127                                 soneDownloader.fetchSone(sone);
2128                         }
2129                 });
2130         }
2131
2132         /**
2133          * Notifies the core that an {@link Identity} was removed.
2134          *
2135          * @param identityRemovedEvent
2136          *            The event
2137          */
2138         @Subscribe
2139         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2140                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2141                 Identity identity = identityRemovedEvent.identity();
2142                 trustedIdentities.remove(ownIdentity, identity);
2143                 boolean foundIdentity = false;
2144                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2145                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2146                                 continue;
2147                         }
2148                         if (trustedIdentity.getValue().contains(identity)) {
2149                                 foundIdentity = true;
2150                         }
2151                 }
2152                 if (foundIdentity) {
2153                         /* some local identity still trusts this identity, don’t remove. */
2154                         return;
2155                 }
2156                 Optional<Sone> sone = getSone(identity.getId());
2157                 if (!sone.isPresent()) {
2158                         /* TODO - we don’t have the Sone anymore. should this happen? */
2159                         return;
2160                 }
2161                 database.removePosts(sone.get());
2162                 for (Post post : sone.get().getPosts()) {
2163                         eventBus.post(new PostRemovedEvent(post));
2164                 }
2165                 database.removePostReplies(sone.get());
2166                 for (PostReply reply : sone.get().getReplies()) {
2167                         eventBus.post(new PostReplyRemovedEvent(reply));
2168                 }
2169                 synchronized (sones) {
2170                         sones.remove(identity.getId());
2171                 }
2172                 eventBus.post(new SoneRemovedEvent(sone.get()));
2173         }
2174
2175         /**
2176          * Deletes the temporary image.
2177          *
2178          * @param imageInsertFinishedEvent
2179          *            The event
2180          */
2181         @Subscribe
2182         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2183                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2184                 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2185                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2186                 touchConfiguration();
2187         }
2188
2189 }