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