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