d20549f4e4ac5e37e162b367f2e80b982ba803f8
[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                         album.newImageBuilder().withId(imageId).by(sone).created(creationTime).at(key).sized(width, height).build().modify().setTitle(title).setDescription(description).update();
1288                 }
1289
1290                 /* load avatar. */
1291                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1292                 if (avatarId != null) {
1293                         profile.setAvatar(getImage(avatarId, false));
1294                 }
1295
1296                 /* load options. */
1297                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1298                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1299                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1300                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1301                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1302                 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1303
1304                 /* if we’re still here, Sone was loaded successfully. */
1305                 synchronized (sone) {
1306                         sone.setTime(soneTime);
1307                         sone.setProfile(profile);
1308                         sone.setPosts(posts);
1309                         sone.setReplies(replies);
1310                         sone.setLikePostIds(likedPostIds);
1311                         sone.setLikeReplyIds(likedReplyIds);
1312                         for (String friendId : friends) {
1313                                 followSone(sone, friendId);
1314                         }
1315                         for (Album album : sone.getRootAlbum().getAlbums()) {
1316                                 sone.getRootAlbum().removeAlbum(album);
1317                         }
1318                         for (Album album : topLevelAlbums) {
1319                                 sone.getRootAlbum().addAlbum(album);
1320                         }
1321                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1322                 }
1323                 synchronized (knownSones) {
1324                         for (String friend : friends) {
1325                                 knownSones.add(friend);
1326                         }
1327                 }
1328                 database.storePosts(sone, posts);
1329                 for (Post post : posts) {
1330                         post.setKnown(true);
1331                 }
1332                 database.storePostReplies(sone, replies);
1333                 for (PostReply reply : replies) {
1334                         reply.setKnown(true);
1335                 }
1336
1337                 logger.info(String.format("Sone loaded successfully: %s", sone));
1338         }
1339
1340         /**
1341          * Creates a new post.
1342          *
1343          * @param sone
1344          *            The Sone that creates the post
1345          * @param text
1346          *            The text of the post
1347          * @return The created post
1348          */
1349         public Post createPost(Sone sone, String text) {
1350                 return createPost(sone, System.currentTimeMillis(), text);
1351         }
1352
1353         /**
1354          * Creates a new post.
1355          *
1356          * @param sone
1357          *            The Sone that creates the post
1358          * @param time
1359          *            The time of the post
1360          * @param text
1361          *            The text of the post
1362          * @return The created post
1363          */
1364         public Post createPost(Sone sone, long time, String text) {
1365                 return createPost(sone, null, time, text);
1366         }
1367
1368         /**
1369          * Creates a new post.
1370          *
1371          * @param sone
1372          *            The Sone that creates the post
1373          * @param recipient
1374          *            The recipient Sone, or {@code null} if this post does not have
1375          *            a recipient
1376          * @param text
1377          *            The text of the post
1378          * @return The created post
1379          */
1380         public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1381                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1382         }
1383
1384         /**
1385          * Creates a new post.
1386          *
1387          * @param sone
1388          *            The Sone that creates the post
1389          * @param recipient
1390          *            The recipient Sone, or {@code null} if this post does not have
1391          *            a recipient
1392          * @param time
1393          *            The time of the post
1394          * @param text
1395          *            The text of the post
1396          * @return The created post
1397          */
1398         public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1399                 checkNotNull(text, "text must not be null");
1400                 checkArgument(text.trim().length() > 0, "text must not be empty");
1401                 if (!sone.isLocal()) {
1402                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1403                         return null;
1404                 }
1405                 PostBuilder postBuilder = database.newPostBuilder();
1406                 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1407                 if (recipient.isPresent()) {
1408                         postBuilder.to(recipient.get().getId());
1409                 }
1410                 final Post post = postBuilder.build();
1411                 database.storePost(post);
1412                 eventBus.post(new NewPostFoundEvent(post));
1413                 sone.addPost(post);
1414                 touchConfiguration();
1415                 localElementTicker.schedule(new Runnable() {
1416
1417                         /**
1418                          * {@inheritDoc}
1419                          */
1420                         @Override
1421                         public void run() {
1422                                 markPostKnown(post);
1423                         }
1424                 }, 10, TimeUnit.SECONDS);
1425                 return post;
1426         }
1427
1428         /**
1429          * Deletes the given post.
1430          *
1431          * @param post
1432          *            The post to delete
1433          */
1434         public void deletePost(Post post) {
1435                 if (!post.getSone().isLocal()) {
1436                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1437                         return;
1438                 }
1439                 database.removePost(post);
1440                 eventBus.post(new PostRemovedEvent(post));
1441                 markPostKnown(post);
1442                 touchConfiguration();
1443         }
1444
1445         /**
1446          * Marks the given post as known, if it is currently not a known post
1447          * (according to {@link Post#isKnown()}).
1448          *
1449          * @param post
1450          *            The post to mark as known
1451          */
1452         public void markPostKnown(Post post) {
1453                 post.setKnown(true);
1454                 eventBus.post(new MarkPostKnownEvent(post));
1455                 touchConfiguration();
1456                 for (PostReply reply : getReplies(post.getId())) {
1457                         markReplyKnown(reply);
1458                 }
1459         }
1460
1461         /**
1462          * Bookmarks the given post.
1463          *
1464          * @param post
1465          *            The post to bookmark
1466          */
1467         public void bookmark(Post post) {
1468                 bookmarkPost(post.getId());
1469         }
1470
1471         /**
1472          * Bookmarks the post with the given ID.
1473          *
1474          * @param id
1475          *            The ID of the post to bookmark
1476          */
1477         public void bookmarkPost(String id) {
1478                 synchronized (bookmarkedPosts) {
1479                         bookmarkedPosts.add(id);
1480                 }
1481         }
1482
1483         /**
1484          * Removes the given post from the bookmarks.
1485          *
1486          * @param post
1487          *            The post to unbookmark
1488          */
1489         public void unbookmark(Post post) {
1490                 unbookmarkPost(post.getId());
1491         }
1492
1493         /**
1494          * Removes the post with the given ID from the bookmarks.
1495          *
1496          * @param id
1497          *            The ID of the post to unbookmark
1498          */
1499         public void unbookmarkPost(String id) {
1500                 synchronized (bookmarkedPosts) {
1501                         bookmarkedPosts.remove(id);
1502                 }
1503         }
1504
1505         /**
1506          * Creates a new reply.
1507          *
1508          * @param sone
1509          *            The Sone that creates the reply
1510          * @param post
1511          *            The post that this reply refers to
1512          * @param text
1513          *            The text of the reply
1514          * @return The created reply
1515          */
1516         public PostReply createReply(Sone sone, Post post, String text) {
1517                 checkNotNull(text, "text must not be null");
1518                 checkArgument(text.trim().length() > 0, "text must not be empty");
1519                 if (!sone.isLocal()) {
1520                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1521                         return null;
1522                 }
1523                 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1524                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1525                 final PostReply reply = postReplyBuilder.build();
1526                 database.storePostReply(reply);
1527                 eventBus.post(new NewPostReplyFoundEvent(reply));
1528                 sone.addReply(reply);
1529                 touchConfiguration();
1530                 localElementTicker.schedule(new Runnable() {
1531
1532                         /**
1533                          * {@inheritDoc}
1534                          */
1535                         @Override
1536                         public void run() {
1537                                 markReplyKnown(reply);
1538                         }
1539                 }, 10, TimeUnit.SECONDS);
1540                 return reply;
1541         }
1542
1543         /**
1544          * Deletes the given reply.
1545          *
1546          * @param reply
1547          *            The reply to delete
1548          */
1549         public void deleteReply(PostReply reply) {
1550                 Sone sone = reply.getSone();
1551                 if (!sone.isLocal()) {
1552                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1553                         return;
1554                 }
1555                 database.removePostReply(reply);
1556                 markReplyKnown(reply);
1557                 sone.removeReply(reply);
1558                 touchConfiguration();
1559         }
1560
1561         /**
1562          * Marks the given reply as known, if it is currently not a known reply
1563          * (according to {@link Reply#isKnown()}).
1564          *
1565          * @param reply
1566          *            The reply to mark as known
1567          */
1568         public void markReplyKnown(PostReply reply) {
1569                 boolean previouslyKnown = reply.isKnown();
1570                 reply.setKnown(true);
1571                 eventBus.post(new MarkPostReplyKnownEvent(reply));
1572                 if (!previouslyKnown) {
1573                         touchConfiguration();
1574                 }
1575         }
1576
1577         /**
1578          * Creates a new top-level album for the given Sone.
1579          *
1580          * @param sone
1581          *            The Sone to create the album for
1582          * @return The new album
1583          */
1584         public Album createAlbum(Sone sone) {
1585                 return createAlbum(sone, sone.getRootAlbum());
1586         }
1587
1588         /**
1589          * Creates a new album for the given Sone.
1590          *
1591          * @param sone
1592          *            The Sone to create the album for
1593          * @param parent
1594          *            The parent of the album (may be {@code null} to create a
1595          *            top-level album)
1596          * @return The new album
1597          */
1598         public Album createAlbum(Sone sone, Album parent) {
1599                 Album album = database.newAlbumBuilder().randomId().build();
1600                 database.storeAlbum(album);
1601                 album.setSone(sone);
1602                 parent.addAlbum(album);
1603                 return album;
1604         }
1605
1606         /**
1607          * Deletes the given album. The owner of the album has to be a local Sone,
1608          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1609          *
1610          * @param album
1611          *            The album to remove
1612          */
1613         public void deleteAlbum(Album album) {
1614                 checkNotNull(album, "album must not be null");
1615                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1616                 if (!album.isEmpty()) {
1617                         return;
1618                 }
1619                 album.getParent().removeAlbum(album);
1620                 database.removeAlbum(album);
1621                 touchConfiguration();
1622         }
1623
1624         /**
1625          * Creates a new image.
1626          *
1627          * @param sone
1628          *            The Sone creating the image
1629          * @param album
1630          *            The album the image will be inserted into
1631          * @param temporaryImage
1632          *            The temporary image to create the image from
1633          * @return The newly created image
1634          */
1635         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1636                 checkNotNull(sone, "sone must not be null");
1637                 checkNotNull(album, "album must not be null");
1638                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1639                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1640                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1641                 Image image = album.newImageBuilder().withId(temporaryImage.getId()).by(sone).createdNow().sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build();
1642                 database.storeImage(image);
1643                 imageInserter.insertImage(temporaryImage, image);
1644                 return image;
1645         }
1646
1647         /**
1648          * Deletes the given image. This method will also delete a matching
1649          * temporary image.
1650          *
1651          * @see #deleteTemporaryImage(TemporaryImage)
1652          * @param image
1653          *            The image to delete
1654          */
1655         public void deleteImage(Image image) {
1656                 checkNotNull(image, "image must not be null");
1657                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1658                 deleteTemporaryImage(image.getId());
1659                 image.getAlbum().removeImage(image);
1660                 database.removeImage(image);
1661                 touchConfiguration();
1662         }
1663
1664         /**
1665          * Creates a new temporary image.
1666          *
1667          * @param mimeType
1668          *            The MIME type of the temporary image
1669          * @param imageData
1670          *            The encoded data of the image
1671          * @return The temporary image
1672          */
1673         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1674                 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1675                 synchronized (temporaryImages) {
1676                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1677                 }
1678                 return temporaryImage;
1679         }
1680
1681         /**
1682          * Deletes the given temporary image.
1683          *
1684          * @param temporaryImage
1685          *            The temporary image to delete
1686          */
1687         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1688                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1689                 deleteTemporaryImage(temporaryImage.getId());
1690         }
1691
1692         /**
1693          * Deletes the temporary image with the given ID.
1694          *
1695          * @param imageId
1696          *            The ID of the temporary image to delete
1697          */
1698         public void deleteTemporaryImage(String imageId) {
1699                 checkNotNull(imageId, "imageId must not be null");
1700                 synchronized (temporaryImages) {
1701                         temporaryImages.remove(imageId);
1702                 }
1703                 Image image = getImage(imageId, false);
1704                 if (image != null) {
1705                         imageInserter.cancelImageInsert(image);
1706                 }
1707         }
1708
1709         /**
1710          * Notifies the core that the configuration, either of the core or of a
1711          * single local Sone, has changed, and that the configuration should be
1712          * saved.
1713          */
1714         public void touchConfiguration() {
1715                 lastConfigurationUpdate = System.currentTimeMillis();
1716         }
1717
1718         //
1719         // SERVICE METHODS
1720         //
1721
1722         /**
1723          * Starts the core.
1724          */
1725         @Override
1726         public void serviceStart() {
1727                 loadConfiguration();
1728                 updateChecker.start();
1729                 identityManager.start();
1730                 webOfTrustUpdater.init();
1731                 webOfTrustUpdater.start();
1732                 database.start();
1733         }
1734
1735         /**
1736          * {@inheritDoc}
1737          */
1738         @Override
1739         public void serviceRun() {
1740                 long lastSaved = System.currentTimeMillis();
1741                 while (!shouldStop()) {
1742                         sleep(1000);
1743                         long now = System.currentTimeMillis();
1744                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1745                                 for (Sone localSone : getLocalSones()) {
1746                                         saveSone(localSone);
1747                                 }
1748                                 saveConfiguration();
1749                                 lastSaved = now;
1750                         }
1751                 }
1752         }
1753
1754         /**
1755          * Stops the core.
1756          */
1757         @Override
1758         public void serviceStop() {
1759                 localElementTicker.shutdownNow();
1760                 synchronized (sones) {
1761                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1762                                 soneInserter.getValue().stop();
1763                                 saveSone(soneInserter.getKey());
1764                         }
1765                 }
1766                 saveConfiguration();
1767                 database.stop();
1768                 webOfTrustUpdater.stop();
1769                 updateChecker.stop();
1770                 soneDownloader.stop();
1771                 soneDownloaders.shutdown();
1772                 identityManager.stop();
1773         }
1774
1775         //
1776         // PRIVATE METHODS
1777         //
1778
1779         /**
1780          * Saves the given Sone. This will persist all local settings for the given
1781          * Sone, such as the friends list and similar, private options.
1782          *
1783          * @param sone
1784          *            The Sone to save
1785          */
1786         private synchronized void saveSone(Sone sone) {
1787                 if (!sone.isLocal()) {
1788                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1789                         return;
1790                 }
1791                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1792                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1793                         return;
1794                 }
1795
1796                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1797                 try {
1798                         /* save Sone into configuration. */
1799                         String sonePrefix = "Sone/" + sone.getId();
1800                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1801                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1802
1803                         /* save profile. */
1804                         Profile profile = sone.getProfile();
1805                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1806                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1807                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1808                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1809                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1810                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1811                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1812
1813                         /* save profile fields. */
1814                         int fieldCounter = 0;
1815                         for (Field profileField : profile.getFields()) {
1816                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1817                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1818                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1819                         }
1820                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1821
1822                         /* save posts. */
1823                         int postCounter = 0;
1824                         for (Post post : sone.getPosts()) {
1825                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1826                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1827                                 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1828                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1829                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1830                         }
1831                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1832
1833                         /* save replies. */
1834                         int replyCounter = 0;
1835                         for (PostReply reply : sone.getReplies()) {
1836                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1837                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1838                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1839                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1840                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1841                         }
1842                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1843
1844                         /* save post likes. */
1845                         int postLikeCounter = 0;
1846                         for (String postId : sone.getLikedPostIds()) {
1847                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1848                         }
1849                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1850
1851                         /* save reply likes. */
1852                         int replyLikeCounter = 0;
1853                         for (String replyId : sone.getLikedReplyIds()) {
1854                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1855                         }
1856                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1857
1858                         /* save friends. */
1859                         int friendCounter = 0;
1860                         for (String friendId : sone.getFriends()) {
1861                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1862                         }
1863                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1864
1865                         /* save albums. first, collect in a flat structure, top-level first. */
1866                         List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1867
1868                         int albumCounter = 0;
1869                         for (Album album : albums) {
1870                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1871                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1872                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1873                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1874                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1875                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1876                         }
1877                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1878
1879                         /* save images. */
1880                         int imageCounter = 0;
1881                         for (Album album : albums) {
1882                                 for (Image image : album.getImages()) {
1883                                         if (!image.isInserted()) {
1884                                                 continue;
1885                                         }
1886                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1887                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1888                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1889                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1890                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1891                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1892                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1893                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1894                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1895                                 }
1896                         }
1897                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1898
1899                         /* save options. */
1900                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1901                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1902                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1903                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1904                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1905                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1906
1907                         configuration.save();
1908
1909                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1910
1911                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1912                 } catch (ConfigurationException ce1) {
1913                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1914                 }
1915         }
1916
1917         /**
1918          * Saves the current options.
1919          */
1920         private void saveConfiguration() {
1921                 synchronized (configuration) {
1922                         if (storingConfiguration) {
1923                                 logger.log(Level.FINE, "Already storing configuration…");
1924                                 return;
1925                         }
1926                         storingConfiguration = true;
1927                 }
1928
1929                 /* store the options first. */
1930                 try {
1931                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1932                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1933                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1934                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1935                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1936                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1937                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1938                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1939                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1940                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1941                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1942                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1943
1944                         /* save known Sones. */
1945                         int soneCounter = 0;
1946                         synchronized (knownSones) {
1947                                 for (String knownSoneId : knownSones) {
1948                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1949                                 }
1950                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1951                         }
1952
1953                         /* save Sone following times. */
1954                         soneCounter = 0;
1955                         synchronized (soneFollowingTimes) {
1956                                 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1957                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1958                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1959                                         ++soneCounter;
1960                                 }
1961                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1962                         }
1963
1964                         /* save known posts. */
1965                         database.save();
1966
1967                         /* save bookmarked posts. */
1968                         int bookmarkedPostCounter = 0;
1969                         synchronized (bookmarkedPosts) {
1970                                 for (String bookmarkedPostId : bookmarkedPosts) {
1971                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1972                                 }
1973                         }
1974                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1975
1976                         /* now save it. */
1977                         configuration.save();
1978
1979                 } catch (ConfigurationException ce1) {
1980                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1981                 } catch (DatabaseException de1) {
1982                         logger.log(Level.SEVERE, "Could not save database!", de1);
1983                 } finally {
1984                         synchronized (configuration) {
1985                                 storingConfiguration = false;
1986                         }
1987                 }
1988         }
1989
1990         /**
1991          * Loads the configuration.
1992          */
1993         private void loadConfiguration() {
1994                 /* create options. */
1995                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1996
1997                         @Override
1998                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1999                                 SoneInserter.setInsertionDelay(newValue);
2000                         }
2001
2002                 }));
2003                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2004                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2005                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2006                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2007                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2008                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2009                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2010                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2011                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2012
2013                         @Override
2014                         @SuppressWarnings("synthetic-access")
2015                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2016                                 fcpInterface.setActive(newValue);
2017                         }
2018                 }));
2019                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2020
2021                         @Override
2022                         @SuppressWarnings("synthetic-access")
2023                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2024                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2025                         }
2026
2027                 }));
2028
2029                 loadConfigurationValue("InsertionDelay");
2030                 loadConfigurationValue("PostsPerPage");
2031                 loadConfigurationValue("ImagesPerPage");
2032                 loadConfigurationValue("CharactersPerPost");
2033                 loadConfigurationValue("PostCutOffLength");
2034                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2035                 loadConfigurationValue("PositiveTrust");
2036                 loadConfigurationValue("NegativeTrust");
2037                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2038                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2039                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2040
2041                 /* load known Sones. */
2042                 int soneCounter = 0;
2043                 while (true) {
2044                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2045                         if (knownSoneId == null) {
2046                                 break;
2047                         }
2048                         synchronized (knownSones) {
2049                                 knownSones.add(knownSoneId);
2050                         }
2051                 }
2052
2053                 /* load Sone following times. */
2054                 soneCounter = 0;
2055                 while (true) {
2056                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2057                         if (soneId == null) {
2058                                 break;
2059                         }
2060                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2061                         synchronized (soneFollowingTimes) {
2062                                 soneFollowingTimes.put(soneId, time);
2063                         }
2064                         ++soneCounter;
2065                 }
2066
2067                 /* load bookmarked posts. */
2068                 int bookmarkedPostCounter = 0;
2069                 while (true) {
2070                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2071                         if (bookmarkedPostId == null) {
2072                                 break;
2073                         }
2074                         synchronized (bookmarkedPosts) {
2075                                 bookmarkedPosts.add(bookmarkedPostId);
2076                         }
2077                 }
2078
2079         }
2080
2081         /**
2082          * Loads an {@link Integer} configuration value for the option with the
2083          * given name, logging validation failures.
2084          *
2085          * @param optionName
2086          *            The name of the option to load
2087          */
2088         private void loadConfigurationValue(String optionName) {
2089                 try {
2090                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2091                 } catch (IllegalArgumentException iae1) {
2092                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2093                 }
2094         }
2095
2096         /**
2097          * Notifies the core that a new {@link OwnIdentity} was added.
2098          *
2099          * @param ownIdentityAddedEvent
2100          *            The event
2101          */
2102         @Subscribe
2103         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2104                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2105                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2106                 if (ownIdentity.hasContext("Sone")) {
2107                         addLocalSone(ownIdentity);
2108                 }
2109         }
2110
2111         /**
2112          * Notifies the core that an {@link OwnIdentity} was removed.
2113          *
2114          * @param ownIdentityRemovedEvent
2115          *            The event
2116          */
2117         @Subscribe
2118         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2119                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2120                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2121                 trustedIdentities.removeAll(ownIdentity);
2122         }
2123
2124         /**
2125          * Notifies the core that a new {@link Identity} was added.
2126          *
2127          * @param identityAddedEvent
2128          *            The event
2129          */
2130         @Subscribe
2131         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2132                 Identity identity = identityAddedEvent.identity();
2133                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2134                 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2135                 addRemoteSone(identity);
2136         }
2137
2138         /**
2139          * Notifies the core that an {@link Identity} was updated.
2140          *
2141          * @param identityUpdatedEvent
2142          *            The event
2143          */
2144         @Subscribe
2145         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2146                 final Identity identity = identityUpdatedEvent.identity();
2147                 soneDownloaders.execute(new Runnable() {
2148
2149                         @Override
2150                         @SuppressWarnings("synthetic-access")
2151                         public void run() {
2152                                 Sone sone = getRemoteSone(identity.getId(), false);
2153                                 if (sone.isLocal()) {
2154                                         return;
2155                                 }
2156                                 sone.setIdentity(identity);
2157                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2158                                 soneDownloader.addSone(sone);
2159                                 soneDownloader.fetchSone(sone);
2160                         }
2161                 });
2162         }
2163
2164         /**
2165          * Notifies the core that an {@link Identity} was removed.
2166          *
2167          * @param identityRemovedEvent
2168          *            The event
2169          */
2170         @Subscribe
2171         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2172                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2173                 Identity identity = identityRemovedEvent.identity();
2174                 trustedIdentities.remove(ownIdentity, identity);
2175                 boolean foundIdentity = false;
2176                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2177                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2178                                 continue;
2179                         }
2180                         if (trustedIdentity.getValue().contains(identity)) {
2181                                 foundIdentity = true;
2182                         }
2183                 }
2184                 if (foundIdentity) {
2185                         /* some local identity still trusts this identity, don’t remove. */
2186                         return;
2187                 }
2188                 Optional<Sone> sone = getSone(identity.getId());
2189                 if (!sone.isPresent()) {
2190                         /* TODO - we don’t have the Sone anymore. should this happen? */
2191                         return;
2192                 }
2193                 database.removePosts(sone.get());
2194                 for (Post post : sone.get().getPosts()) {
2195                         eventBus.post(new PostRemovedEvent(post));
2196                 }
2197                 database.removePostReplies(sone.get());
2198                 for (PostReply reply : sone.get().getReplies()) {
2199                         eventBus.post(new PostReplyRemovedEvent(reply));
2200                 }
2201                 synchronized (sones) {
2202                         sones.remove(identity.getId());
2203                 }
2204                 eventBus.post(new SoneRemovedEvent(sone.get()));
2205         }
2206
2207         /**
2208          * Deletes the temporary image.
2209          *
2210          * @param imageInsertFinishedEvent
2211          *            The event
2212          */
2213         @Subscribe
2214         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2215                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2216                 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2217                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2218                 touchConfiguration();
2219         }
2220
2221 }