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