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