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