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