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