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