Set Sone of an album in the album builder, use album builder to add albums.
[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.Collection;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Set;
31 import java.util.concurrent.ExecutorService;
32 import java.util.concurrent.Executors;
33 import java.util.concurrent.ScheduledExecutorService;
34 import java.util.concurrent.TimeUnit;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
37
38 import net.pterodactylus.sone.core.Options.DefaultOption;
39 import net.pterodactylus.sone.core.Options.Option;
40 import net.pterodactylus.sone.core.Options.OptionWatcher;
41 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
42 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
43 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
44 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
45 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
46 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
47 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
48 import net.pterodactylus.sone.core.event.PostRemovedEvent;
49 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
50 import net.pterodactylus.sone.core.event.SoneLockedEvent;
51 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
53 import net.pterodactylus.sone.data.Album;
54 import net.pterodactylus.sone.data.Client;
55 import net.pterodactylus.sone.data.Image;
56 import net.pterodactylus.sone.data.Post;
57 import net.pterodactylus.sone.data.PostReply;
58 import net.pterodactylus.sone.data.Profile;
59 import net.pterodactylus.sone.data.Profile.Field;
60 import net.pterodactylus.sone.data.Reply;
61 import net.pterodactylus.sone.data.Sone;
62 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
63 import net.pterodactylus.sone.data.Sone.SoneStatus;
64 import net.pterodactylus.sone.data.SoneImpl;
65 import net.pterodactylus.sone.data.TemporaryImage;
66 import net.pterodactylus.sone.database.Database;
67 import net.pterodactylus.sone.database.DatabaseException;
68 import net.pterodactylus.sone.database.PostBuilder;
69 import net.pterodactylus.sone.database.PostProvider;
70 import net.pterodactylus.sone.database.PostReplyBuilder;
71 import net.pterodactylus.sone.database.PostReplyProvider;
72 import net.pterodactylus.sone.database.SoneProvider;
73 import net.pterodactylus.sone.fcp.FcpInterface;
74 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
75 import net.pterodactylus.sone.freenet.wot.Identity;
76 import net.pterodactylus.sone.freenet.wot.IdentityManager;
77 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
78 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
83 import net.pterodactylus.sone.main.SonePlugin;
84 import net.pterodactylus.sone.utils.IntegerRangePredicate;
85 import net.pterodactylus.util.config.Configuration;
86 import net.pterodactylus.util.config.ConfigurationException;
87 import net.pterodactylus.util.logging.Logging;
88 import net.pterodactylus.util.number.Numbers;
89 import net.pterodactylus.util.service.AbstractService;
90 import net.pterodactylus.util.thread.NamedThreadFactory;
91
92 import com.google.common.base.Optional;
93 import com.google.common.base.Predicate;
94 import com.google.common.base.Predicates;
95 import com.google.common.collect.FluentIterable;
96 import com.google.common.collect.HashMultimap;
97 import com.google.common.collect.ImmutableSet;
98 import com.google.common.collect.Maps;
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         public Optional<Album> getAlbum(String albumId) {
610                 return database.getAlbum(albumId);
611         }
612
613         public Optional<Image> getImage(String imageId) {
614                 return database.getImage(imageId);
615         }
616
617         /**
618          * Returns the temporary image with the given ID.
619          *
620          * @param imageId
621          *            The ID of the temporary image
622          * @return The temporary image, or {@code null} if there is no temporary
623          *         image with the given ID
624          */
625         public TemporaryImage getTemporaryImage(String imageId) {
626                 synchronized (temporaryImages) {
627                         return temporaryImages.get(imageId);
628                 }
629         }
630
631         //
632         // ACTIONS
633         //
634
635         /**
636          * Locks the given Sone. A locked Sone will not be inserted by
637          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
638          * again.
639          *
640          * @param sone
641          *            The sone to lock
642          */
643         public void lockSone(Sone sone) {
644                 synchronized (lockedSones) {
645                         if (lockedSones.add(sone)) {
646                                 eventBus.post(new SoneLockedEvent(sone));
647                         }
648                 }
649         }
650
651         /**
652          * Unlocks the given Sone.
653          *
654          * @see #lockSone(Sone)
655          * @param sone
656          *            The sone to unlock
657          */
658         public void unlockSone(Sone sone) {
659                 synchronized (lockedSones) {
660                         if (lockedSones.remove(sone)) {
661                                 eventBus.post(new SoneUnlockedEvent(sone));
662                         }
663                 }
664         }
665
666         /**
667          * Adds a local Sone from the given own identity.
668          *
669          * @param ownIdentity
670          *            The own identity to create a Sone from
671          * @return The added (or already existing) Sone
672          */
673         public Sone addLocalSone(OwnIdentity ownIdentity) {
674                 if (ownIdentity == null) {
675                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
676                         return null;
677                 }
678                 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
679                 synchronized (sones) {
680                         final Sone sone;
681                         try {
682                                 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
683                         } catch (MalformedURLException mue1) {
684                                 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
685                                 return null;
686                         }
687                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
688                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
689                         sone.setKnown(true);
690                         /* TODO - load posts ’n stuff */
691                         sones.put(ownIdentity.getId(), sone);
692                         final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
693                         soneInserters.put(sone, soneInserter);
694                         sone.setStatus(SoneStatus.idle);
695                         loadSone(sone);
696                         soneInserter.start();
697                         return sone;
698                 }
699         }
700
701         /**
702          * Creates a new Sone for the given own identity.
703          *
704          * @param ownIdentity
705          *            The own identity to create a Sone for
706          * @return The created Sone
707          */
708         public Sone createSone(OwnIdentity ownIdentity) {
709                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
710                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
711                         return null;
712                 }
713                 Sone sone = addLocalSone(ownIdentity);
714                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
715                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
716                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
717                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
718                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
719                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
720
721                 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
722                 touchConfiguration();
723                 return sone;
724         }
725
726         /**
727          * Adds the Sone of the given identity.
728          *
729          * @param identity
730          *            The identity whose Sone to add
731          * @return The added or already existing Sone
732          */
733         public Sone addRemoteSone(Identity identity) {
734                 if (identity == null) {
735                         logger.log(Level.WARNING, "Given Identity is null!");
736                         return null;
737                 }
738                 synchronized (sones) {
739                         final Sone sone = getRemoteSone(identity.getId(), true);
740                         if (sone.isLocal()) {
741                                 return sone;
742                         }
743                         sone.setIdentity(identity);
744                         boolean newSone = sone.getRequestUri() == null;
745                         sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
746                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
747                         if (newSone) {
748                                 synchronized (knownSones) {
749                                         newSone = !knownSones.contains(sone.getId());
750                                 }
751                                 sone.setKnown(!newSone);
752                                 if (newSone) {
753                                         eventBus.post(new NewSoneFoundEvent(sone));
754                                         for (Sone localSone : getLocalSones()) {
755                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
756                                                         followSone(localSone, sone.getId());
757                                                 }
758                                         }
759                                 }
760                         }
761                         soneDownloader.addSone(sone);
762                         soneDownloaders.execute(new Runnable() {
763
764                                 @Override
765                                 @SuppressWarnings("synthetic-access")
766                                 public void run() {
767                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
768                                 }
769
770                         });
771                         return sone;
772                 }
773         }
774
775         /**
776          * Lets the given local Sone follow the Sone with the given ID.
777          *
778          * @param sone
779          *            The local Sone that should follow another Sone
780          * @param soneId
781          *            The ID of the Sone to follow
782          */
783         public void followSone(Sone sone, String soneId) {
784                 checkNotNull(sone, "sone must not be null");
785                 checkNotNull(soneId, "soneId must not be null");
786                 sone.addFriend(soneId);
787                 synchronized (soneFollowingTimes) {
788                         if (!soneFollowingTimes.containsKey(soneId)) {
789                                 long now = System.currentTimeMillis();
790                                 soneFollowingTimes.put(soneId, now);
791                                 Optional<Sone> followedSone = getSone(soneId);
792                                 if (!followedSone.isPresent()) {
793                                         return;
794                                 }
795                                 for (Post post : followedSone.get().getPosts()) {
796                                         if (post.getTime() < now) {
797                                                 markPostKnown(post);
798                                         }
799                                 }
800                                 for (PostReply reply : followedSone.get().getReplies()) {
801                                         if (reply.getTime() < now) {
802                                                 markReplyKnown(reply);
803                                         }
804                                 }
805                         }
806                 }
807                 touchConfiguration();
808         }
809
810         /**
811          * Lets the given local Sone unfollow the Sone with the given ID.
812          *
813          * @param sone
814          *            The local Sone that should unfollow another Sone
815          * @param soneId
816          *            The ID of the Sone being unfollowed
817          */
818         public void unfollowSone(Sone sone, String soneId) {
819                 checkNotNull(sone, "sone must not be null");
820                 checkNotNull(soneId, "soneId must not be null");
821                 sone.removeFriend(soneId);
822                 boolean unfollowedSoneStillFollowed = false;
823                 for (Sone localSone : getLocalSones()) {
824                         unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
825                 }
826                 if (!unfollowedSoneStillFollowed) {
827                         synchronized (soneFollowingTimes) {
828                                 soneFollowingTimes.remove(soneId);
829                         }
830                 }
831                 touchConfiguration();
832         }
833
834         /**
835          * Sets the trust value of the given origin Sone for the target Sone.
836          *
837          * @param origin
838          *            The origin Sone
839          * @param target
840          *            The target Sone
841          * @param trustValue
842          *            The trust value (from {@code -100} to {@code 100})
843          */
844         public void setTrust(Sone origin, Sone target, int trustValue) {
845                 checkNotNull(origin, "origin must not be null");
846                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
847                 checkNotNull(target, "target must not be null");
848                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
849                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
850         }
851
852         /**
853          * Removes any trust assignment for the given target Sone.
854          *
855          * @param origin
856          *            The trust origin
857          * @param target
858          *            The trust target
859          */
860         public void removeTrust(Sone origin, Sone target) {
861                 checkNotNull(origin, "origin must not be null");
862                 checkNotNull(target, "target must not be null");
863                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
864                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
865         }
866
867         /**
868          * Assigns the configured positive trust value for the given target.
869          *
870          * @param origin
871          *            The trust origin
872          * @param target
873          *            The trust target
874          */
875         public void trustSone(Sone origin, Sone target) {
876                 setTrust(origin, target, preferences.getPositiveTrust());
877         }
878
879         /**
880          * Assigns the configured negative trust value for the given target.
881          *
882          * @param origin
883          *            The trust origin
884          * @param target
885          *            The trust target
886          */
887         public void distrustSone(Sone origin, Sone target) {
888                 setTrust(origin, target, preferences.getNegativeTrust());
889         }
890
891         /**
892          * Removes the trust assignment for the given target.
893          *
894          * @param origin
895          *            The trust origin
896          * @param target
897          *            The trust target
898          */
899         public void untrustSone(Sone origin, Sone target) {
900                 removeTrust(origin, target);
901         }
902
903         /**
904          * Updates the stored Sone with the given Sone.
905          *
906          * @param sone
907          *            The updated Sone
908          */
909         public void updateSone(Sone sone) {
910                 updateSone(sone, false);
911         }
912
913         /**
914          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
915          * {@code true}, an older Sone than the current Sone can be given to restore
916          * an old state.
917          *
918          * @param sone
919          *            The Sone to update
920          * @param soneRescueMode
921          *            {@code true} if the stored Sone should be updated regardless
922          *            of the age of the given Sone
923          */
924         public void updateSone(Sone sone, boolean soneRescueMode) {
925                 Optional<Sone> storedSone = getSone(sone.getId());
926                 if (storedSone.isPresent()) {
927                         if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
928                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
929                                 return;
930                         }
931                         /* find removed posts. */
932                         Collection<Post> existingPosts = database.getPosts(sone.getId());
933                         for (Post oldPost : existingPosts) {
934                                 if (!sone.getPosts().contains(oldPost)) {
935                                         eventBus.post(new PostRemovedEvent(oldPost));
936                                 }
937                         }
938                         /* find new posts. */
939                         for (Post newPost : sone.getPosts()) {
940                                 if (existingPosts.contains(newPost)) {
941                                         continue;
942                                 }
943                                 if (newPost.getTime() < getSoneFollowingTime(sone)) {
944                                         newPost.setKnown(true);
945                                 } else if (!newPost.isKnown()) {
946                                         eventBus.post(new NewPostFoundEvent(newPost));
947                                 }
948                         }
949                         /* store posts. */
950                         database.storePosts(sone, sone.getPosts());
951                         if (!soneRescueMode) {
952                                 for (PostReply reply : storedSone.get().getReplies()) {
953                                         if (!sone.getReplies().contains(reply)) {
954                                                 eventBus.post(new PostReplyRemovedEvent(reply));
955                                         }
956                                 }
957                         }
958                         Set<PostReply> storedReplies = storedSone.get().getReplies();
959                         for (PostReply reply : sone.getReplies()) {
960                                 if (storedReplies.contains(reply)) {
961                                         continue;
962                                 }
963                                 if (reply.getTime() < getSoneFollowingTime(sone)) {
964                                         reply.setKnown(true);
965                                 } else if (!reply.isKnown()) {
966                                         eventBus.post(new NewPostReplyFoundEvent(reply));
967                                 }
968                         }
969                         database.storePostReplies(sone, sone.getReplies());
970                         for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
971                                 database.removeAlbum(album);
972                                 for (Image image : album.getImages()) {
973                                         database.removeImage(image);
974                                 }
975                         }
976                         for (Album album : sone.getRootAlbum().getAlbums()) {
977                                 database.storeAlbum(album);
978                                 for (Image image : album.getImages()) {
979                                         database.storeImage(image);
980                                 }
981                         }
982                         synchronized (sones) {
983                                 sone.setOptions(storedSone.get().getOptions());
984                                 sone.setKnown(storedSone.get().isKnown());
985                                 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
986                                 if (sone.isLocal()) {
987                                         soneInserters.get(storedSone.get()).setSone(sone);
988                                         touchConfiguration();
989                                 }
990                                 sones.put(sone.getId(), sone);
991                         }
992                 }
993         }
994
995         /**
996          * Deletes the given Sone. This will remove the Sone from the
997          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
998          * remove the context from its identity.
999          *
1000          * @param sone
1001          *            The Sone to delete
1002          */
1003         public void deleteSone(Sone sone) {
1004                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1005                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1006                         return;
1007                 }
1008                 synchronized (sones) {
1009                         if (!getLocalSones().contains(sone)) {
1010                                 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1011                                 return;
1012                         }
1013                         sones.remove(sone.getId());
1014                         SoneInserter soneInserter = soneInserters.remove(sone);
1015                         soneInserter.stop();
1016                 }
1017                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1018                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1019                 try {
1020                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1021                 } catch (ConfigurationException ce1) {
1022                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1023                 }
1024         }
1025
1026         /**
1027          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1028          * known} before, a {@link MarkSoneKnownEvent} is fired.
1029          *
1030          * @param sone
1031          *            The Sone to mark as known
1032          */
1033         public void markSoneKnown(Sone sone) {
1034                 if (!sone.isKnown()) {
1035                         sone.setKnown(true);
1036                         synchronized (knownSones) {
1037                                 knownSones.add(sone.getId());
1038                         }
1039                         eventBus.post(new MarkSoneKnownEvent(sone));
1040                         touchConfiguration();
1041                 }
1042         }
1043
1044         /**
1045          * Loads and updates the given Sone from the configuration. If any error is
1046          * encountered, loading is aborted and the given Sone is not changed.
1047          *
1048          * @param sone
1049          *            The Sone to load and update
1050          */
1051         public void loadSone(Sone sone) {
1052                 if (!sone.isLocal()) {
1053                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1054                         return;
1055                 }
1056                 logger.info(String.format("Loading local Sone: %s", sone));
1057
1058                 /* initialize options. */
1059                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1060                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1061                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1062                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1063                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1064                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1065
1066                 /* load Sone. */
1067                 String sonePrefix = "Sone/" + sone.getId();
1068                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1069                 if (soneTime == null) {
1070                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1071                         return;
1072                 }
1073                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1074
1075                 /* load profile. */
1076                 Profile profile = new Profile(sone);
1077                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1078                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1079                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1080                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1081                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1082                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1083
1084                 /* load profile fields. */
1085                 while (true) {
1086                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1087                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1088                         if (fieldName == null) {
1089                                 break;
1090                         }
1091                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1092                         profile.addField(fieldName).setValue(fieldValue);
1093                 }
1094
1095                 /* load posts. */
1096                 Set<Post> posts = new HashSet<Post>();
1097                 while (true) {
1098                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1099                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1100                         if (postId == null) {
1101                                 break;
1102                         }
1103                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1104                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1105                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1106                         if ((postTime == 0) || (postText == null)) {
1107                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1108                                 return;
1109                         }
1110                         PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1111                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1112                                 postBuilder.to(postRecipientId);
1113                         }
1114                         posts.add(postBuilder.build());
1115                 }
1116
1117                 /* load replies. */
1118                 Set<PostReply> replies = new HashSet<PostReply>();
1119                 while (true) {
1120                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1121                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1122                         if (replyId == null) {
1123                                 break;
1124                         }
1125                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1126                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1127                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1128                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1129                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1130                                 return;
1131                         }
1132                         PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1133                         replies.add(postReplyBuilder.build());
1134                 }
1135
1136                 /* load post likes. */
1137                 Set<String> likedPostIds = new HashSet<String>();
1138                 while (true) {
1139                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1140                         if (likedPostId == null) {
1141                                 break;
1142                         }
1143                         likedPostIds.add(likedPostId);
1144                 }
1145
1146                 /* load reply likes. */
1147                 Set<String> likedReplyIds = new HashSet<String>();
1148                 while (true) {
1149                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1150                         if (likedReplyId == null) {
1151                                 break;
1152                         }
1153                         likedReplyIds.add(likedReplyId);
1154                 }
1155
1156                 /* load friends. */
1157                 Set<String> friends = new HashSet<String>();
1158                 while (true) {
1159                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1160                         if (friendId == null) {
1161                                 break;
1162                         }
1163                         friends.add(friendId);
1164                 }
1165
1166                 /* load albums. */
1167                 Map<String, Album> albums = Maps.newHashMap();
1168                 int albumCounter = 0;
1169                 while (true) {
1170                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1171                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1172                         if (albumId == null) {
1173                                 break;
1174                         }
1175                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1176                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1177                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1178                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1179                         if ((albumTitle == null) || (albumDescription == null)) {
1180                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1181                                 return;
1182                         }
1183                         Album parentAlbum = sone.getRootAlbum();
1184                         if (albumParentId != null) {
1185                                 parentAlbum = albums.get(albumParentId);
1186                         }
1187                         Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1188                         albums.put(album.getId(), album);
1189                 }
1190
1191                 /* load images. */
1192                 int imageCounter = 0;
1193                 while (true) {
1194                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1195                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1196                         if (imageId == null) {
1197                                 break;
1198                         }
1199                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1200                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1201                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1202                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1203                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1204                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1205                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1206                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1207                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1208                                 return;
1209                         }
1210                         Album album = albums.get(albumId);
1211                         if (album == null) {
1212                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1213                                 return;
1214                         }
1215                         album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build().modify().setTitle(title).setDescription(description).update();
1216                 }
1217
1218                 /* load avatar. */
1219                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1220                 if (avatarId != null) {
1221                         profile.setAvatar(getImage(avatarId).orNull());
1222                 }
1223
1224                 /* load options. */
1225                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1226                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1227                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1228                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1229                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1230                 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1231
1232                 /* if we’re still here, Sone was loaded successfully. */
1233                 synchronized (sone) {
1234                         sone.setTime(soneTime);
1235                         sone.setProfile(profile);
1236                         sone.setPosts(posts);
1237                         sone.setReplies(replies);
1238                         sone.setLikePostIds(likedPostIds);
1239                         sone.setLikeReplyIds(likedReplyIds);
1240                         for (String friendId : friends) {
1241                                 followSone(sone, friendId);
1242                         }
1243                         for (Album album : sone.getRootAlbum().getAlbums()) {
1244                                 sone.getRootAlbum().removeAlbum(album);
1245                         }
1246                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1247                 }
1248                 synchronized (knownSones) {
1249                         for (String friend : friends) {
1250                                 knownSones.add(friend);
1251                         }
1252                 }
1253                 database.storePosts(sone, posts);
1254                 for (Post post : posts) {
1255                         post.setKnown(true);
1256                 }
1257                 database.storePostReplies(sone, replies);
1258                 for (PostReply reply : replies) {
1259                         reply.setKnown(true);
1260                 }
1261
1262                 logger.info(String.format("Sone loaded successfully: %s", sone));
1263         }
1264
1265         /**
1266          * Creates a new post.
1267          *
1268          * @param sone
1269          *            The Sone that creates the post
1270          * @param text
1271          *            The text of the post
1272          * @return The created post
1273          */
1274         public Post createPost(Sone sone, String text) {
1275                 return createPost(sone, System.currentTimeMillis(), text);
1276         }
1277
1278         /**
1279          * Creates a new post.
1280          *
1281          * @param sone
1282          *            The Sone that creates the post
1283          * @param time
1284          *            The time of the post
1285          * @param text
1286          *            The text of the post
1287          * @return The created post
1288          */
1289         public Post createPost(Sone sone, long time, String text) {
1290                 return createPost(sone, null, time, text);
1291         }
1292
1293         /**
1294          * Creates a new post.
1295          *
1296          * @param sone
1297          *            The Sone that creates the post
1298          * @param recipient
1299          *            The recipient Sone, or {@code null} if this post does not have
1300          *            a recipient
1301          * @param text
1302          *            The text of the post
1303          * @return The created post
1304          */
1305         public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1306                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1307         }
1308
1309         /**
1310          * Creates a new post.
1311          *
1312          * @param sone
1313          *            The Sone that creates the post
1314          * @param recipient
1315          *            The recipient Sone, or {@code null} if this post does not have
1316          *            a recipient
1317          * @param time
1318          *            The time of the post
1319          * @param text
1320          *            The text of the post
1321          * @return The created post
1322          */
1323         public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1324                 checkNotNull(text, "text must not be null");
1325                 checkArgument(text.trim().length() > 0, "text must not be empty");
1326                 if (!sone.isLocal()) {
1327                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1328                         return null;
1329                 }
1330                 PostBuilder postBuilder = database.newPostBuilder();
1331                 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1332                 if (recipient.isPresent()) {
1333                         postBuilder.to(recipient.get().getId());
1334                 }
1335                 final Post post = postBuilder.build();
1336                 database.storePost(post);
1337                 eventBus.post(new NewPostFoundEvent(post));
1338                 sone.addPost(post);
1339                 touchConfiguration();
1340                 localElementTicker.schedule(new Runnable() {
1341
1342                         /**
1343                          * {@inheritDoc}
1344                          */
1345                         @Override
1346                         public void run() {
1347                                 markPostKnown(post);
1348                         }
1349                 }, 10, TimeUnit.SECONDS);
1350                 return post;
1351         }
1352
1353         /**
1354          * Deletes the given post.
1355          *
1356          * @param post
1357          *            The post to delete
1358          */
1359         public void deletePost(Post post) {
1360                 if (!post.getSone().isLocal()) {
1361                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1362                         return;
1363                 }
1364                 database.removePost(post);
1365                 eventBus.post(new PostRemovedEvent(post));
1366                 markPostKnown(post);
1367                 touchConfiguration();
1368         }
1369
1370         /**
1371          * Marks the given post as known, if it is currently not a known post
1372          * (according to {@link Post#isKnown()}).
1373          *
1374          * @param post
1375          *            The post to mark as known
1376          */
1377         public void markPostKnown(Post post) {
1378                 post.setKnown(true);
1379                 eventBus.post(new MarkPostKnownEvent(post));
1380                 touchConfiguration();
1381                 for (PostReply reply : getReplies(post.getId())) {
1382                         markReplyKnown(reply);
1383                 }
1384         }
1385
1386         /**
1387          * Bookmarks the given post.
1388          *
1389          * @param post
1390          *            The post to bookmark
1391          */
1392         public void bookmark(Post post) {
1393                 bookmarkPost(post.getId());
1394         }
1395
1396         /**
1397          * Bookmarks the post with the given ID.
1398          *
1399          * @param id
1400          *            The ID of the post to bookmark
1401          */
1402         public void bookmarkPost(String id) {
1403                 synchronized (bookmarkedPosts) {
1404                         bookmarkedPosts.add(id);
1405                 }
1406         }
1407
1408         /**
1409          * Removes the given post from the bookmarks.
1410          *
1411          * @param post
1412          *            The post to unbookmark
1413          */
1414         public void unbookmark(Post post) {
1415                 unbookmarkPost(post.getId());
1416         }
1417
1418         /**
1419          * Removes the post with the given ID from the bookmarks.
1420          *
1421          * @param id
1422          *            The ID of the post to unbookmark
1423          */
1424         public void unbookmarkPost(String id) {
1425                 synchronized (bookmarkedPosts) {
1426                         bookmarkedPosts.remove(id);
1427                 }
1428         }
1429
1430         /**
1431          * Creates a new reply.
1432          *
1433          * @param sone
1434          *            The Sone that creates the reply
1435          * @param post
1436          *            The post that this reply refers to
1437          * @param text
1438          *            The text of the reply
1439          * @return The created reply
1440          */
1441         public PostReply createReply(Sone sone, Post post, String text) {
1442                 checkNotNull(text, "text must not be null");
1443                 checkArgument(text.trim().length() > 0, "text must not be empty");
1444                 if (!sone.isLocal()) {
1445                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1446                         return null;
1447                 }
1448                 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1449                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1450                 final PostReply reply = postReplyBuilder.build();
1451                 database.storePostReply(reply);
1452                 eventBus.post(new NewPostReplyFoundEvent(reply));
1453                 sone.addReply(reply);
1454                 touchConfiguration();
1455                 localElementTicker.schedule(new Runnable() {
1456
1457                         /**
1458                          * {@inheritDoc}
1459                          */
1460                         @Override
1461                         public void run() {
1462                                 markReplyKnown(reply);
1463                         }
1464                 }, 10, TimeUnit.SECONDS);
1465                 return reply;
1466         }
1467
1468         /**
1469          * Deletes the given reply.
1470          *
1471          * @param reply
1472          *            The reply to delete
1473          */
1474         public void deleteReply(PostReply reply) {
1475                 Sone sone = reply.getSone();
1476                 if (!sone.isLocal()) {
1477                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1478                         return;
1479                 }
1480                 database.removePostReply(reply);
1481                 markReplyKnown(reply);
1482                 sone.removeReply(reply);
1483                 touchConfiguration();
1484         }
1485
1486         /**
1487          * Marks the given reply as known, if it is currently not a known reply
1488          * (according to {@link Reply#isKnown()}).
1489          *
1490          * @param reply
1491          *            The reply to mark as known
1492          */
1493         public void markReplyKnown(PostReply reply) {
1494                 boolean previouslyKnown = reply.isKnown();
1495                 reply.setKnown(true);
1496                 eventBus.post(new MarkPostReplyKnownEvent(reply));
1497                 if (!previouslyKnown) {
1498                         touchConfiguration();
1499                 }
1500         }
1501
1502         /**
1503          * Deletes the given album. The owner of the album has to be a local Sone,
1504          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1505          *
1506          * @param album
1507          *            The album to remove
1508          */
1509         public void deleteAlbum(Album album) {
1510                 checkNotNull(album, "album must not be null");
1511                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1512                 if (!album.isEmpty()) {
1513                         return;
1514                 }
1515                 album.getParent().removeAlbum(album);
1516                 database.removeAlbum(album);
1517                 touchConfiguration();
1518         }
1519
1520         /**
1521          * Creates a new image.
1522          *
1523          * @param sone
1524          *            The Sone creating the image
1525          * @param album
1526          *            The album the image will be inserted into
1527          * @param temporaryImage
1528          *            The temporary image to create the image from
1529          * @return The newly created image
1530          */
1531         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1532                 checkNotNull(sone, "sone must not be null");
1533                 checkNotNull(album, "album must not be null");
1534                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1535                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1536                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1537                 Image image = album.newImageBuilder().withId(temporaryImage.getId()).createdNow().sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build();
1538                 database.storeImage(image);
1539                 imageInserter.insertImage(temporaryImage, image);
1540                 return image;
1541         }
1542
1543         /**
1544          * Deletes the given image. This method will also delete a matching
1545          * temporary image.
1546          *
1547          * @see #deleteTemporaryImage(TemporaryImage)
1548          * @param image
1549          *            The image to delete
1550          */
1551         public void deleteImage(Image image) {
1552                 checkNotNull(image, "image must not be null");
1553                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1554                 deleteTemporaryImage(image.getId());
1555                 image.getAlbum().removeImage(image);
1556                 database.removeImage(image);
1557                 touchConfiguration();
1558         }
1559
1560         /**
1561          * Creates a new temporary image.
1562          *
1563          * @param mimeType
1564          *            The MIME type of the temporary image
1565          * @param imageData
1566          *            The encoded data of the image
1567          * @return The temporary image
1568          */
1569         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1570                 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1571                 synchronized (temporaryImages) {
1572                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1573                 }
1574                 return temporaryImage;
1575         }
1576
1577         /**
1578          * Deletes the given temporary image.
1579          *
1580          * @param temporaryImage
1581          *            The temporary image to delete
1582          */
1583         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1584                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1585                 deleteTemporaryImage(temporaryImage.getId());
1586         }
1587
1588         /**
1589          * Deletes the temporary image with the given ID.
1590          *
1591          * @param imageId
1592          *            The ID of the temporary image to delete
1593          */
1594         public void deleteTemporaryImage(String imageId) {
1595                 checkNotNull(imageId, "imageId must not be null");
1596                 synchronized (temporaryImages) {
1597                         temporaryImages.remove(imageId);
1598                 }
1599                 Optional<Image> image = getImage(imageId);
1600                 if (image.isPresent()) {
1601                         imageInserter.cancelImageInsert(image.get());
1602                 }
1603         }
1604
1605         /**
1606          * Notifies the core that the configuration, either of the core or of a
1607          * single local Sone, has changed, and that the configuration should be
1608          * saved.
1609          */
1610         public void touchConfiguration() {
1611                 lastConfigurationUpdate = System.currentTimeMillis();
1612         }
1613
1614         //
1615         // SERVICE METHODS
1616         //
1617
1618         /**
1619          * Starts the core.
1620          */
1621         @Override
1622         public void serviceStart() {
1623                 loadConfiguration();
1624                 updateChecker.start();
1625                 identityManager.start();
1626                 webOfTrustUpdater.init();
1627                 webOfTrustUpdater.start();
1628                 database.start();
1629         }
1630
1631         /**
1632          * {@inheritDoc}
1633          */
1634         @Override
1635         public void serviceRun() {
1636                 long lastSaved = System.currentTimeMillis();
1637                 while (!shouldStop()) {
1638                         sleep(1000);
1639                         long now = System.currentTimeMillis();
1640                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1641                                 for (Sone localSone : getLocalSones()) {
1642                                         saveSone(localSone);
1643                                 }
1644                                 saveConfiguration();
1645                                 lastSaved = now;
1646                         }
1647                 }
1648         }
1649
1650         /**
1651          * Stops the core.
1652          */
1653         @Override
1654         public void serviceStop() {
1655                 localElementTicker.shutdownNow();
1656                 synchronized (sones) {
1657                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1658                                 soneInserter.getValue().stop();
1659                                 saveSone(soneInserter.getKey());
1660                         }
1661                 }
1662                 saveConfiguration();
1663                 database.stop();
1664                 webOfTrustUpdater.stop();
1665                 updateChecker.stop();
1666                 soneDownloader.stop();
1667                 soneDownloaders.shutdown();
1668                 identityManager.stop();
1669         }
1670
1671         //
1672         // PRIVATE METHODS
1673         //
1674
1675         /**
1676          * Saves the given Sone. This will persist all local settings for the given
1677          * Sone, such as the friends list and similar, private options.
1678          *
1679          * @param sone
1680          *            The Sone to save
1681          */
1682         private synchronized void saveSone(Sone sone) {
1683                 if (!sone.isLocal()) {
1684                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1685                         return;
1686                 }
1687                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1688                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1689                         return;
1690                 }
1691
1692                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1693                 try {
1694                         /* save Sone into configuration. */
1695                         String sonePrefix = "Sone/" + sone.getId();
1696                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1697                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1698
1699                         /* save profile. */
1700                         Profile profile = sone.getProfile();
1701                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1702                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1703                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1704                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1705                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1706                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1707                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1708
1709                         /* save profile fields. */
1710                         int fieldCounter = 0;
1711                         for (Field profileField : profile.getFields()) {
1712                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1713                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1714                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1715                         }
1716                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1717
1718                         /* save posts. */
1719                         int postCounter = 0;
1720                         for (Post post : sone.getPosts()) {
1721                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1722                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1723                                 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1724                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1725                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1726                         }
1727                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1728
1729                         /* save replies. */
1730                         int replyCounter = 0;
1731                         for (PostReply reply : sone.getReplies()) {
1732                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1733                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1734                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1735                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1736                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1737                         }
1738                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1739
1740                         /* save post likes. */
1741                         int postLikeCounter = 0;
1742                         for (String postId : sone.getLikedPostIds()) {
1743                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1744                         }
1745                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1746
1747                         /* save reply likes. */
1748                         int replyLikeCounter = 0;
1749                         for (String replyId : sone.getLikedReplyIds()) {
1750                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1751                         }
1752                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1753
1754                         /* save friends. */
1755                         int friendCounter = 0;
1756                         for (String friendId : sone.getFriends()) {
1757                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1758                         }
1759                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1760
1761                         /* save albums. first, collect in a flat structure, top-level first. */
1762                         List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1763
1764                         int albumCounter = 0;
1765                         for (Album album : albums) {
1766                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1767                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1768                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1769                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1770                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1771                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1772                         }
1773                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1774
1775                         /* save images. */
1776                         int imageCounter = 0;
1777                         for (Album album : albums) {
1778                                 for (Image image : album.getImages()) {
1779                                         if (!image.isInserted()) {
1780                                                 continue;
1781                                         }
1782                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1783                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1784                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1785                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1786                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1787                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1788                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1789                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1790                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1791                                 }
1792                         }
1793                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1794
1795                         /* save options. */
1796                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1797                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1798                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1799                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1800                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1801                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1802
1803                         configuration.save();
1804
1805                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1806
1807                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1808                 } catch (ConfigurationException ce1) {
1809                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1810                 }
1811         }
1812
1813         /**
1814          * Saves the current options.
1815          */
1816         private void saveConfiguration() {
1817                 synchronized (configuration) {
1818                         if (storingConfiguration) {
1819                                 logger.log(Level.FINE, "Already storing configuration…");
1820                                 return;
1821                         }
1822                         storingConfiguration = true;
1823                 }
1824
1825                 /* store the options first. */
1826                 try {
1827                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1828                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1829                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1830                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1831                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1832                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1833                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1834                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1835                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1836                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1837                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1838                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1839
1840                         /* save known Sones. */
1841                         int soneCounter = 0;
1842                         synchronized (knownSones) {
1843                                 for (String knownSoneId : knownSones) {
1844                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1845                                 }
1846                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1847                         }
1848
1849                         /* save Sone following times. */
1850                         soneCounter = 0;
1851                         synchronized (soneFollowingTimes) {
1852                                 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1853                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1854                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1855                                         ++soneCounter;
1856                                 }
1857                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1858                         }
1859
1860                         /* save known posts. */
1861                         database.save();
1862
1863                         /* save bookmarked posts. */
1864                         int bookmarkedPostCounter = 0;
1865                         synchronized (bookmarkedPosts) {
1866                                 for (String bookmarkedPostId : bookmarkedPosts) {
1867                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1868                                 }
1869                         }
1870                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1871
1872                         /* now save it. */
1873                         configuration.save();
1874
1875                 } catch (ConfigurationException ce1) {
1876                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1877                 } catch (DatabaseException de1) {
1878                         logger.log(Level.SEVERE, "Could not save database!", de1);
1879                 } finally {
1880                         synchronized (configuration) {
1881                                 storingConfiguration = false;
1882                         }
1883                 }
1884         }
1885
1886         /**
1887          * Loads the configuration.
1888          */
1889         private void loadConfiguration() {
1890                 /* create options. */
1891                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1892
1893                         @Override
1894                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1895                                 SoneInserter.setInsertionDelay(newValue);
1896                         }
1897
1898                 }));
1899                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1900                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1901                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1902                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1903                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1904                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1905                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1906                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1907                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1908
1909                         @Override
1910                         @SuppressWarnings("synthetic-access")
1911                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1912                                 fcpInterface.setActive(newValue);
1913                         }
1914                 }));
1915                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1916
1917                         @Override
1918                         @SuppressWarnings("synthetic-access")
1919                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1920                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1921                         }
1922
1923                 }));
1924
1925                 loadConfigurationValue("InsertionDelay");
1926                 loadConfigurationValue("PostsPerPage");
1927                 loadConfigurationValue("ImagesPerPage");
1928                 loadConfigurationValue("CharactersPerPost");
1929                 loadConfigurationValue("PostCutOffLength");
1930                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1931                 loadConfigurationValue("PositiveTrust");
1932                 loadConfigurationValue("NegativeTrust");
1933                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1934                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1935                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1936
1937                 /* load known Sones. */
1938                 int soneCounter = 0;
1939                 while (true) {
1940                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1941                         if (knownSoneId == null) {
1942                                 break;
1943                         }
1944                         synchronized (knownSones) {
1945                                 knownSones.add(knownSoneId);
1946                         }
1947                 }
1948
1949                 /* load Sone following times. */
1950                 soneCounter = 0;
1951                 while (true) {
1952                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1953                         if (soneId == null) {
1954                                 break;
1955                         }
1956                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1957                         synchronized (soneFollowingTimes) {
1958                                 soneFollowingTimes.put(soneId, time);
1959                         }
1960                         ++soneCounter;
1961                 }
1962
1963                 /* load bookmarked posts. */
1964                 int bookmarkedPostCounter = 0;
1965                 while (true) {
1966                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1967                         if (bookmarkedPostId == null) {
1968                                 break;
1969                         }
1970                         synchronized (bookmarkedPosts) {
1971                                 bookmarkedPosts.add(bookmarkedPostId);
1972                         }
1973                 }
1974
1975         }
1976
1977         /**
1978          * Loads an {@link Integer} configuration value for the option with the
1979          * given name, logging validation failures.
1980          *
1981          * @param optionName
1982          *            The name of the option to load
1983          */
1984         private void loadConfigurationValue(String optionName) {
1985                 try {
1986                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1987                 } catch (IllegalArgumentException iae1) {
1988                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1989                 }
1990         }
1991
1992         /**
1993          * Notifies the core that a new {@link OwnIdentity} was added.
1994          *
1995          * @param ownIdentityAddedEvent
1996          *            The event
1997          */
1998         @Subscribe
1999         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2000                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2001                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2002                 if (ownIdentity.hasContext("Sone")) {
2003                         addLocalSone(ownIdentity);
2004                 }
2005         }
2006
2007         /**
2008          * Notifies the core that an {@link OwnIdentity} was removed.
2009          *
2010          * @param ownIdentityRemovedEvent
2011          *            The event
2012          */
2013         @Subscribe
2014         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2015                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2016                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2017                 trustedIdentities.removeAll(ownIdentity);
2018         }
2019
2020         /**
2021          * Notifies the core that a new {@link Identity} was added.
2022          *
2023          * @param identityAddedEvent
2024          *            The event
2025          */
2026         @Subscribe
2027         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2028                 Identity identity = identityAddedEvent.identity();
2029                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2030                 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2031                 addRemoteSone(identity);
2032         }
2033
2034         /**
2035          * Notifies the core that an {@link Identity} was updated.
2036          *
2037          * @param identityUpdatedEvent
2038          *            The event
2039          */
2040         @Subscribe
2041         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2042                 final Identity identity = identityUpdatedEvent.identity();
2043                 soneDownloaders.execute(new Runnable() {
2044
2045                         @Override
2046                         @SuppressWarnings("synthetic-access")
2047                         public void run() {
2048                                 Sone sone = getRemoteSone(identity.getId(), false);
2049                                 if (sone.isLocal()) {
2050                                         return;
2051                                 }
2052                                 sone.setIdentity(identity);
2053                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2054                                 soneDownloader.addSone(sone);
2055                                 soneDownloader.fetchSone(sone);
2056                         }
2057                 });
2058         }
2059
2060         /**
2061          * Notifies the core that an {@link Identity} was removed.
2062          *
2063          * @param identityRemovedEvent
2064          *            The event
2065          */
2066         @Subscribe
2067         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2068                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2069                 Identity identity = identityRemovedEvent.identity();
2070                 trustedIdentities.remove(ownIdentity, identity);
2071                 boolean foundIdentity = false;
2072                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2073                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2074                                 continue;
2075                         }
2076                         if (trustedIdentity.getValue().contains(identity)) {
2077                                 foundIdentity = true;
2078                         }
2079                 }
2080                 if (foundIdentity) {
2081                         /* some local identity still trusts this identity, don’t remove. */
2082                         return;
2083                 }
2084                 Optional<Sone> sone = getSone(identity.getId());
2085                 if (!sone.isPresent()) {
2086                         /* TODO - we don’t have the Sone anymore. should this happen? */
2087                         return;
2088                 }
2089                 database.removePosts(sone.get());
2090                 for (Post post : sone.get().getPosts()) {
2091                         eventBus.post(new PostRemovedEvent(post));
2092                 }
2093                 database.removePostReplies(sone.get());
2094                 for (PostReply reply : sone.get().getReplies()) {
2095                         eventBus.post(new PostReplyRemovedEvent(reply));
2096                 }
2097                 synchronized (sones) {
2098                         sones.remove(identity.getId());
2099                 }
2100                 eventBus.post(new SoneRemovedEvent(sone.get()));
2101         }
2102
2103         /**
2104          * Deletes the temporary image.
2105          *
2106          * @param imageInsertFinishedEvent
2107          *            The event
2108          */
2109         @Subscribe
2110         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2111                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2112                 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2113                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2114                 touchConfiguration();
2115         }
2116
2117 }