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