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