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