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