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