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